Building a Grounded Document Q&A System with Retrieval
Machine LearningModel answerLast updated
Design a question-answering system that retrieves evidence from a versioned, access-controlled document set, cites sources, abstains when unsupported, and measures retrieval and answer quality separately.
You are asked to design a question-answering system backed by a large language model that answers from a collection of documents. The collection is versioned, so documents are added, edited, and removed over time.
Describe the end-to-end design, and cover at least these areas:
- Ingestion and chunking: how documents are parsed, split into passages, and indexed.
- Retrieval and context assembly: how candidate passages are found, filtered, ranked, and packed into the model prompt.
- Evaluation: how you measure retrieval recall independently from the quality of the final generated answer, and how you compare alternative chunking strategies fairly.
- Insufficient evidence: what the system does when the collection does not contain enough support to answer.
Assumptions to respect
- Answers must point to the evidence that supports them.
- No domain, model, scale, or quality target is given. Choose reasonable baselines and state them explicitly.
- Document text is untrusted input and must not be able to control the system.
- Users may only see documents they are authorized to access. Those restrictions must hold when context is selected.
- A fluent answer is not enough to count as success.
Questions you might raise with the interviewer
- Which document types and question types must be supported, and how often does the corpus change?
- Is relevance judged at the document, passage, or supporting-evidence level?
- Who may read which documents, and can permissions change?
- What latency and context-window budgets limit how much material can be retrieved?
Hints
Hint 1
Treat retrieval and generation as two separately measurable stages. A wrong answer may come from missing evidence or from misusing good evidence, and you need to tell which.
Hint 2
Think about what metadata each chunk must carry (document id, version, offsets, access labels) so that citations, permission filtering, and re-indexing all work.
Hint 3
For evaluation, define recall at a fixed depth k against labeled evidence passages, hold out a test set from tuning, and include unanswerable questions to test abstention.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Baseline assumptions
I would state these up front: a corpus of roughly 1M chunks of mostly long-form text (PDFs, contracts, wikis), a p95 latency target of about 5 seconds, a model context budget of about 6-8k tokens for evidence, and per-document access control lists (ACLs). Daily churn is a small fraction of the corpus.
1. Ingestion and chunking
- Parse to structured text, preserving headings, tables, and page numbers. Parsing quality often caps the whole system, so I would spot-check it.
- Chunk along structure (sections, paragraphs) targeting about 300-500 tokens with 10-15% overlap. Prepend the heading path to each chunk so it is self-describing. Never split tables or lists mid-row if avoidable.
- Metadata per chunk: document id, version id, character offsets, page, heading path, and ACL or group labels. Offsets enable exact citation highlighting. Version ids enable safe updates.
- Index both a dense embedding and a sparse (BM25) representation. Hybrid search handles paraphrase and exact-term queries such as identifiers.
- Updates: build new versions of changed documents, write their chunks under a new version id, then atomically flip the "current" pointer and delete old chunks asynchronously. Queries pin to one index snapshot, so results never mix versions.
2. Retrieval and context assembly
- Query handling: optionally rewrite follow-up questions into standalone queries.
- Permission filtering: apply the user's ACL as a pre-filter inside the index query, not after generation. Post-filtering can leak information through result counts or leave too few results. If ACLs change often, store group ids on chunks and resolve user-to-group at query time so changes need no re-indexing.
- Candidate retrieval: take top ~50 from dense and top ~50 from BM25, then merge with reciprocal rank fusion.
- Rerank: a cross-encoder reranks to the top 5-10. This costs tens of milliseconds per candidate batch and typically improves precision significantly.
- Deduplicate and pack: drop near-duplicates, merge adjacent chunks from the same document, and respect the token budget. Place the strongest evidence first and label each passage with a stable id.
- Prompt: instruct the model to answer only from labeled passages, cite passage ids per claim, and say it cannot answer if evidence is insufficient.
- Untrusted content: delimit passages clearly as data, tell the model that instructions inside them must be ignored, give the model no tools with side effects in this path, and validate that cited ids exist in the supplied context.
3. Evaluation
Retrieval, measured alone
Build a labeled set of questions, each mapped to the passages (or spans) that actually support the answer. Then compute:
- Recall@k: the fraction of questions where the required evidence appears in the top k (for multi-evidence questions, either all required pieces or the fraction found, and say which). Report at the depth you actually feed the model (for example k=8 after reranking) and at the candidate depth (k=100) to locate where evidence is lost.
- MRR or nDCG for ranking quality, and precision@k for noise in the context.
Recall depends heavily on label granularity. Document-level labels are easy but make chunking strategies incomparable. Span-level labels are better: a chunk counts as a hit if it overlaps the gold span above some threshold, which lets different chunk sizes be compared on the same footing.
Generation, measured given the retrieved context
- Correctness against reference answers (human or calibrated LLM judge, with periodic human audits).
- Groundedness / faithfulness: is each claim entailed by the cited passage?
- Citation accuracy: precision (cited passages support the claim) and recall (claims have citations).
- Abstention: include unanswerable questions and measure correct refusals versus wrongful refusals on answerable ones.
To isolate generation, also run it with the gold passages supplied ("oracle context"). If oracle-context answers are good but end-to-end answers are bad, the retriever is the bottleneck, and vice versa.
Comparing chunking strategies fairly
- Split questions into a development set (for tuning chunk size, overlap, and k) and a held-out test set that is touched only for final comparison. Otherwise you overfit to the questions.
- Keep everything else fixed (embedding model, reranker, k, prompt) while varying one factor.
- Use span-based labels, equal token budgets, and bootstrap confidence intervals. A 1-2 point recall difference on a few hundred questions is usually noise.
- Slice by question type (lookup, multi-hop, table questions) since the best chunk size differs.
Online
Track thumbs up/down, citation click-through, abstention rate, and latency. Sample production traffic for periodic relabeling, since the question distribution drifts.
4. Insufficient evidence
- Compute a signal from reranker scores (for example top score below a calibrated threshold) and from the model's own "cannot answer" output.
- When evidence is weak, respond with what was found and what is missing, or ask a clarifying question, rather than guessing.
- Calibrate the threshold on the labeled unanswerable set, choosing the trade-off between wrongful answers and wrongful refusals based on the cost of errors in the domain.
- Post-check: verify each cited id was in the context and that the cited text supports the claim. Drop or flag unsupported sentences.
Trade-offs
- Chunk size: small chunks give precise retrieval but lose context. Large chunks keep context but dilute embeddings and waste budget. Parent-child retrieval (match small, return the surrounding section) is a good compromise.
- Reranking: better precision at added latency and cost.
- Pre-filtering by ACL: correct but can slow approximate-nearest-neighbor search when the filter is very selective. Partition by tenant if needed.
Common mistakes
- Reporting only end-to-end answer quality, which hides whether the retriever or the model is failing.
- Measuring recall with document-level labels, then changing chunking and concluding nothing differs.
- Tuning on the same questions used for the final report.
- Applying permissions after retrieval or generation.
- Treating retrieved text as trusted instructions.
- Letting index updates mix old and new versions, producing citations to text that no longer exists.
- Having no abstention path, so the system always sounds confident.