Build a Document QA System with Grounded LLM Responses
Machine LearningModel answerLast updated
Design an end-to-end system that answers user questions by retrieving relevant passages from a large corpus and generating responses with citations.
You're building a question-answering service where users submit natural language queries and receive answers backed by a corporate knowledge base. The system must ground its responses in actual documents rather than relying solely on what the language model learned during training.
Your responsibility covers both components:
- The backend pipeline that processes incoming documents, creates searchable representations, and keeps the index current
- The request handler that takes a user's question, finds relevant content, constructs an appropriate prompt, and returns an answer with source references
Describe your architecture, justify your main technical choices with their benefits and drawbacks, and explain how you'd measure whether the system works well once deployed.
Given Information
- Knowledge base size: approximately 10 million documents totaling around 100 GB of text in various formats (HTML, Markdown, PDF), primarily English
- Update frequency: new documents and edits arrive constantly; users should see fresh content within minutes
- Traffic pattern: expect peaks around 300 queries per second
- Response time: a few seconds end-to-end is acceptable (generation takes most of this time); the retrieval portion should complete in roughly 300 milliseconds
- Every answer must reference which passages support it, and the system should explicitly decline to answer when the knowledge base lacks sufficient information
- The language model has context limits, and token costs make it impractical to include everything in each prompt
Questions You Should Consider
- What's the exact composition of the knowledge base—volume, file types, languages—and how often does it change?
- What are your targets for speed, throughput, and cost per query?
- How strictly must answers cite sources, and what should happen when no documents match?
- Do different users have permission to see different documents?
- Are queries independent or part of conversations where follow-up questions need context?
- Will you use hosted model APIs or run your own inference infrastructure for embeddings and generation?
Hints
Hint 1
Separate your architecture into two independent pipelines: one that runs continuously to process documents, and one that handles real-time user requests with strict latency requirements.
Hint 2
Retrieval based only on semantic similarity often misses exact matches like error codes or product names; consider combining multiple search strategies.
Hint 3
The model needs clear instructions about when it should refuse to answer, and you may need a separate verification step to ensure responses actually match the provided context.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Building a Document QA System with Grounded LLM Responses
Framework for a Strong Response
An effective design demonstrates four capabilities:
- Clear separation between the document processing pipeline and the query serving path
- Concrete capacity planning with realistic numbers
- Thoughtful handling of retrieval accuracy, content freshness, answer verification, and quality measurement
- Explicit reasoning behind each architectural decision
A shallow answer might simply suggest "embed documents, store vectors, call an LLM API." This misses critical details: how do you split documents into searchable units, how do you improve initial retrieval results, how do you prevent hallucinated answers, and how do you know if it's working?
1. Requirements Clarification and Capacity Math
First, confirm the stated parameters and resolve two important ambiguities:
- Access control: assume users have different document permissions
- Conversation handling: assume multi-turn dialogues where follow-ups reference previous context
Storage and indexing calculations
- 100 GB of text equals roughly 25 billion tokens
- Splitting into ~400-token segments with 15% overlap yields approximately 60 million chunks
- Vector representations at 768 dimensions using 32-bit floats require 3 KB each, totaling ~180 GB uncompressed
- Quantization to 8-bit integers reduces this to ~45 GB; product quantization can shrink it further to ~10 GB plus index overhead
- Plan for 4–8 index partitions with 2–3 replicas for availability
Embedding computation
- Processing 25 billion tokens for a complete rebuild
- A typical bi-encoder processes roughly 100k tokens/second per GPU
- Full reindexing requires about 70 GPU-hours, achievable in 2–3 hours with 32 GPUs
- Daily incremental updates (assuming 100k edited documents) add negligible load
Request volume
- 300 queries/second at peak with ~2–3k token prompts means ~1 million prompt tokens/second flowing to the LLM
- Generation cost and latency dominate; retrieval must stay under 300 ms
2. Service Interface
POST /ask
{
question: string,
conversation_id?: string,
user_id: string,
filters?: object
}
Response (streamed):
{
text: string,
sources: [{
chunk_id: string,
document_id: string,
url: string,
excerpt: string
}],
status: "answered" | "insufficient_information",
request_id: string
}
The request_id connects all logged data—original question, retrieval candidates, ranking scores, constructed prompt, and generated answer—for later analysis.
3. Data Schema
Document record: id, origin, url, version_hash, content_fingerprint, access_groups[], last_modified, metadata{title, category, language}
Searchable chunk: id, document_id, version_hash, content, hierarchy_path ("Setup > Linux > Network"), position_range, vector_embedding, access_groups[]
Maintain two storage layers:
- Primary store: object storage or key-value database holding authoritative content
- Search indexes: inverted index for keyword matching (BM25) and vector index for semantic search (HNSW or IVF-PQ), both partitioned by chunk ID hash
4. Document Processing Pipeline
-
Change detection. Connectors and crawlers publish events (
create/update/delete,document_id,version) to a message queue- Content fingerprinting skips unchanged documents
- This event stream enables minute-scale freshness
-
Content extraction. Format-specific handlers produce clean, structured text:
- HTML: remove navigation and ads
- Markdown: preserve heading hierarchy
- PDF: layout-aware text extraction with OCR fallback; convert tables to Markdown
-
Segmentation. Split on structural boundaries (headings, paragraphs) targeting 300–500 tokens with overlap
- Prepend document title and section hierarchy to each chunk so embeddings capture broader context
- Smaller chunks enable precise matching; larger chunks provide more context but dilute semantic signal
- Effective compromise: index small chunks but retrieve their parent sections at serving time ("chunk-to-section expansion")
-
Vector generation. GPU worker pool with autoscaling based on queue depth; tag each vector with
model_version -
Index updates.
- Write to both keyword and vector indexes
- Handle deletions with tombstone markers, filtered at query time, with periodic compaction
- HNSW supports incremental additions; rebuild index segments overnight to maintain graph quality
-
Freshness objective. Target 95th percentile latency from document change to searchability under 5 minutes; alert on processing delays
5. Query Serving Path (~300ms Retrieval Budget)
| Phase | Implementation | Latency |
|---|---|---|
| Question reformulation | Lightweight LLM converts follow-up into standalone query; skip for initial questions | 50–150ms (async) |
| Query encoding | Same bi-encoder used for documents | ~10ms |
| Multi-strategy retrieval | Keyword top-100 and vector top-100 in parallel across partitions, filtered by permissions | 30–60ms |
| Score combination | Reciprocal rank fusion: score = Σ 1/(k + rank) where k=60 | <1ms |
| Reranking | Cross-encoder scores top ~50 (query, chunk) pairs on GPU | 60–120ms |
| Context assembly | Select top 5–8 above threshold; remove duplicates; expand to containing sections; respect token budget | ~5ms |
| Answer generation | LLM with grounding instructions, streamed output | 1–3s |
| Verification | Check citations support claims; abstain or filter unsupported content | 50–200ms |
Why combine retrieval methods
- Vector search handles paraphrasing but struggles with exact identifiers like error codes, SKUs, or proper names
- Keyword search excels at exact matching but misses semantic equivalents
- Reciprocal rank fusion merges both without needing score normalization
Why add reranking
- Bi-encoders encode queries and documents independently, missing fine-grained interactions
- Cross-encoders jointly process query-document pairs, typically improving top-5 precision substantially
- Applying this expensive step to only ~50 candidates keeps latency manageable
Ensuring grounded answers
- Pre-generation check: if the best reranker score falls below a learned threshold, immediately return "I cannot find this information" without calling the LLM (also saves cost)
- Prompt engineering: number passages
[1]...[k], instruct the model to answer only from provided content, cite every claim, and explicitly state when information is missing - Post-generation validation: extract claims from the answer, use an entailment model to verify each claim against its cited passage, remove unsupported claims, and abstain if too few claims remain valid
Optimization techniques
- Cache normalized query → answer pairs with short TTL; invalidate when cited document versions change
- Cache query embeddings for common questions
- Use prefix caching for the static system prompt portion
6. Quality Measurement and Observability
Evaluate components separately to identify whether failures occur in retrieval or generation.
Retrieval metrics
- Create evaluation sets of (query, relevant_chunks) from:
- Manual annotations
- User interaction logs (clicks, citations)
- Synthetic questions generated from document content
- Measure recall@50 (upper bound for reranker), recall@5, MRR, and nDCG after reranking
- Segment by query characteristics: exact-match queries vs. conceptual questions vs. follow-ups
Generation metrics
- Faithfulness: percentage of claims supported by provided context
- Citation accuracy: precision and recall of source references
- Relevance: how well the answer addresses the question
- Correctness: agreement with human-verified answers
- Abstention quality: precision and recall on deliberately unanswerable questions
- Use an LLM as an automated judge, validated through regular human evaluation to check agreement and detect judge model drift
Production monitoring
- User signals: approval ratings, source link clicks, query refinement rate, abstention frequency
- Reranker score distributions (drops indicate coverage gaps)
- Continuous sampling for automated quality scoring
- Per-stage latency breakdown
- Index freshness lag
Improvement cycle
- Low retrieval recall → improve chunking strategy, add domain-specific embedding fine-tuning, expand coverage
- High retrieval recall but low faithfulness → strengthen grounding instructions, adjust verification threshold, improve context selection
- High abstention with good coverage → relax thresholds, improve query understanding
- Latency issues → optimize reranking candidate count, add result caching, scale infrastructure
Common Pitfalls
- No chunking strategy: storing entire documents produces poor retrieval and exceeds context limits
- Missing exact-match retrieval: vector search alone fails on identifiers and proper nouns
- No verification: models frequently generate plausible-sounding but unsupported content
- Ignoring permissions: security-filtered retrieval must happen before ranking to avoid leaking information through scores
- Lack of evaluation infrastructure: without measuring retrieval and generation separately, you can't diagnose what's broken
Trade-offs Summary
- Chunk size: smaller improves precision, larger provides context; hybrid approach retrieves small but expands to large
- Reranker depth: more candidates improve recall but increase latency; 50 candidates balances both
- Abstention threshold: higher prevents hallucination but increases "don't know" responses; tune on labeled data
- Index freshness vs. cost: faster updates require more frequent rebuilds; event-driven incremental updates provide good balance
- Hosted vs. self-hosted models: APIs are simpler but costlier at scale; self-hosting adds operational complexity but reduces per-query cost
This architecture provides production-ready question answering with verifiable grounding, sub-second retrieval, minute-scale freshness, and comprehensive observability for continuous improvement.