Home / AI Architecture & System Design / RAG & Retrieval

RAG & RetrievalSeniorQuestion 7 of 12

How do you enforce document permissions in RAG?

30-second answer

Store ACL metadata (tenant, groups, document IDs) with each chunk and filter at retrieval time using the caller's identity, never relying on the LLM to withhold information. Use a vector store that supports efficient filtered search, keep ACLs in sync with the source system, and test for leakage in evals. Per-tenant indexes are an option for strong isolation.

Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.

New to these terms? 15 terms on this page are explained in the glossary

0–5 min Functional requirements

Treat this as a security design problem. Start by understanding the permission model you need to mirror.

You What does the permission model look like in the source systems? Per-document ACLs, groups, nested groups?

Interviewer SharePoint and Jira. Mostly group-based, with nested groups, plus some documents shared with individual people.

You Is this one company, or a multi-tenant product serving many customers?

Interviewer Multi-tenant SaaS. Each customer is a tenant with its own users and documents.

You How quickly must a permission change take effect? For example, someone is removed from the HR group.

Interviewer Within a few minutes. For terminated employees, immediately.

You Do we need to show who accessed what?

Interviewer Yes. Security teams will ask for audit logs.

# Functional requirement Why it matters
F1 Retrieval returns only chunks the asking user can open in the source system The core guarantee
F2 Strict tenant isolation: no tenant can ever retrieve another's data Cross-tenant leaks are catastrophic
F3 Support group, nested-group and per-user grants Mirrors real source permissions
F4 Apply permission changes within minutes; account disablement immediately Revocations matter more than grants
F5 Audit log of which documents were retrieved for which user and question Security reviews and incident response
F6 Derived data (caches, summaries, conversation memory) follows the same permissions Leaks often happen through side channels

Out of scope: managing permissions (the source systems own them) and field-level redaction inside documents.

5–10 min Non-functional requirements and estimates

You I'll state the most important requirement explicitly: the model must never see a chunk the user can't read. Anything in the context window can end up in the answer, through a mistake or prompt injection, so enforcement happens before generation.

Interviewer Agreed. What else?

Requirement Target What it forces in the design
Leakage Zero, verified by automated tests on every release Filtering inside retrieval; leak-test suite
Revocation latency Group or document changes ≤ 5 min; disabled accounts immediately Event-driven sync; identity checks on every request
Latency overhead Permission handling adds ≤ 30 ms p95 Cached group resolution; filter-aware vector search
Recall under filters No large drop in recall@k for users with narrow access Pre-filtering or filter-aware search, not post-filtering
Isolation Tenant boundary enforced by design, not just by a query parameter Namespaces or separate indexes per tenant
Auditability Every retrieval logged with user, tenant and doc IDs Append-only audit stream

Back-of-envelope estimates:

  • Users and groups: a large tenant has 50,000 users, each in ~150 groups on average, with some power users in 2,000+ groups through nesting.
  • Chunks: a large tenant has ~10M chunks; the whole platform ~500M across tenants.
  • ACL metadata: if each chunk lists ~5 group IDs as 8-byte integers, that's ~40 bytes per chunk, ~400 MB for a large tenant. Small compared with vectors.
  • Permission events: a large tenant might see ~10,000 group-membership and sharing changes a day, with bursts during reorganizations.
  • Selectivity: an intern may be able to read 2% of a tenant's chunks; a director 60%. The design must work well at both ends.

10–18 min High-level design

You Three pieces work together: resolving who the user is and which groups they belong to, filtering inside the search using those groups, and keeping each chunk's ACL in sync with the source.

Scroll sideways to see the whole diagram.

