Design a RAG-Powered Internal Knowledge Assistant
System DesignModel answerLast updated
Architect a multi-turn chatbot that retrieves answers from internal docs using RAG, enforces per-user access controls, and handles traffic spikes under a 2-second latency budget.
Context
Your company wants to replace the "search and hope" workflow for internal documentation. Employees currently dig through wikis, project trackers, and ticket archives to find answers. The goal is a conversational assistant that understands follow-up questions, grounds every answer in real documents, and respects the fact that not everyone is allowed to read everything.
Functional Requirements
- Employees ask questions in natural language and get responses that cite specific internal documents.
- The assistant remembers what was said earlier in a conversation for at least 10 minutes.
- When the system is not confident in its answer, it routes the conversation to a human support agent rather than guessing.
- Answers must never be fabricated — every claim must be traceable to a document the user is authorized to see.
Non-Functional Requirements
- Latency: first token of the response within 2 seconds at p95, with the rest streamed.
- Concurrency: 10,000 simultaneous users across global time zones; plan for 5–10x spikes during company-wide events.
- Correctness: minimize hallucinations by strictly grounding the model in retrieved context.
- Security: a user must never receive content from a document they lack permission to access — even indirectly through timing signals or result counts.
What to Cover
Produce a high-level architecture design that addresses:
- Ingestion pipeline — how documents get chunked, embedded, and indexed, including how ACL metadata flows into the index.
- Retrieval and inference pipeline — the full path from a user's typed question to a streamed, cited answer, including how multi-turn context is handled.
- Storage schemas — how you store conversation state and document embeddings; what databases you choose and why.
- Access control strategy — how you enforce document-level permissions inside the retrieval step, not just at the API boundary.
- Post-deployment monitoring — how you detect when answer quality or retrieval relevance degrades over time.
You are expected to state your assumptions, justify your component choices, discuss trade-offs, and flag the trickiest failure modes.
Hints
Hint 1
Start by sizing the problem: estimate corpus size in chunks, embedding storage in GB, steady-state QPS, and peak QPS. Interviewers watch whether you anchor decisions in numbers or just name technologies.
Hint 2
Access control is the hardest sub-problem. Think about where filtering happens — pre-filter inside the ANN search vs. post-filter after retrieving top-k — and what goes wrong in each case when a user's permissions are very restrictive.
Hint 3
A 2-second latency target covers several sequential steps. Sketch a latency budget that allocates time to auth, query rewriting, embedding, retrieval, reranking, and LLM time-to-first-token. That budget exposes which steps need caching or can run in parallel.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. State Your Assumptions First
Interviewers reward candidates who make assumptions explicit before drawing boxes.
- Corpus: ~10M documents (wiki pages, tickets). Chunked at ~500 tokens → ~100M chunks.
- Embeddings: 1024-dim float32 = 4 KB/chunk → 400 GB raw. Int8 quantization brings this to ~100 GB, fitting a sharded vector cluster.
- Steady-state load: 10k concurrent users × ~1 query/min = ~170 QPS.
- Peak load: 5–10x spike → ~1–2k QPS. Plan for this with autoscaling, not permanent over-provisioning.
- Latency definition: "under 2 s" means time-to-first-token at p95. Streaming the rest is fine. A full 300-token generation in 2 s at p99 is not achievable with today's GPU inference — confirm this interpretation early.
2. Latency Budget
Decomposing the budget forces precision and reveals where to focus optimization effort.
| Step | Budget |
|---|---|
| Auth + ACL resolution (cached) | 20 ms |
| Query rewrite (small model, uses conversation history) | 150 ms |
| Query embedding | 30 ms |
| Hybrid retrieval (vector + BM25) | 80 ms |
| Reranking top-50 candidates | 120 ms |
| LLM time-to-first-token | 600 ms |
| Remaining headroom | ~1 s |
Steps 3–5 can run in parallel once query rewriting completes.
3. Architecture Overview
Ingestion path: Source systems (wiki, ticket tracker) emit change events to a Kafka topic. Ingestion workers fetch documents, clean and chunk the text, extract effective ACLs (space + page-level, with inheritance), embed chunks in GPU batch jobs, and write to three stores: a vector DB (embedding + ACL metadata), a BM25 index (keyword search), and an object store + Postgres for raw text and document metadata used for idempotent re-indexing and deletes.
Serving path:
- Client sends a message → API Gateway authenticates via SSO/OIDC and rate-limits.
- A stateless Chat Orchestrator loads the session from Redis, rewrites the follow-up into a standalone query using the last few turns, and calls the ACL service to expand the user into their group memberships.
- The Retrieval service runs permission-filtered hybrid search (ANN + BM25), merges results by Reciprocal Rank Fusion, then runs a cross-encoder reranker on the top 50 candidates.
- The Orchestrator builds a prompt: system instructions ("answer only from the provided context, cite chunk IDs, say 'I don't know' if the context is insufficient"), a rolling conversation summary, then the top-k chunks.
- The LLM Gateway streams tokens back to the client. Simultaneously, a post-generation groundedness check runs an NLI pass to verify the answer is entailed by the cited chunks.
- The completed turn is persisted to Redis (for session continuity) and asynchronously to Postgres (for audit and evaluation).
4. Storage Schemas
Session state (Redis Cluster, sharded by session_id):
session:{id} HASH {user_id, created_at, handoff_state, rolling_summary}
session:{id}:turns LIST [{role, text, cited_chunk_ids, timestamp}] (capped at last 6 turns)
TTL is refreshed to 15 minutes on every write (satisfying the 10-minute requirement). Losing Redis degrades experience but loses no permanent data — full transcripts live in Postgres.
Vector index (Milvus, Vespa, or OpenSearch k-NN):
chunk_id, doc_id, source, space_key,
embedding (int8, 1024-dim, HNSW index),
text, title, url, updated_at, doc_version,
allowed_principals: [group/user IDs],
is_org_public: bool
Postgres tracks doc_id → version, ACL hash, chunk_ids for change detection. Permission-change webhooks trigger a metadata-only update on affected chunks — no re-embedding needed.
5. Access Control — The Hardest Part
Never post-filter only. If you retrieve the top 50 chunks and then drop the ones the user cannot see, two things go wrong: (a) recall collapses when the user has narrow permissions, and (b) result count and latency variation leak information about the existence of restricted documents.
Correct approach — pre-filter inside ANN traversal:
- At ingestion, denormalize the effective ACL onto every chunk as
allowed_principals. - At query time, the ACL service returns the user's expanded principal set (user ID + all groups), cached in Redis for ~5 minutes and invalidated on group-change events.
- The vector search runs with a filter:
allowed_principals ∩ user_principals ≠ ∅ OR is_org_public. Use an engine that supports filtered HNSW graph traversal. For very selective filters, fall back to exact search over the filtered subset — acceptable because the filtered set is small.
Defense in depth: before returning citations to the client, batch-check the final chunk IDs against the source system's permission API (or a synced permission cache). This catches ACL changes that have not yet propagated to the index.
Cache isolation: prompt caches and answer caches must be keyed by the user's permission scope hash, not just the query text. Sharing a cache entry across users with different permissions leaks data.
6. Confidence Scoring and Human Handoff
Confidence is a composite signal:
- Top reranker score and the gap between first and second result (low gap = ambiguous retrieval).
- NLI groundedness score: are the answer sentences entailed by the cited chunks?
- Citation validity: every cited chunk ID must appear in the prompt context.
- An explicit "insufficient context" signal embedded in the LLM's output format.
When confidence falls below the threshold, do not present a low-confidence answer as fact. Instead: surface the best-effort retrieved links, tell the user you are connecting them to a human agent, and publish a handoff_requested event (session ID, transcript, retrieved docs, inferred topic) to a queue consumed by a live-agent console. The handoff service attaches the full conversation context so the agent does not start cold.
7. Post-Deployment Monitoring
Catching drift requires both system-level and answer-quality signals:
- Retrieval health: track mean reranker score, the fraction of queries returning fewer than 3 results after filtering (signals overly restrictive ACLs or a stale index), and index staleness (time since last ingestion run per source).
- Answer quality: run an async LLM-as-judge eval on a sample of turns, scoring groundedness and relevance against the cited chunks. Alert when weekly mean drops by more than ~0.05.
- User signals: thumbs-up/down ratings and handoff rate are cheap proxies for satisfaction. A rising handoff rate often surfaces retrieval gaps before eval scores move.
- Infrastructure: p95 latency per pipeline stage (so you can tell whether a regression is in retrieval vs. LLM), GPU utilization, and Redis memory pressure.
Common Mistakes
- Enforcing ACLs only at the API layer and returning forbidden content as part of a grounded answer.
- Setting a hard 2-second end-to-end target without streaming, which is effectively impossible with a large LLM.
- Storing full conversation history in the session without summarization — at turn 20 the context window fills up and costs spike.
- Forgetting that caches (prompt, answer, ANN result) must be permission-scoped.
- Conflating "the model said it" with "it is grounded" — always run a separate groundedness check rather than trusting the model to self-police hallucinations.