Building a Trustworthy Document Q&A Assistant with Retrieval and LLMs
Machine LearningModel answerLast updated
Design an internal question-answering assistant that retrieves enterprise documents to ground an LLM, then explain how you would measure, guard, and debug it.
You are interviewing for a senior data scientist position on a team that ships LLM-powered products. Your task is to design an internal question-answering assistant that answers employee questions using the company's own documents (wikis, PDFs, tickets, chat exports). The assistant must ground its answers in retrieved content rather than rely on the model's memory.
Assume the following:
- The document set changes frequently throughout the day.
- Answers must be trustworthy and traceable to sources.
- The system runs under realistic latency and cost limits.
In your answer, cover:
- Architecture end to end: ingestion, chunking, embeddings, retrieval, reranking, prompt construction, generation, and citation or grounding.
- Retrieval strategy: how you would decide between dense, sparse, or hybrid retrieval.
- Trade-offs: latency, cost, freshness, precision versus recall, context window limits, and hallucination risk.
- Data hygiene and governance: how you handle missing metadata, stale documents, duplicate content, and documents with restricted access.
- Evaluation: offline and online measurement, including answer-quality metrics, business metrics, and guardrail metrics.
- Approach choice and failure modes: when you would choose retrieval over fine-tuning, and which problems you expect in production.
State your assumptions about scale and service-level targets explicitly.
Hints
Hint 1
Break the pipeline into stages that can each be measured separately (retrieval recall, rerank precision, faithfulness of the generated answer), so that a bad answer can be traced to the stage that failed.
Hint 2
Treat access control and freshness as hard requirements, not afterthoughts: think about where permission filtering must happen (before ranking, not after) and what the default should be when permissions or metadata are missing.
Hint 3
For the retrieval choice, propose an experiment: build a labeled query set, compare recall per method by query type (exact IDs and acronyms versus paraphrased questions), and let the data justify hybrid search plus a reranker.
Hint 4
For evaluation, separate the layers: retrieval metrics (recall@k, MRR), generation metrics (faithfulness, citation correctness, abstention quality), online business metrics (resolution rate, deflection, feedback), and guardrails (permission leaks, latency, cost).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
A strong answer decomposes the system into stages that can each be measured, treats permissions and freshness as first-class constraints, and has an evaluation plan that pinpoints which stage failed. Start with requirements, then architecture, then spend most of the time on retrieval quality, governance, and evaluation.
1. Requirements and assumptions
State numbers so the design is concrete:
- Corpus: ~5M documents, ~50M chunks, ~100K documents changed per day.
- Traffic: ~200K queries/day, peak ~30 QPS.
- Latency: p95 time-to-first-token under 2s, full answer under ~6s.
- Freshness: edits searchable within ~15 minutes; permission revocations effective within ~1 minute.
- Trust: every claim cited; abstain when evidence is weak; never use a document the user cannot open.
Clarifying questions: which sources, whether ACLs are per-document or per-space, multilingual needs, and whether the assistant only answers or also takes actions.
2. Architecture
Ingestion (streaming plus batch backfill)
- Connectors emit change events (webhooks/CDC) to a queue.
- Parse text and layout (headings, tables, OCR for scans).
- Normalize, tag PII, detect language.
- Deduplicate: exact hash plus MinHash for near-duplicates.
- Chunk by document structure, ~300-500 tokens with 10-15% overlap, prefixing each chunk with title and section path.
- Embed and upsert into a vector index (e.g., HNSW) and a BM25 index, with ACL and metadata fields attached.
Query path
- Query understanding: rewrite follow-ups into standalone queries; extract filters (dates, product).
- Retrieval: ACL pre-filter, then dense top-100 and BM25 top-100 in parallel, fused with Reciprocal Rank Fusion.
- Reranking: a cross-encoder scores ~50 candidates and keeps 5-8; apply a mild recency prior and MMR for diversity.
- Prompt: instructions to answer only from context, cite sources by number, and say "I don't know" if evidence is insufficient; numbered context blocks with metadata.
- Generation: stream tokens.
- Post-check: verify citations exist and the cited span supports each claim (NLI model or LLM judge); abstain if support is low.
- Logging: query, retrieved IDs and scores, answer, feedback.
3. Dense vs. sparse vs. hybrid
- Sparse (BM25): excellent for exact terms, error codes, SKUs, acronyms; cheap and interpretable; misses paraphrases.
- Dense: handles semantic matches and paraphrases; weak on rare tokens and internal jargon; requires re-embedding when the model changes.
- Hybrid plus reranker: best recall across query types at the cost of extra infrastructure and ~50-150ms for reranking.
Decide empirically: build a labeled query set, measure Recall@50 per method sliced by query type. Enterprise data is full of identifiers and jargon, so hybrid usually wins. If dense underperforms on internal vocabulary, fine-tune the embedder on click logs or synthetic query-chunk pairs with hard negatives.
4. Trade-offs
- Latency vs. quality: rerankers and verifiers add time. Cap rerank candidates, use a small model for rewriting, cache embeddings and answers (key includes query, permission group, index version).
- Cost: dominated by LLM tokens. Send fewer, better chunks; route easy queries to a smaller model.
- Precision vs. recall: retrieve wide (k~100) for recall, let the reranker deliver precision. Too little context causes missing evidence and hallucination; too much causes distraction ("lost in the middle") and cost.
- Context window: fixed budget (~4-6K tokens), strongest evidence first; use parent-child retrieval (match small chunks, send the enclosing section).
- Freshness vs. cost: incremental upserts, re-embed only chunks whose content hash changed; full re-index only on embedding model change, using blue/green indexes.
- Hallucination: grounding instructions, mandatory citations, support verification, explicit abstention.
5. Data quality and governance
- Missing metadata: do not drop the document. Impute where safe (owner from source system, date from file mtime), flag imputed fields, treat missing
updated_atas neutral in the recency prior. Missing ACL means deny and quarantine until resolved. - Stale documents: version everything, retrieve only current versions, show "last updated" in citations, prefer the newer authoritative source when two disagree and surface the conflict, hard-delete chunks when sources are deleted, and monitor edit-to-searchable lag.
- Duplicates: collapse at ingestion into a canonical document with aliases; apply MMR at query time so copies do not fill the context.
- Permissions: pre-filter on principals during retrieval (post-filtering leaks information and can return empty sets); re-check against the live permission service for the final chunks; never share caches across permission groups; never fine-tune on restricted content, since weights cannot be ACL'd; audit-log what each user was shown.
6. Evaluation
Offline (golden set of a few hundred to thousands of queries, stratified by type, with labeled relevant chunks and reference answers):
- Retrieval: Recall@k, MRR, nDCG, plus ACL-correctness tests.
- Generation: faithfulness (claims supported by context), answer relevance, citation precision/recall, correctness versus reference. Use an LLM judge calibrated against human labels on a sample, and report agreement.
- Abstention: accuracy on unanswerable queries and the rate of wrongly abstaining on answerable ones.
- Stage attribution: if the gold chunk is not in the top-k, it is a retrieval failure; if retrieved but not used or contradicted, it is a generation failure.
Online:
- Business: task resolution, ticket deflection, time saved, repeat-query rate, adoption and retention.
- Quality signals: thumbs up/down, citation clicks, reformulation rate.
- Guardrails: permission-leak incidents (target zero), unsupported-claim rate on sampled traffic, abstention rate, p95 latency, cost per query, index freshness lag.
- Roll out via A/B tests or shadow mode; gate launches on guardrails, not only on the primary metric.
7. RAG vs. fine-tuning
Prefer RAG when knowledge changes often, answers need citations, and data is access-controlled: updates are an index write, and permissions are enforceable at retrieval. Fine-tuning suits style, format, domain vocabulary, or task behavior, not injecting facts. Often the best system combines RAG with a lightly tuned embedder, reranker, or generator.
8. Expected failure modes
- Relevant evidence never retrieved (bad chunking, vocabulary mismatch, over-aggressive filters).
- Right chunk retrieved but ignored or misread; answers blending conflicting versions.
- Stale or duplicate content dominating results.
- Tables and scanned PDFs parsed badly.
- Citations that look right but do not support the claim.
- Multi-hop questions that a single retrieval pass cannot answer.
- Permission lag or cache leakage across groups.
- Prompt injection from document text.
- Silent regressions after an embedding or model change.
Mitigations: per-stage dashboards, regression suites run on every index or model change, query decomposition or iterative retrieval for multi-hop questions, treating retrieved text as untrusted input, and a human-review loop on low-confidence answers.
Common mistakes
- Evaluating only the final answer, so failures cannot be attributed.
- Post-filtering by permission instead of pre-filtering.
- Treating missing metadata as "fresh" or "public".
- Stuffing the context window instead of reranking.
- Relying on an uncalibrated LLM judge.