Permission-aware retrievalComponents: Identity provider (user → groups); Employee; RAG API (resolve caller groups); Filtered search (acl ∩ user groups); Permission re-check (sensitive docs only); LLM (permitted chunks only); Index (chunks + ACL metadata); Audit log (who retrieved what); Source systems (SharePoint · Jira); ACL sync (events + nightly reconcile). Flow: Employee to RAG API; RAG API to Identity provider (groups); RAG API to Filtered search; Filtered search to Index; Filtered search to Permission re-check; Permission re-check to LLM; Permission re-check to Audit log (log); Source systems to ACL sync; ACL sync to Index (update ACLs).ACL SYNCIdentity provideruser → groupsEmployeeRAG APIresolve caller groupsFiltered searchacl ∩ user groupsPermission re-checksensitive docs onlyLLMpermitted chunks onlyIndexchunks + ACL metadataAudit logwho retrieved whatSource systemsSharePoint · JiraACL syncevents + nightlyreconcilegroupslogupdate ACLs
Permission-aware retrieval. The caller's groups are resolved from the identity provider and applied as a filter inside the search, so the model only ever sees permitted chunks. ACLs are kept in sync from source systems.

Components:

  • Identity provider (IdP): source of users and group memberships, including nested groups.
  • RAG API: authenticates the request, resolves the user's effective groups (expanded and cached for a few minutes), and passes them to search.
  • Index: per-tenant namespace; each chunk carries tenant_id, doc_id, acl_groups, acl_users and acl_version.
  • Filtered search: hybrid retrieval whose candidate set is restricted to chunks where acl_groups ∩ user_groups ≠ ∅ or the user is listed directly.
  • Permission re-check: for sensitive sources, verify the final few chunks against the source system's API before generation.
  • ACL sync: consumes permission-change events from sources, updates chunk metadata, and reconciles nightly.
  • Audit log: records user, question hash, retrieved doc IDs and their ACL versions.

Request flow:

  1. Authenticate and confirm the account is active (no caching for this check).
  2. Resolve effective groups from the cache, falling back to the IdP.
  3. Run the search within the tenant's namespace with the group filter.
  4. For sensitive sources, re-check the top chunks with the source API.
  5. Send only permitted chunks to the model; log the retrieval to the audit stream.

How ACL changes reach the index:

Scroll sideways to see the whole diagram.

How permission changes reach the index[membership change]; Identity provider → ACL sync: user removed from HR; ACL sync → Group cache: invalidate user's groups; [document sharing change]; Source system → ACL sync: webhook: ACL changed; ACL sync → Source system: fetch current ACL; Source system → ACL sync: groups + users; ACL sync → Index: update ACL metadata (no re-embed); [nightly]; ACL sync: reconcile all ACLs; ACL sync → Index: fix drift; [next query]; RAG API → Identity provider: account still active?; RAG API → Group cache: effective groups; Group cache → RAG API: fresh groups; RAG API → Index: search with group filter.Source systemSharePoint · JiraIdentity providerACL syncGroup cacheTTL 2–5 minIndexchunk ACLsRAG APIMEMBERSHIP CHANGEuser removed from HRinvalidate user's groupsDOCUMENT SHARING CHANGEwebhook: ACL changedfetch current ACLgroups + usersupdate ACL metadata (no re-embed)NIGHTLYreconcile all ACLsfix driftNEXT QUERYaccount still active?effective groupsfresh groupssearch with group filter
How permission changes reach the index. A group-membership change invalidates the user's cached groups at once. A document sharing change updates chunk ACL metadata without re-embedding. A nightly reconcile fixes anything missed. Every query checks the account is active and searches with fresh groups.

How it works: a worked example

A study aid: the same question asked by two employees with different access, then a permission revoked, traced through identity resolution, filtered search and audit.

The document: drive:Q4-board-deck (tenant acme), chunks carry acl_groups: ["exec-team"], acl_version: 12.

