Building an Enterprise Document Q&A Assistant with Retrieval
Machine LearningModel answerLast updated
Design a production retrieval-augmented question-answering service over company documents, covering indexing, search, grounding, freshness, access control, evaluation and operations.
You are asked to design an internal question-answering assistant for a large organization. Employees ask natural-language questions, and the assistant answers using the company's own content: wikis, tickets, PDFs, chat archives and similar sources. Answers are produced by a language model that is given retrieved passages as context.
Describe the full system, from raw documents to a streamed, cited answer. Your design should cover:
- Ingestion: how documents are parsed, split into chunks, embedded and indexed.
- Retrieval: how candidates are found and ranked (vector search, keyword search, hybrid combination, reranking).
- Prompt orchestration: how context is assembled and how the model is instructed.
- Grounding and citations: how answers are tied to sources and how unsupported claims are handled.
- Freshness: how edits, deletions and permission changes propagate.
- Performance: latency and throughput targets, with rough capacity numbers.
- Privacy and security: access control, sensitive data handling, and untrusted retrieved text.
- Evaluation: how you measure retrieval relevance and answer quality, and how you reduce hallucinations.
- Operations: how you scale and monitor the system in production.
State your assumptions about scale (users, corpus size, QPS) up front and explain the main trade-offs you make.
Hints
Hint 1
Begin by clarifying scale and SLAs, then do quick arithmetic: documents to chunks to vector storage, and QPS to the number of retrieval and GPU workers you need.
Hint 2
Split the design into an asynchronous ingestion path and a synchronous query path. For the query path, think in stages: query rewrite, parallel dense and keyword retrieval, fusion, cross-encoder rerank, prompt building, generation, verification.
Hint 3
Treat permissions as a first-class constraint: where in the pipeline are they enforced, and what happens if you filter after retrieval instead of during it? Also decide what the system does when evidence is weak.
Hint 4
For evaluation, separate retrieval metrics (recall@k, MRR, nDCG) from generation metrics (faithfulness, answer relevance, citation accuracy), and say how you would gate releases and monitor drift online.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing and assumptions
I would first confirm scope, then fix numbers so the design is testable.
- Users: about 50k employees, roughly 20 QPS average and 100 QPS peak.
- Corpus: about 10M documents, around 5 pages each. With ~500-token chunks plus overlap, that is on the order of 200M chunks. At 768 dimensions in fp16, raw vectors are about 300 GB; product quantization brings that to roughly 30 GB in memory-friendly form.
- Freshness: edits searchable within ~5 minutes; deletions and permission revocations within ~1 minute, since a stale permission is a security defect.
- Latency: time-to-first-token p95 under 3 s; retrieval plus reranking under ~300 ms at p95.
- Quality: every answer cites sources, and the system abstains when evidence is thin.
Architecture
Ingestion (asynchronous): source connectors (webhooks or change-data-capture, plus periodic reconciliation crawls) push events to a queue. Workers parse and clean (OCR, table extraction), chunk, scan for sensitive data, embed on GPUs, and upsert into a vector index, a BM25 index and a metadata store. Raw and parsed documents live in object storage.
Query path (synchronous): gateway with auth and rate limiting, then query rewriting, hybrid retrieval, fusion, reranking, context building, generation, citation verification, and streaming to the client.
User identity always comes from the auth token, never the request body, and every ACL decision keys off it.
Ingestion details
- Structure-aware chunking: split on headings, paragraphs and table boundaries; target 300-800 tokens with 10-15% overlap. Keep tables whole (serialized as markdown) and handle code blocks separately.
- Contextual prefix: prepend the title and section path to each chunk before embedding. This noticeably helps short chunks.
- Incremental updates: hash each chunk's content so only changed chunks are re-embedded; this usually removes most of the re-embedding cost on edits.
- Embedding model: a bi-encoder, ideally fine-tuned on in-domain query-passage pairs mined from search logs. Version it. A model change means a full re-embed into a shadow index followed by an atomic alias swap. At ~5k chunks/s, 200M chunks take about 11 hours, fine for an offline backfill.
- ACL denormalization: store the allowed principals on each chunk so filtering happens inside the index.
Retrieval
- Dense ANN (HNSW, or IVF-PQ at this size), sharded by chunk ID, querying all shards and merging; fetch top ~100.
- BM25 in parallel for acronyms, error codes, ticket IDs and product names that embeddings handle poorly.
- Fusion with Reciprocal Rank Fusion,
score = sum(1 / (60 + rank_i)), which needs no score calibration. - Cross-encoder reranking of the top 50-100 down to 5-10 (~50-100 ms on GPU). Usually the largest single quality gain.
- Query rewriting: a small model turns follow-ups into standalone queries and extracts filters. Multi-query or HyDE can be used where recall matters most.
- ACL as a pre-filter, not a post-filter. Post-filtering can return empty results and lets unauthorized text pass through intermediate stages. Resolve group membership once per request and cache it for about a minute.
Prompting, grounding, citations
- Prompt order: system rules, numbered passages
[1]..[k]with source and date, conversation summary, question. - Instruct the model to answer only from the passages, cite
[n]per claim, and say "not found" when evidence is insufficient. - Budget about 4-6k context tokens; place the strongest passages at the start and end to reduce "lost in the middle" effects.
- Post-generation verification: map each citation to its chunk and check entailment with an NLI model or LLM judge; remove or flag unsupported sentences.
- Abstention: if the top rerank score is below a tuned threshold, skip generation and return the closest documents.
- Prompt injection: treat retrieved text as untrusted data, delimit it, and never let it override system instructions.
Freshness
- Event-driven updates with periodic reconciliation to catch missed events.
- Upserts keyed by
(doc_id, version); deletions write tombstones immediately, and query time also checks versions against the metadata store. - ACL changes update chunk metadata directly without re-embedding, so the 1-minute SLA is realistic.
- Mild recency boost for time-sensitive sources; show document dates in citations.
Privacy and security
- Document-level ACLs enforced inside retrieval; audit logs of who retrieved what.
- PII/secret detection at ingestion with redaction or restricted classification.
- Encryption in transit and at rest, data residency respected per region, and no training on customer content by the model provider.
- Logs store identifiers and hashes rather than raw sensitive text where possible.
Evaluation
- Retrieval (offline): a labeled set of queries with relevant chunks; track recall@k, MRR and nDCG, per source and per query type.
- Generation: faithfulness (claims supported by context), answer relevance, citation precision/recall, and abstention correctness, scored by a calibrated LLM judge spot-checked by humans.
- Release gating: run the suite on every change to chunking, embeddings, reranker or prompts; require no regression on key slices.
- Online: thumbs up/down, follow-up rate, escalation to search, A/B tests; sample low-rated sessions for review.
Reducing hallucinations
Better retrieval (hybrid plus rerank), strict grounded prompts, abstention thresholds, citation verification, lower temperature, and fallbacks that show sources instead of a synthesized answer.
Scale and monitoring
- Autoscale stateless gateway and orchestration; keep rerankers and LLM serving on GPU pools with batching and streaming. Cache query embeddings and frequent answers (permission-aware keys).
- Budget the latency: rewrite ~100 ms, retrieval ~100 ms, rerank ~100 ms, then LLM first token ~1 s.
- Monitor stage latencies, index lag, queue depth, empty-result rate, abstention rate, faithfulness samples, cost per query and embedding drift. Alert on freshness-SLA breaches and ACL-sync failures.
Common mistakes
- Filtering by permissions after retrieval.
- Using dense-only search and missing exact identifiers.
- Skipping reranking, or evaluating only the final answer so retrieval failures are invisible.
- No abstention path, so weak evidence still produces confident answers.
- Forgetting that an embedding-model change requires a full reindex strategy.