How would you design a retrieval-augmented question answering system over a company's internal documents? As part of the prompt budget, if the model has an 8,000-token context window, 1,000 tokens are reserved for system instructions and the user question, and 500 tokens are reserved for the answer, how many 400-token chunks fit?

ML system design, Case studies
Level L4 Advanced. Length Long. Nature Th+Mat Both.

What's being asked

Whether you can architect an end-to-end retrieval-augmented generation (RAG) pipeline that respects enterprise permissions, handles stale documents, stays within a token budget, evaluates retrieval separately from generation, and defends against prompt injection.

Key idea

Separate the problem into offline document ingestion (parsing, chunking, embedding, indexing with access metadata) and online retrieval-plus-generation (hybrid sparse-and-dense search, re-ranking, strict permission filtering before prompting, and citation-grounded generation). The chunk budget is ⌊(8,000−1,000−500)/400⌋=⌊6,500/400⌋=16 chunks, and retrieved text must always be treated as untrusted data.

Steps

  1. Clarify requirements and scale: establish corpus size (for example, 1 million internal PDFs, wikis and tickets), query volume in QPS (queries per second), latency target (such as p95, or 95th-percentile, end-to-end latency under 2 seconds), freshness expectations (minutes for incident docs, hours for wikis), and strict document-level ACL (access control list) enforcement.
  2. Define the ML objective and metrics: measure retrieval and generation separately offline. For retrieval, track recall@k (fraction of queries where a gold supporting chunk appears in the top k results; note that the metric formula is covered separately in the bank) and MRR (mean reciprocal rank). For generation, track faithfulness (claims supported by cited chunks), answer correctness, and abstention accuracy when no document supports an answer. Online, track citation click rate, thumbs-up ratio, query reformulation rate, and task completion.
  3. Design data ingestion, chunking and freshness: parse tables, headings and code cleanly, then split documents into chunks of roughly 300–500 tokens with 10–15% overlap (about 40–60 tokens) so facts straddling boundaries are not lost, attaching document ID, section title, timestamp and ACL metadata to every chunk. Maintain freshness via an incremental re-indexing pipeline driven by document change events and content hashes, updating or deleting stale chunks and ACLs without rebuilding the full index.
  4. Choose features and representations: represent each chunk twice for hybrid search. Compute a sparse lexical representation for BM25 (a keyword-matching scorer that excels on exact product codes, acronyms and error strings) and a dense unit-norm (ℓ2-normalised) embedding vector from a bi-encoder model (which captures paraphrases and semantic similarity).
  5. Build the model pipeline from simple to strong: start with a fast BM25 baseline to verify parsing and ACL filtering, then add a dense ANN (approximate nearest neighbour) vector index such as HNSW (hierarchical navigable small world) and fuse results with reciprocal rank fusion. Next, add a cross-encoder re-ranker over the top 50–100 fused candidates to score query–chunk pairs jointly before passing the top chunks to an LLM (large language model) instructed to cite passage IDs and refuse to guess when evidence is missing.
  6. Plan serving architecture, context budget and security: at query time, authenticate the user and enforce ACLs inside the retriever (via metadata pre-filtering or post-filtering) so unauthorised chunks never enter the prompt. Compute the prompt token budget explicitly: 8,000−1,000 (instructions + question)−500 (answer)=6,500 tokens remain for retrieved context, so ⌊6,500/400⌋=16 chunks of 400 tokens fit (using 6,400 tokens and leaving 100 tokens for chunk headers and delimiters). Wrap retrieved passages in clear data delimiters, keep system instructions strictly separated, strip hidden instructions or executable markup, and block unapproved tool calls because retrieved internal documents can contain indirect prompt injections.
  7. Evaluate and launch safely: curate an evaluation set of real employee questions paired with gold source passages (and unanswerable queries to test abstention). Run offline ablations on retrieval recall@k and automated LLM-judge faithfulness, validate ACL isolation with automated security tests, then roll out via shadow traffic (logging retrieved chunks and latency) followed by a gradual canary release.
  8. Monitor, iterate and address interviewer trade-offs: track retrieval empty-result rate, p95 latency per stage (embedding, ANN + BM25, re-ranker, LLM), index lag, and user downvotes to feed hard negatives back into embedding fine-tuning. Be ready to discuss trade-offs: smaller chunks improve precision but break multi-paragraph reasoning (mitigated by parent-document expansion); re-ranking boosts quality at the cost of extra latency; and metadata pre-filtering guarantees ACL compliance but can shrink HNSW graph connectivity for restrictive roles.

Common mistakes

How long your answer should be

About 6–8 minutes in an interview: cover the pipeline stages in order, work through the 16-chunk budget, and highlight ACL filtering and prompt-injection defence.

Read this

Previous in ML system design: How would you design a real-time payment fraud detection system?
Next in ML system design: How would you design a visual search system that finds products looking like an uploaded photo? Assuming 500 images/s per GPU (graphics processing unit) and USD 2 per GPU-hour, how much GPU time and cost does it take to re-embed a 500-million-image catalogue when upgrading the embedding model?