Question from Lee (an executive): "What revenue target did we set for Q4?"

  1. Authenticate; confirm Lee's account is active (checked live, never cached).
  2. Resolve effective groups (expanded nested groups, cached 5 minutes): ["all-staff", "sales", "exec-team"] → group IDs [101, 205, 999].
  3. Search inside the acme namespace with the filter applied during the ANN search:
{ "namespace": "acme", "query_vector": [...], "k": 50,
  "filter": { "or": [ { "acl_groups": { "any_of": [101, 205, 999] } }, { "acl_users": { "contains": "u_lee" } } ] } }
  1. drive:Q4-board-deck#4 is in the results. Because Drive is marked sensitive, the top 5 chunks are re-checked against the Drive permissions API (~40 ms) before the prompt is built. All pass.
  2. Audit event: { user: u_lee, tenant: acme, q_hash: 7f2…, doc_ids: [drive:Q4-board-deck#4, …], acl_versions: [12, …] }.

Same question from Ana (sales, no exec access): groups [101, 205]. The filter excludes every chunk of the board deck during search, so the model never sees it. Ana's answer: "I couldn't find a Q4 revenue target in documents you have access to." No hint that a restricted document exists.

Revocation. At 16:00 an admin removes Lee from exec-team.

  1. The identity provider emits a group-change event; the permission service drops Lee's cached group set immediately (not waiting for the 5-minute TTL).
  2. Lee's next question resolves to [101, 205], so the deck disappears from his results within seconds.
  3. If instead the document's sharing changes, the Drive connector's change event updates acl_groups on all its chunks (a metadata update, no re-embedding) and bumps acl_version to 13. A nightly reconciliation compares every document's ACL with the source and fixes drift.

The leak test that runs on every release: a synthetic tenant with planted documents (canary-secret-123 visible only to group G-secret) and test users in and out of that group; any answer or retrieval containing the canary for an unauthorized user fails the build.

Where each piece runs:

Component Runs as Example technology If it fails
Identity / group resolution Permission service + cache IdP (Okta/Entra) + Redis cache with event-driven invalidation Fail closed: only public documents
Index with ACL metadata Per-tenant namespaces in a vector + keyword store with filtered search OpenSearch, Vespa, Pinecone namespaces, pgvector with row filters No results rather than unfiltered results
Source re-check Calls to source APIs for sensitive sources Drive/SharePoint/Confluence permission APIs Drop chunks that can't be verified
ACL sync Event consumers + nightly reconciliation job Webhooks → queue → workers Lag alert; reconciliation catches drift
Audit log Append-only stream Kafka → warehouse with restricted access Alert; consider pausing sensitive sources

18–32 min Deep dive

You The interesting parts are group resolution, making filtered vector search fast and accurate, revocation, and testing that nothing leaks.

Interviewer Start with filtered search. Why not just filter the results after searching?

There are three strategies:

Strategy How Problem
Post-filter Retrieve top 50, then drop forbidden ones A user with narrow access may get 0–2 results; the index "wasted" its candidates on forbidden chunks
Pre-filter Find permitted chunks first, then search only them Can be slow; very selective filters can break HNSW graph traversal
Filter-aware search The ANN index checks the filter during graph traversal Best of both; needs database support

I'd use a vector database with filter-aware HNSW, plus a fallback: when the filter matches fewer than ~20,000 chunks, use exact (brute-force) search on that set, which is fast at that size and has perfect recall.

Making the filter cheap: don't send 2,000 group IDs as a giant OR clause. Options:

  • Map groups to compact integer IDs and store ACLs as small integer arrays with an index.
  • For the largest tenants, precompute a bitset of permitted chunks per group, and OR the user's group bitsets at query time.

Deep dive 2 · Group resolution

  • Nested groups: expand membership transitively at sync time and cache user → effective groups with a short TTL (2–5 minutes).
  • Too many groups for a token: identity tokens often can't hold thousands of group claims, so resolve server-side rather than trusting the token's group list.
  • Disabled accounts: check account status on every request against the IdP or a revocation list that's pushed instantly. Never rely on the group cache for this.
  • Per-user shares: store them as acl_users on the chunk; the filter becomes groups ∩ user_groups ≠ ∅ OR user_id ∈ acl_users.

Interviewer Someone is removed from the HR group at 10:00. When can they no longer see HR documents?

Deep dive 3 · Revocation and freshness

  • The IdP sends a membership-change event; the group cache for that user is invalidated immediately. From the next request on (seconds), their effective groups exclude HR.
  • Document-level changes (a page's sharing settings change) arrive as source webhooks; ACL sync updates that document's chunks within minutes, without re-embedding.
  • Nightly reconciliation compares source ACLs with index ACLs and fixes drift from missed events.
  • Re-check for sensitive sources: for HR, legal and finance spaces, verify the final chunks against the source API at query time. It adds ~50–100 ms but closes the gap between a change and the sync.
  • Derived data: answer caches are keyed by user (or permission set), conversation memory is per user, and any stored summary of a document carries the document's ACL.

Deep dive 4 · Proving there are no leaks

  • Leak-test suite: synthetic users with known, narrow permissions run hundreds of questions designed to surface restricted documents ("what is the CEO's salary?", "summarize the layoff plan"). Assert that no restricted doc_id appears in retrieval results, not just in answers.
  • Canary documents: plant restricted documents with unique phrases; alert if any retrieval for an unauthorized user ever returns them.
  • Tenant isolation tests: the same queries across tenants must never cross namespaces.
  • Audit review: sample audit logs and verify retrieved documents against source permissions offline.

Tenant isolation options

Scroll sideways to see the whole diagram.

Two ways to isolate tenantsComponents: Query (tenant A); Shared index (all tenants, filtered by tenant_id); Query (tenant A); Tenant router (tenant → namespace); Tenant A index (namespace); Tenant B index (unreachable). Flow: Query to Shared index (WHERE tenant_id = A); Query to Tenant router; Tenant router to Tenant A index (only A).OPTION 1 · SHARED INDEXOPTION 2 · NAMESPACE PER TENANTQuerytenant AShared indexall tenants, filtered by tenant_idQuerytenant ATenant routertenant → namespaceTenant A indexnamespaceTenant B indexunreachableWHERE tenant_id = Aonly ASimple and cheap to run.Risk: one missing filter crosses tenants.A's request can't reach B's data.Easy deletion; more indexes to operate.
Two ways to isolate tenants. A shared index relies on every query including the tenant filter. A namespace per tenant makes cross-tenant access impossible by construction and makes deleting a tenant easy, at the cost of running more indexes.

32–37 min Trade-offs

Decision Chosen Alternative Why
Where to enforce Inside retrieval, before the model In the prompt, or after generation Anything in context can leak
Filtering Filter-aware ANN + brute force for small sets Post-filtering Recall for users with narrow access
Tenant isolation Namespace per tenant (separate index for the largest or regulated tenants) One shared index with a tenant filter A missing filter can't cross tenants; easy per-tenant deletion
Group cache Short TTL + event invalidation No cache, or long TTL Latency vs. revocation speed
Sensitive sources Re-check against source at query time Trust the synced ACLs Closes the sync gap where it matters most
Permission changes Metadata update only Re-index documents Fast and cheap

Build first: tenant namespaces, ACL metadata with filter-aware search, group resolution with event invalidation, and the leak-test suite. Then source re-checks for sensitive spaces and bitset optimizations for large tenants.

37–40 min Wrap-up and likely follow-ups

Close with: "The model only sees chunks the user can read: each chunk carries its source ACL, the user's groups are resolved and cached briefly, and filter-aware search applies them inside retrieval. Revocations flow through events within minutes, disabled accounts are checked every request, sensitive sources are re-checked live, and leak tests run on every release."

Likely follow-ups:

  • What about fine-tuning on private documents? Model weights can't enforce ACLs; don't fine-tune shared models on restricted content.
  • Field-level permissions, like salary columns? Split restricted fields into separate chunks with stricter ACLs, or redact them at ingestion.
  • How do you handle a source that doesn't send webhooks? Poll with change cursors more often for sensitive sources and rely on query-time re-checks.
  • Shared links ("anyone with the link")? Treat them as not visible unless the user has actually opened the link, or exclude them; ask the security team which.

What interviewers listen for

  • "Enforce before the model sees it" as the principle.
  • Understanding why post-filtering hurts recall, and how filtered ANN works.
  • Revocation timing, disabled accounts and nightly reconciliation.
  • Leak testing and audit, not just design.

Red flags

  • "Tell the model not to reveal restricted documents."
  • Post-filtering with no thought about recall.
  • Ignoring caches, summaries and conversation memory as leak paths.

Discussion

Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.