Design an End-to-End RAG System for a Large Document Corpus
Machine LearningModel answerLast updated
Design a production RAG pipeline that ingests millions of documents, retrieves grounded context, and generates cited answers with low latency at scale.
Scenario
Your company maintains an internal knowledge base of roughly 10 million documents — a mix of PDFs and Markdown files — stored in cloud object storage. Employees need to ask natural language questions and get concise, accurate answers that point back to the exact source documents.
You are asked to design the full production system, from the moment a document lands in storage to the moment a cited answer reaches the user.
Functional Requirements
- Ingestion: The system must detect and process new or updated documents automatically.
- Retrieval: Given a natural language query, the system must surface the most relevant document passages.
- Generation: An LLM must produce an answer grounded in the retrieved passages and include verifiable citations.
- Resilience: The system must handle component failures and high-latency conditions without silent degradation.
Non-Functional Requirements
| Dimension | Target |
|---|---|
| Corpus size | 10 million documents |
| Retrieval latency | p95 under 200 ms |
| End-to-end latency | Under 3 seconds, first token under 1 second |
| Hallucinations | Minimized through grounding and post-generation checks |
What You Are Expected to Cover
- Architecture overview: Describe the flow from document storage through ingestion, retrieval, and generation to the final response.
- Ingestion pipeline: Explain how you parse, chunk, and embed documents, and which vector store you would choose and why.
- Retrieval strategy: Explain how you combine retrieval methods, and how you rerank results before passing them to the LLM.
- Grounding and orchestration: Explain how you construct the prompt, enforce citation, and validate the output.
- Evaluation: Define how you would measure retrieval quality and generation accuracy in both offline and online settings.
Discuss trade-offs and failure modes at each stage. There is no single correct answer, but your choices should be justified with numbers and concrete reasoning.
Hints
Hint 1
Start from scale estimates before drawing any boxes — how many chunks do you actually have, how big are the vectors, and what does that imply for storage and indexing?
Hint 2
Dense retrieval alone fails on exact tokens like product codes and CLI flags. Think about what complementary retrieval method covers that gap, and how you combine the two ranked lists.
Hint 3
Getting relevant chunks into the top-100 is a recall problem; getting the right 5–8 into the LLM prompt is a precision problem. These call for different solutions at different points in the pipeline.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Ground the Design in Concrete Estimates
Before drawing any architecture, establish the numbers. Every design decision flows from them.
- Corpus: 10M docs, averaging roughly 4K tokens each (PDFs run long, Markdown short).
- Chunks: Targeting 300–512 tokens with ~15% overlap gives about 10 chunks per document → ~100M chunks total.
- Vector storage: 768-dimensional float32 vectors cost ~3 KB each → ~300 GB raw. With int8 or product quantization, that drops to ~75 GB.
- Daily churn: ~1% of docs change per day → ~100K doc updates → ~1M chunk re-embeds per day (manageable).
- Query load: ~50 QPS peak for an internal enterprise tool.
- Latency budget: retrieval p95 under 200 ms; end-to-end under 3 s; first streamed token under 1 s.
Questions worth clarifying with the interviewer before continuing:
- Are documents access-controlled per user or per group? (Affects pre-filtering in the vector store.)
- Is the LLM hosted externally or self-hosted? (Affects latency and data residency.)
- Are queries mostly exact-token lookups (error codes, SKUs) or conceptual? (Affects retrieval weighting.)
2. High-Level Architecture
Object Storage (S3)
│ (event notifications)
▼
Queue (SQS / Kafka)
│
▼
Ingestion Workers
parse → clean → chunk → embed
│
▼
Vector Index (HNSW, sharded) + BM25 Index + Metadata / ACL Store
▲
│
User → API Gateway (authN) → Query Service
│ 1. query embed / rewrite
│ 2. hybrid retrieve (dense + BM25, ACL filter)
│ 3. RRF fusion → cross-encoder rerank
│ 4. prompt assembly with chunk IDs
▼
LLM (streaming) → citation validator → response
│
Logging → eval pipeline / feedback store
3. Ingestion Pipeline
Change detection. S3 event notifications are pushed to a queue. Workers are idempotent and keyed by (doc_id, etag). On update, existing chunks for that doc are deleted before the new ones are upserted. On delete, chunks are tombstoned. A nightly reconciliation job diffs the object storage inventory against the index to catch any missed events. Failures go to a dead-letter queue with exponential backoff retries.
Parsing. Use format-specific parsers. For PDFs, a layout-aware library (Unstructured or a custom pdfplumber pipeline) with OCR fallback for scanned pages and table extraction to Markdown. For Markdown, split on headings. Always strip boilerplate — headers, footers, TOCs — which otherwise pollute retrieval with noise.
Chunking. The goal is chunks that are semantically coherent and fit within the embedding model's context window.
- Recursive structure-aware splitting: section → paragraph → sentence, targeting 300–512 tokens.
- 10–15% overlap preserves sentences that straddle boundaries. More than that inflates the index with diminishing returns.
- Prepend a context header to each chunk before embedding:
"Admin Guide > Snapshots > Retention". This is cheap and meaningfully improves recall by anchoring the vector in topical space. - Optional parent-child strategy: retrieve on small chunks for precision, but pass the containing section to the LLM for coherence.
Embedding. A strong open model (bge-large or e5-large, 768 dimensions) self-hosted on GPU. At ~5K chunks/second on a small GPU cluster, the 100M-chunk backfill takes roughly 6 hours. Daily incremental updates are trivial. Store model_version alongside every vector — model upgrades require a blue/green re-index. Never mix embedding spaces in the same index.
Vector store selection. At 100M vectors, requirements are: sharding, HNSW or IVF-PQ indexing, metadata filtering, and native hybrid search. OpenSearch or Vespa satisfy all of these in a single system (BM25 and kNN together, mature ACL filtering). Milvus and Weaviate are strong alternatives if you want a dedicated vector database. I would choose OpenSearch or Vespa to avoid managing two separate retrieval systems. Chunk text lives in the same index; raw source files stay in object storage.
4. Retrieval: Hybrid Search and Reranking
Why hybrid? Dense retrieval handles paraphrase and conceptual queries well but struggles with exact tokens like ERR-4012 or --snapshot-retain-days 30. BM25 handles those precisely but misses synonyms. For technical corpora, neither alone is sufficient.
Combining results. Fetch top-100 candidates from each retriever independently, then fuse with Reciprocal Rank Fusion (RRF). RRF is score-scale-free, requires no tuning, and is consistently robust in practice.
Reranking. This is the biggest single precision lever. A cross-encoder (bge-reranker or a hosted rerank API) scores each of the top-50 fused candidates jointly with the query, keeping the top 5–8. Unlike bi-encoders, cross-encoders compare query and passage together, catching relevance that embedding similarity misses. Budget roughly 80–100 ms for a GPU-batched rerank call. Apply a minimum score threshold — if nothing clears it, return "not found in the knowledge base" rather than generating from weak context.
Latency budget:
| Step | ~p95 time |
|---|---|
| Query embed | 15 ms |
| Hybrid search | 50 ms |
| Rerank (top 50 → top 8) | 90 ms |
| Overhead | 20 ms |
| Total | ~175 ms |
Query rewriting via a small LLM (for multi-turn conversation) adds ~150 ms and should be applied only when conversation history is present.
5. Prompt Assembly, Grounding, and Output Validation
Number each retrieved chunk with a stable citation ID and include source metadata: [S3] Admin Guide §4.2 (p. 37): .... Order chunks with the highest-scoring ones first and last — this mitigates the known "lost in the middle" attention degradation. Cap context at roughly 4K tokens.
The system prompt must instruct the model to answer only from the provided sources, cite [S#] inline after every claim, and respond with "not found" when the answer is absent.
Post-generation validation:
- Parse all cited IDs and reject any that don't appear in the context window.
- Run an NLI or small-LLM faithfulness check per sentence against its cited chunk. Drop or flag sentences that are unsupported.
- Return citations as deep links — presigned object storage URLs with page numbers — so users can verify claims directly.
Reliability. Stream tokens to hit the first-token-under-1-second target. Set per-stage timeouts and circuit breakers. Degrade gracefully: reranker unavailable → fall back to RRF order; a slow vector shard → return results from healthy shards; primary LLM fails → route to a fallback model or provider.
6. Evaluation
Offline retrieval. Build a golden query set of 1–2K examples with labeled relevant chunks (sourced from SME labeling, mined search logs, and LLM-synthesized questions filtered by humans). Key metrics: Recall@50 before reranking, Recall@8 after, MRR, and nDCG@10. Evaluate each component in isolation (BM25, dense, hybrid, reranked) to detect regressions precisely.
Offline generation (RAGAS-style, LLM-as-judge calibrated against human labels):
- Faithfulness: fraction of answer claims that are directly supported by the retrieved context. This is the hallucination metric.
- Answer relevance: does the answer actually address the question?
- Context precision/recall: are the right chunks being retrieved and used?
Online monitoring. Track citation click-through rate (proxy for trust), thumbs-up/thumbs-down feedback, retrieval latency percentiles, and reranker score distributions. A drop in average reranker scores is an early signal that the corpus or query distribution has drifted from the embedding model's training data.
Common Mistakes to Avoid
- Skipping BM25. Dense-only retrieval reliably fails on exact identifiers and technical terms that dominate enterprise corpora.
- No reranking. Passing raw retrieval results to the LLM with no precision stage is the most common source of hallucination from weak context.
- Ignoring model versioning. Mixing vectors from different embedding models in the same index silently corrupts similarity scores.
- No relevance threshold. Generating from irrelevant context produces confident-sounding hallucinations. Returning "not found" is always better than fabricating.
- Citation theater. Generating
[S1]in the output without validating that the claim is actually in chunk S1 gives a false sense of grounding. The post-generation faithfulness check closes this gap.