Design a RAG-Powered Knowledge Assistant with Access Control
Machine LearningModel answerLast updated
Architect a retrieval-augmented generation system that answers natural language queries over heterogeneous internal documents with strict permissions, low latency, and near-real-time freshness.
Scenario
Your company runs an internal knowledge platform used by hundreds of engineers every day. The corpus spans product wikis, project-management tickets, and team chat archives — thousands of documents in total, updated continuously throughout the day.
You have been asked to design an intelligent assistant that lets engineers ask plain-language questions and receive synthesized answers, with citations. Some documents are sensitive and visible only to specific teams or channels, so the system must enforce those restrictions without exception.
Requirements
Functional
- Accept natural-language questions from authenticated users.
- Retrieve relevant content from multiple source types and synthesize a coherent answer.
- Support multi-step reasoning: the agent may need to look up one piece of information before knowing what to look for next.
- Enforce per-user access restrictions — users must never see content they are not authorized to view.
Non-Functional
- Latency: time-to-first-token must be under 1 second at the 95th percentile.
- Freshness: any document edit must be searchable within 5 minutes. Access-control changes must propagate at least as fast.
- Scale: the system must sustain 500 requests per second, with documents ranging from a few sentences to many pages.
What Your Design Should Cover
- Ingestion pipeline — how documents from different sources are collected, split, enriched, and embedded, including incremental update handling.
- Retrieval layer — how you combine vector and keyword search, and how access control is enforced without leaking information.
- Agent orchestration — how the system decides whether one retrieval round is enough or whether additional hops are needed, given the hard latency target.
- Evaluation strategy — how you measure retrieval quality and answer quality in a way that is actionable.
You are not expected to write code. Walk through each component, call out the tensions between requirements, and justify your trade-offs.
Hints
Hint 1
Start by writing down a latency budget — divide the 1-second target across auth, retrieval, reranking, and generation. This immediately shows you how many sequential LLM calls you can afford before the first token.
Hint 2
Think carefully about where access control is enforced. Post-filtering after retrieval is tempting but creates correctness and information-leakage problems. Consider pre-filtering and why it has its own recall pitfalls, and what you do about both.
Hint 3
Distinguish the common case from the multi-hop case. Most questions need one retrieval round; designing everything around the agentic path will blow your latency budget. A router that classifies query complexity early lets you serve the two cases differently.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What This Question Is Really Testing
Three hard constraints pull against each other here: security (no unauthorized content, ever), latency (under 1 s to first token), and reasoning quality (multi-hop answers). A strong answer names those tensions up front, gives each pipeline stage a concrete time budget, and treats an ACL violation as a correctness bug — not a configuration detail.
Step 1: Clarify and Estimate
Before drawing any boxes, ask:
- What is the rough corpus breakdown across wikis, tickets, and chat?
- What fraction of content is restricted versus public?
- Do answers need citations? (Yes, almost always for internal tooling.)
- Does the 5-minute freshness window apply to ACL changes too, or only document edits? (It should apply to both — revoking access must propagate quickly.)
Back-of-envelope numbers (say these out loud):
| Item | Estimate |
|---|---|
| Wiki pages | ~50K → ~500K chunks |
| Tickets | ~2M → ~4M chunks |
| Chat threads | ~20M → ~40M chunks |
| Total chunks | ~45M |
| Dense vectors (fp32) | 45M × 768 × 4B ≈ 140 GB |
| After int8 quantization | ~35–50 GB, fits on a few nodes |
| Index QPS needed | 500 RPS × ~2.5 retrieval calls × 2 (dense + BM25) ≈ 2,500 QPS |
TTFT budget (p95 < 1 s):
| Stage | Budget |
|---|---|
| Auth + principal lookup (cached) | ~15 ms |
| Query router / rewrite (small model) | ~100 ms |
| Parallel hybrid retrieval | ~70 ms |
| Cross-encoder rerank of top 50 | ~90 ms |
| LLM prefill (~6K tokens, prefix-cached prompt) | ~350 ms |
| Headroom | ~375 ms |
The critical implication: there is budget for at most one sequential LLM hop before the first token. Any design that plans on two or three serial reasoning steps before generating will fail the SLO.
Step 2: Ingestion Pipeline
Event-driven ingestion via webhooks and change-data capture feeds into per-source Kafka topics. Stateless consumer workers chunk, enrich, and batch-embed documents, then upsert into both the vector index and a BM25 index.
Source-aware chunking:
- Wikis: split on headings at 300–500 tokens with small overlap; prepend the breadcrumb path as a contextual header before embedding so the vector carries positional semantics.
- Tickets: combine title, description, and resolution comment into one chunk; keep status and version as filterable metadata.
- Chat threads: chunk at thread granularity, not individual messages; prefix with channel name and date; drop low-signal threads.
Incremental updates use a deterministic chunk_id = hash(doc_id, section_path) plus a version counter. An edit upserts changed chunks and tombstones stale ones. New writes land in a small mutable delta segment that is searched alongside the large immutable segments, then compacted on a schedule. Target p99 ingest lag under 2 minutes with alerting on consumer lag.
ACL changes are separate lightweight events that update metadata only — no re-embedding needed — so they propagate in seconds.
Step 3: Retrieval and Access Control
Hybrid search matters here because internal corpora are dense with exact identifiers: error codes, service names, ticket IDs. Pure vector search misses exact-match queries; pure keyword search misses paraphrases. Run BM25 and dense ANN (HNSW) in parallel, fuse with Reciprocal Rank Fusion (no score calibration needed), then rerank the top ~50 with a cross-encoder. Apply mild post-rerank boosts for recency and source authority (official wiki > chat).
ACL enforcement is the hardest part:
- Pre-filter inside the ANN search on
acl_principals ∩ user_principals ≠ ∅. Never rely solely on post-filtering — it leaks information through result counts and timing side-channels, and it can return empty results when most top-k hits are restricted. - Pre-filtering on HNSW hurts recall when the filter is highly selective. Mitigate by partitioning the index by sensitivity tier: one large shard for public content, smaller shards for restricted projects and channels. Fall back to brute force on small partitions where HNSW's graph structure breaks down.
- At generation time, re-verify each chunk against the live ACL service before it enters the prompt. This defense-in-depth step handles index staleness.
- Never pass unauthorized text to the LLM, even with prompt-level instructions to ignore it. Prompt instructions are not access control.
A principals service maps user_id → {groups, channels}. Cache it aggressively with a short TTL and invalidate on ACL change events.
Step 4: Agent Orchestration
A naïve ReAct loop (plan → retrieve → reflect → retrieve again) can produce better multi-hop answers but easily consumes 3–5 seconds. The solution is a tiered architecture.
Tier 1 — Router (small model, ~100 ms): classifies the query as simple lookup or multi-hop, emits rewritten sub-queries, and identifies target sources.
Tier 2 — Fast path (~70% of traffic): all sub-queries fan out in parallel across sources; results merge, rerank, and flow into a single generation call. This path comfortably fits within the 1 s SLO.
Tier 3 — Agentic path: the first retrieval hop still uses the router's parallel plan, so no extra LLM call happens before the first token. The generator has access to tools (search, get_ticket, get_doc) and may request additional data if a sufficiency check fails — for example, a referenced ticket ID was never fetched, or key entities are missing. Cap the loop at 3 steps and a token budget. Stream status events to the client immediately ("Searching tickets for INFRA-1234…") so users see progress. The agentic path gets a separate, looser SLO.
When to stop: stop fetching when the model judges the evidence sufficient, the step cap is hit, or new retrievals return chunks already seen. If evidence remains insufficient, answer with what is known and explicitly state what is missing rather than hallucinating.
Serving optimizations: prefix-cache the system prompt and tool schemas; use speculative decoding; run the router on a distilled model; cache final answers in a semantic cache keyed on (normalized query, principal-set hash) — including the principal hash is mandatory to prevent cross-user cache hits that leak restricted content.
Step 5: Evaluation
Retrieval quality:
- Build a golden set of ~1–2K questions with labeled relevant chunks, mined from resolved support threads.
- Track Recall@k (most important — the reranker cannot recover misses), nDCG@10, and MRR.
- Slice by source type and query type to surface blind spots.
Generation quality:
- Faithfulness/groundedness: are all claims supported by cited chunks?
- Answer correctness against reference answers.
- Citation precision and recall.
- Refusal rate on out-of-scope or unauthorized questions.
- Use an LLM judge, but calibrate it against human labels on a held-out sample — LLM judges have systematic biases toward length and confident tone.
Online signals: thumbs-up/down per answer, escalation rate (user immediately asks the same question differently), and latency percentiles split by fast vs. agentic path.
Common Mistakes to Avoid
- Relying on post-filtering for ACLs — it leaks and breaks recall.
- Designing the happy path around multi-hop reasoning without a latency budget — the 1 s constraint makes sequential hops almost impossible before the first token.
- Chunking chat message-by-message instead of thread-by-thread — individual messages lose conversational context and inflate the index.
- Using a single monolithic HNSW index without sensitivity partitioning — filtered search on a highly selective predicate degrades rapidly.
- Treating evaluation as an afterthought — without a golden retrieval set, you cannot tell whether a bad answer is a retrieval failure or a generation failure.