Enterprise Document Q&A with Retrieval and Generation at Scale
System DesignModel answerLast updated
Design an end-to-end, multi-tenant retrieval-augmented question-answering platform over large, mixed-format document collections, with strict isolation, freshness, latency and cost targets.
Problem
A company wants to offer a question-answering product over its customers' private document collections. Users ask natural-language questions and receive grounded answers that cite the documents they came from. Design the full production system and justify your main choices.
Requirements
- Tenancy and security: many customers share the platform. No tenant may ever see another tenant's data, and per-user document permissions must be respected. Data must be encrypted in transit and at rest, and personal data must be handled according to tenant policy.
- Content: PDFs, web pages, emails, spreadsheets and source code, arriving at up to 10 million documents per day.
- Freshness: a new or changed document should be searchable in under 5 minutes.
- Latency: P50 ≤ 800 ms and P95 ≤ 2 s per query.
- Cost: a defined budget per 1,000 queries.
What to cover
- Ingestion: connectors, change capture, parsing of each format, chunking (size, overlap, metadata, tables, code), duplicate detection, and PII redaction.
- Embeddings: model choice and dimensionality, multilingual vs. code-specific models, multi-vector chunks, similarity and normalization, and how to migrate between embedding versions.
- Indexing: vector index type and parameters (e.g. graph-based vs. quantized inverted-file), a keyword index, sharding, replication, storage tiers, zero-downtime reindexing, and memory/capacity arithmetic.
- Retrieval: query understanding, hybrid sparse and dense candidate generation with permission filters and recency weighting, score fusion, deduplication, cross-encoder re-ranking, and a threshold for "can this be answered?"
- Prompt construction: context budget, packing, citations, tool use, and routing between models of different cost and quality.
- Trustworthiness: attribution checks, abstention, guardrails, prompt injection through retrieved text, and runtime PII enforcement.
- Caching and freshness: which caches exist, key design, invalidation on document change, and online index swaps.
- Multilingual support.
- Scaling, per-stage latency budgets, autoscaling, and disaster recovery (replication, snapshots, RTO/RPO).
- Observability and evaluation: retrieval and answer metrics, drift, tracing, offline gold sets, online experiments, and feedback loops.
- Cost model and levers, plus the accuracy / latency / cost trade-offs.
- Behavior when retrieval is weak.
- An API and a data schema for documents and embeddings.
- Cloud vs. on-prem, and a phased rollout with experiments and rollback.
State your assumptions and numbers explicitly. Because the scope is wide, show how you prioritize.
Hints
Hint 1
Spend the first few minutes on scale math: convert 10M docs/day into docs/s and chunks/s (including peak), estimate the live corpus, and decide how much of it must be in fast memory.
Hint 2
Treat tenant and permission isolation as a data-plane invariant: inject tenant and ACL filters server-side in every index query, never rely on the prompt, and plan a fallback for filters so selective that approximate search loses recall.
Hint 3
Split the latency budget by stage (query understanding, parallel sparse and dense retrieval, fusion, reranking, generation) and use tiering, quantization and model routing to hit both the latency and cost targets.
Hint 4
Close the loop with evaluation: a gold set for retrieval recall and answer groundedness, calibrated abstention thresholds, and shadow-index plus per-tenant alias flips for safe embedding migrations.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The scope is huge, so I would state assumptions, draw two pipelines (ingestion and query), and go deep on the three things that most often break real systems: tenant/ACL leakage, retrieval quality, and latency and cost under load.
1. Scale and SLOs (assumptions)
- 10M docs/day is about 116 docs/s on average, roughly 350/s at a 3x peak. At about 10 chunks per doc that is about 100M chunks/day, or 1.2k chunks/s average and 3.5k/s peak.
- Live corpus after dedup and retention: about 500M chunks, of which about 100M are "hot".
- Clarify whether latency is measured to first streamed token or to the full answer. I would propose first token for long answers and full answer for short ones.
- Isolation is a correctness invariant enforced in the data plane.
2. Ingestion and chunking
- Connectors and CDC: webhooks and polling for drives, mail APIs, git hooks and object-store events. All changes go onto a log (Kafka) partitioned by tenant, giving ordering, replay and backpressure.
- Parsing: layout-aware PDF parsing with OCR fallback; HTML to boilerplate-free Markdown; emails split into thread, quoted-reply removal and attachments; spreadsheets by sheet with header detection; code via a syntax-tree parser.
- Chunking: prose split on structure, about 400 tokens with about 15% overlap. Tables kept whole up to roughly 1k tokens, otherwise split by row groups with the header repeated and a generated summary. Code split by function/class with path and signature prepended.
- Metadata per chunk: tenant, ACL principals, doc id, version, section path, language, timestamp, source URI, content hash.
- Dedup: hash of normalized text skips re-embedding of unchanged chunks; MinHash catches near-duplicates such as forwarded mail.
- PII: NER plus regex detectors, then redact or tokenize per tenant policy. Originals live in an encrypted vault with per-tenant keys. TLS in transit, AES-256 at rest.
3. Embeddings
- A multilingual 768-dim model that supports truncation (Matryoshka-style) to 256 dims for cold data; a separate code model with its own index.
- L2-normalize and use inner product (equivalent to cosine).
- Multi-vector (summary and synthetic questions pointing to the same chunk) improves recall but costs 2-3x storage, so restrict it to the hot tier.
- Store the embedding model version on every vector. Migrate by shadow dual-write, offline backfill, gold-set recall comparison, then a per-tenant alias flip with easy rollback.
- A roughly 100M-parameter encoder handles about 1.5k chunks/s per GPU, so 4-6 GPUs at peak plus elastic backfill capacity.
4. Indexing
- Hot tier: HNSW with int8 vectors, M=32, efConstruction=200, efSearch about 100, giving recall@10 of 0.95+ in single-digit milliseconds per shard. Memory: 100M × (768 B + about 256 B graph) is about 100 GB, i.e. 4 shards of about 25 GB with 3 replicas.
- Warm/cold tier: IVF-PQ (nlist about 65k, 64-byte codes, nprobe about 32). 400M × 64 B is about 26 GB of RAM, with full vectors on SSD for exact rescoring of the top 200. A float32 HNSW over all 500M chunks would need about 1.75 TB, which tiering avoids.
- Sparse: BM25 in Lucene/OpenSearch with per-language analyzers.
- Sharding: by tenant hash; very large tenants get dedicated indexes; small tenants share shards but the server always injects the tenant filter.
- Selective filters: filtered HNSW loses recall when few vectors pass the filter. Below about 10k candidates, brute-force scan the filtered set.
- Writes: upserts and tombstones from CDC; a small real-time segment gives the 5-minute freshness and is merged periodically. Reindex by building a new index, validating, and atomically switching an alias.
5. Retrieval and re-ranking
- Query understanding: language ID, spelling, conversation-aware rewrite, intent, and filters (e.g. "Q3 2024" to a date range).
- Parallel BM25 top-100 and dense top-100, both with the ACL pre-filter.
- Reciprocal Rank Fusion (k=60) avoids score calibration; apply recency decay with an intent-specific time constant; collapse duplicates by doc and hash.
- Cross-encoder reranks the top 50 and keeps 8-12 (about 80 ms on GPU).
- If the best rerank score is below a threshold calibrated on the gold set, take the fallback path.
6. Prompting and generation
- About 8k token budget: policy (~800), history summary (~700), evidence (~5k), output reserve.
- Order by relevance, merge adjacent chunks of the same document, label each as
[S3] title | date | text, and require a citation per claim. - Tools (SQL/spreadsheet, calculator, live connectors) run with the user's own credentials.
- Route by complexity, rerank confidence and tenant tier: roughly 75% to a small/medium model, hard or multi-hop queries to a frontier model.
7. Hallucination and safety
- Check each cited sentence with an entailment model; compute coverage; below threshold regenerate more strictly or abstain.
- Treat retrieved text as untrusted data: delimited blocks, instruction hierarchy, stripping of instruction-like patterns, no tool calls triggered by retrieved content without policy checks.
- Runtime PII and compliance filters on output, with audit logs.
8. Caching and freshness
- Caches: query-result (keyed by tenant, ACL hash, normalized query, index version), retrieval, embedding (by content hash), and reranker caches.
- Invalidate on document change via version or doc-id tags emitted by CDC; short TTLs for volatile sources. Index swaps are online via aliases.
9. Multilingual
Language-aware analyzers for BM25, a multilingual embedding model for cross-lingual retrieval, and answering in the user's language while citing original-language sources.
10. Scale and resilience
- Autoscale each stage on its own signal: queue lag for parsers and embedders, GPU utilization for rerankers, QPS for retrieval, tokens/s for generation.
- Illustrative P95 budget: query understanding 50 ms, retrieval 150 ms, fusion 20 ms, rerank 120 ms, prompt build 30 ms, leaving the rest for generation (first token).
- Multi-AZ replication; cross-region snapshots; RPO of minutes and RTO under an hour for standard tenants, tighter tiers for premium. The log makes the index rebuildable.
11. Evaluation and observability
- Retrieval: recall@k, MRR, nDCG on gold sets (augmented with synthetic questions). Answers: groundedness, citation precision, abstention correctness, user satisfaction.
- Monitor embedding and query-distribution drift; trace every request across stages.
- Online A/B tests plus thumbs and edit feedback feeding hard-negative mining and active labeling.
12. Cost and trade-offs
Cost per 1k queries is dominated by generation tokens, then reranking, then retrieval infrastructure. Levers: caching, model routing, smaller context via better reranking, quantization, tiering, and batching. Higher recall (larger candidate sets, multi-vector, bigger reranker) costs latency and money, so spend it where the gold set shows gains.
13. Fallbacks
Weak retrieval leads to a clarifying question, then scope expansion (older documents, more sources, relaxed filters within permissions), and finally a clear refusal rather than a guess.
14. Interfaces
POST /v1/query {tenant, user, question, filters, stream}returns answer, citations (doc id, chunk id, span, URL) and confidence.POST /v1/documents,DELETE /v1/documents/{id}, and a status endpoint.- Chunk record:
chunk_id, tenant_id, doc_id, version, acl_principals[], text_ref, lang, ts, content_hash, embed_model_version, vector.
15. Deployment and rollout
Cloud gives elasticity and managed GPUs; on-prem or private deployments serve strict data-residency customers at higher operational cost. Roll out in phases: shadow traffic, internal users, a few tenants behind flags with A/B tests, then general availability, with automatic rollback on groundedness, latency or leakage-canary regressions.
Common mistakes
- Enforcing tenant isolation in the prompt rather than at the index.
- Ignoring recall loss from highly selective filters.
- Embedding everything in float32 in RAM without capacity math.
- No answerability threshold, so the system always answers.
- Treating retrieved text as trusted instructions.