Design a Document Q&A Service with Retrieval-Augmented Generation
Machine LearningModel answerLast updated
Architect a production RAG system that lets employees query a large internal document corpus and get cited, access-controlled answers within two seconds.
Scenario
Your team is building an internal knowledge assistant for a large organization. Employees need to search across hundreds of thousands of internal documents — policies, technical guides, meeting notes, and reports — and get concise AI-generated answers that cite the exact source. Unlike a general-purpose chatbot, this system must respect who is allowed to read what, stay fresh as documents change, and never fabricate references.
What You Are Designing
A query-and-answer service backed by a large document corpus. The system ingests uploaded files (PDF and Markdown), indexes them for retrieval, and at query time fetches relevant passages to ground an LLM response.
Scale and Constraints
- Corpus: 500,000 documents today, growing by roughly 5,000 per day. Expect around 30 chunks per document, so about 15 million indexed chunks.
- Traffic: Approximately 50 queries per second at peak.
- Latency: A complete answer (or the first streamed token) must arrive within 2 seconds.
- Freshness: An edit to any document must be reflected in search results within 1 hour.
- Access control: Users may only receive content from documents they are authorized to read. Revoking access must take effect within minutes, not hours.
- Safety: The system must not leak PII from documents, and it must not let the model answer from unauthorized content even under adversarial prompting.
What Is Expected
Walk through your design covering:
- Ingestion pipeline — how documents are parsed, split into chunks, and embedded.
- Storage layer — what goes in the vector index, what goes in a relational store, and why.
- Retrieval logic — how hybrid search, access filtering, and re-ranking work together.
- Grounding and citation accuracy — how you prevent the model from hallucinating or fabricating references.
- Observability — which metrics tell you the pipeline is healthy and the answers are good.
Justify your choices, call out trade-offs, and flag what you would confirm with stakeholders before locking in an approach.
Hints
Hint 1
Start by sizing the problem: how many chunks exist, how large are the vectors, and how does that shape your storage and latency budget? Allocate milliseconds to each stage before picking components.
Hint 2
Access control must be enforced inside the vector search query — as a pre-filter, not a post-filter. Post-filtering can silently return too few results and leaks information through score distributions and timing.
Hint 3
Hallucination and citation drift are retrieval problems as much as generation problems. Think about what you can check automatically after the model responds, and when you should refuse to generate at all.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to Approach This Problem
Start by quantifying the system, then allocate your latency budget, then design each layer to hit both the SLA and the correctness requirements. Interviewers want to see that "add a vector database" is not your whole answer.
Step 1: Size the Problem
Corpus math
500k documents × 30 chunks × ~500 tokens per chunk = ~15M chunks. At 1024-dimensional float32, each vector is ~4 KB, so ~60 GB raw. With int8 or product quantization that drops to ~15 GB — manageable on a sharded ANN cluster.
Growth of 5k docs/day adds ~150k chunks/day. At ~1 ms GPU time per embedding, a single A10 handles this in about 3 minutes of wall time, so the 1-hour freshness SLA is very achievable; the bottleneck is queue lag, not compute.
Latency budget (2 seconds to first streamed token)
| Stage | Allocation |
|---|---|
| Auth and group resolution (cached) | 20 ms |
| Query rewrite and embedding | 50 ms |
| Hybrid retrieval, parallel BM25 + ANN | 100 ms |
| Cross-encoder rerank, top-50 → top-8 | 150 ms |
| LLM time-to-first-token | 600 ms |
| Citation verification and safety filter | 150 ms |
Clarify with the interviewer whether 2s is measured to first token (streamable) or full response. The LLM slot dominates; keep the retrieval stack fast so you have headroom.
Step 2: Ingestion Pipeline
The pipeline is event-driven, not batch, to meet the 1-hour freshness requirement.
Flow: File upload or connector webhook → blob store (raw) → event queue → parser workers → chunker → PII scanner → embedding workers (GPU) → index writers
Parsing
Use layout-aware parsing for PDFs (libraries like pdfplumber or a managed service like Azure Document Intelligence). Preserve heading hierarchy, table structure, and page numbers. Run OCR for scanned pages. Parse Markdown via its AST so headings become structural boundaries, not just formatting.
Chunking
Target 300–600 tokens per chunk with ~10–15% overlap between adjacent chunks. Never split a table mid-row. Prepend a breadcrumb to each chunk — Document title > Section > Subsection — before embedding. This improves both BM25 and dense retrieval significantly because the most relevant text appears at the top of every chunk.
Incremental updates
Hash each chunk's content. When a document changes, re-chunk the whole document, diff against stored hashes, and re-embed only changed chunks. Tombstone removed chunks and atomically flip the document's current_version pointer so queries never mix old and new chunks mid-read.
PII handling at ingestion
Run an entity detector (e.g., Microsoft Presidio) over every chunk. For high-risk entities like SSNs and account numbers, either redact before indexing or tag the chunk sensitivity=high to restrict retrieval. This is a policy choice — flag it and get a decision before building.
Step 3: Storage Layer
| Store | What lives here |
|---|---|
| Blob storage | Raw files, parsed text — source of truth for reprocessing |
| Postgres | Document metadata, versions, chunk-to-doc mappings, ACLs, sensitivity labels, ingestion state |
| Vector + BM25 index | Chunk text, embedding, filterable fields: allowed_principals[], sensitivity, doc_id, version, is_current |
The vector index is a derived artifact. It can always be rebuilt from blob storage and Postgres. Design so you can drop and rebuild the index without losing any source data.
Choose a search engine with native filtered ANN — Elasticsearch/OpenSearch, Azure AI Search, Vespa, or Qdrant all support this. Native means the ACL filter is applied during graph traversal, not after. Post-filtering is wrong here: it degrades recall unpredictably and leaks information through timing and score distributions.
Step 4: Retrieval Logic
1. Resolve the user's principals. Expand their identity into user ID plus all group IDs from your directory service. Cache with a short TTL (a few minutes). Store ACLs on chunks as group IDs, not user IDs — group membership changes are free, and the arrays stay small.
2. Rewrite the query. Use a small, fast LLM to resolve conversational references, expand acronyms, and optionally generate two or three query variants for better recall.
3. Hybrid search in parallel. Run BM25 (top-50) and dense ANN (top-50) simultaneously, both with the same pre-filter: allowed_principals ∩ user_principals ≠ ∅ AND is_current AND sensitivity ≤ user_clearance. BM25 handles exact terms like policy numbers and error codes; dense search handles semantic paraphrases. Fuse the two ranked lists with Reciprocal Rank Fusion (RRF), which avoids calibrating incompatible score scales.
4. Cross-encoder rerank. Score the ~100 fused candidates against the query with a cross-encoder model. Keep the top 6–10. Apply max-marginal-relevance (MMR) diversification so a single document doesn't consume all context slots.
5. Defense-in-depth ACL re-check. Before building the prompt, re-validate each selected chunk against Postgres or the source system's permission API. This catches the window between a revocation and the index reflecting it. Log every check.
Step 5: Grounding, Hallucination Mitigation, and Citation Accuracy
Grounded prompt design. Pass chunks to the model as numbered sources [1]..[k], each including its text and metadata. Instruct the model to answer only from the provided sources, cite every factual sentence, and respond "I cannot find this in the available documents" when the sources are insufficient. Never ask it to infer beyond what's there.
Abstention gate. If the top rerank score is below a tuned threshold, skip generation entirely and return the closest matching documents with a message that no confident answer was found. This is better than a low-confidence generation.
Post-generation citation verification. After the model responds, split the answer into individual claims. Use an entailment model or a cheap LLM judge to verify each claim is supported by its cited chunk. Drop or visually flag unsupported sentences. Also validate that cited indices like [3] actually exist in the provided set — models occasionally invent citation numbers.
Server-side citation construction. Map chunk IDs to uri#page and a quoted span on the server. Never let the model emit URLs; it will hallucinate them.
Prompt injection defense. Treat all retrieved text as untrusted data. Delimit it clearly in the prompt so model instructions and document content cannot be confused. The model can only leak what retrieval gave it, which is why ACL enforcement belongs in retrieval — not in a system-prompt instruction like "don't reveal secret documents."
Step 6: Observability
Retrieval health
- Fraction of queries returning zero results (overall and per user cohort)
- Mean and p99 retrieval latency, broken down by stage
- Queue lag and embedding backlog (alert if > 30 minutes)
- Time from document update to chunk appearing in search results
Answer quality
- Citation support rate: fraction of claims verified by their cited source
- Abstention rate: if it rises sharply, retrieval quality may have dropped
- Thumbs-up/down from users, linked to query and retrieved chunks
- LLM-as-judge scores on a held-out golden set, run nightly
Security and compliance
- ACL filter application rate (every query must show this = 1.0)
- Number of defense-in-depth re-check failures (should be near zero; spikes need investigation)
- PII redaction hit rate at ingestion and output filter
Common Mistakes to Avoid
- Post-filtering instead of pre-filtering. Doing ACL checks after retrieval is both a security risk and a recall problem.
- Letting the model enforce access control. Prompt instructions are not a security boundary.
- Nightly batch ingestion. The 1-hour SLA requires an event-driven pipeline.
- Assuming dense search alone is enough. BM25 outperforms embedding models on exact-match queries like product codes or policy identifiers.
- No abstention logic. Without a low-confidence fallback, the model will generate confidently from weak evidence.