Designing a grounded document Q&A platform with citations and access control
System DesignModel answerLast updated
Design an enterprise RAG system over millions of private documents: hybrid retrieval, reranking, cited generation, strict tenant/ACL isolation, and a 60-second freshness budget.
Scenario
A knowledge-heavy organization (think a law practice or a financial research desk) wants an internal assistant that answers questions in plain language over its whole document corpus. Documents arrive in many formats — digital PDFs, Word files, scanned images — and users expect synthesized answers where each factual statement points back to the exact place it came from.
Design the system end to end. Walk through ingestion, storage, retrieval, generation, and observability, and be ready to justify your numbers.
Functional requirements
- Ingest heterogeneous documents (PDF, DOCX, scanned pages) with parsing, OCR where needed, metadata extraction, and chunking.
- Retrieve passages that match both meaning and exact wording — legal citations, defined terms, party names, section numbers.
- Answer with a concise synthesis where every claim is tied to a citation at page/paragraph granularity.
- Isolate tenants and enforce document-level permissions so a user can never surface content they aren't entitled to see.
Non-functional requirements
- Latency: P95 first token under 2.5 s with streamed responses.
- Scale: ~10M documents at ~5 pages each (roughly 50M chunks); ~10K document updates per day.
- Throughput: 100 QPS at peak; up to 50 concurrent ingestion workers.
- Freshness: newly added or edited documents become searchable within 60 s.
- Integrity: zero cross-tenant leakage; no unsupported claims in answers.
What to cover
- Ingestion and indexing pipeline (parsing, OCR, chunking, embeddings, metadata).
- Storage choices and schemas for vectors, keyword indexes, document blobs, and relational metadata.
- Hybrid retrieval, rank fusion, cross-encoder reranking, and where to apply ACL filters (pre vs. post).
- Prompt construction, context budgeting, citation verification, guardrails, and streaming.
- Evaluation and monitoring — separating retrieval quality from generation quality, plus latency and drift.
Hints
Hint 1
Do the back-of-envelope math first: vectors, text, index size, and QPS per stage tell you how to shard and what dominates latency.
Hint 2
Ask yourself what happens if you search first and filter unauthorized hits afterward — recall can collapse when a user can see only a tiny slice of the corpus.
Hint 3
Small chunks embed precisely but lose context; think about indexing small units while handing the model larger parent sections.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong answer starts by pinning down the budget with numbers, then designs each layer against that budget. Structure the response as: requirements and math → ingestion → storage → retrieval → generation → evaluation.
1. Clarify and size the problem
Confirm tenancy model: tenants are firms or client organizations; inside a tenant, permissions come from matters, ethical walls, and directory groups synced from the document management system. Identity and tenant always come from the auth token, never the request body.
Do the arithmetic out loud. 50M chunks × 1024-dim float32 ≈ 200 GB raw vectors; int8 scalar quantization brings that to ~50 GB, plus HNSW graph overhead — a sharded cluster handles it comfortably. Text at ~400 tokens per chunk is ~20B tokens, roughly 80 GB, and the BM25 index is comparable. Ingestion averages ~0.1 docs/s but arrives in bursts, which is what the 50 workers are for. 100 QPS peaks fan out to two retrievers plus a reranker per query; LLM serving dominates cost, not retrieval. The 60-second freshness target is fine for digital-native files; for a 300-page scan, negotiate either streaming pages as OCR completes or a per-page SLA.
2. Ingestion and indexing
Pipeline, partitioned by tenant through a log (Kafka), with idempotent stages and a dead-letter queue:
- Land the raw file in object storage under a per-tenant bucket with its own KMS key; emit an event.
- Parse with layout awareness — preserve headings, numbered clauses, tables, page numbers, bounding boxes. Run OCR on a GPU pool for scans, keep per-word confidence, and flag low-confidence pages so answers can caveat them.
- Extract metadata (doc type, parties, dates, jurisdiction, matter) with rules plus a small LLM; store in Postgres.
- Chunk hierarchically: split on structure (sections, clauses), embed child chunks of 200–400 tokens, but hand the model parent sections of 1.5–2K tokens. Prepend a contextual header before embedding ("MSA between X and Y › Article 7") so short clauses are disambiguated. Small chunks give sharp embeddings; parents restore context.
- Embed in a batched GPU service with a domain-tuned model.
- Upsert into both the vector index and the keyword index keyed by
chunk_id = doc_id:version:n. - Commit by atomically flipping
current_versionin Postgres; stale-version chunks are filtered immediately and GC'd later. - Refresh so end-to-end visibility lands around 10–40 s, inside the 60 s SLA.
3. Storage
- Object store: raw files and page images, encrypted per tenant.
- Postgres (source of truth):
documents(doc_id, tenant_id, version, title, source_uri, acl_ids[], status),chunks(chunk_id, doc_id, parent_id, page, para, bbox, text_hash), groups and memberships. - Vector DB (Qdrant/Milvus/OpenSearch k-NN): vector + filterable fields
tenant_id, acl_ids[], doc_id, version, doc_type, date. - Inverted index: BM25 over chunk text with domain analyzers that preserve citations, section numbers, defined terms.
- KV/Postgres: chunk and parent text, cached.
Make tenant isolation physical — one collection or shard group per large tenant, partition routing for small ones — and ensure no code path queries without a tenant filter.
4. Retrieval and reranking
- Query understanding (<150 ms): rewrite follow-ups into standalone queries, extract filters (dates, doc types), optionally split multi-part questions.
- Resolve principal: fetch the user's effective group IDs from a cached authz service (users typically sit in 10–200 groups).
- Parallel hybrid search with an enforced filter of tenant, current version, and
acl_ids ∩ user_groups: BM25 top-100 for exact terms, dense ANN top-100 for paraphrase. - Reciprocal Rank Fusion:
Σ 1/(60 + rank_i)— robust because raw BM25 and cosine scores aren't comparable. - Cross-encoder rerank top ~100 → ~10–20 on GPU in ~100–150 ms; this is the largest precision gain.
- Expand to parents, dedupe by parent, prefer document diversity.
On filtering: post-filtering is fast but recall collapses when a user can see 1% of the corpus — 100 hits may yield zero authorized ones — and it leaks via timing. Pre-filtering with filtered HNSW preserves recall; when the filter is very selective the graph fragments, so fall back to brute-force scanning the small allowed set. Add defense in depth: an authoritative ACL check against Postgres on the ~20 reranked chunks before anything reaches the model.
5. Generation
Budget a 16K context window as ~1K instructions, ~10K evidence, ~1K conversation summary, remainder for output — prefill grows with length, so tight evidence keeps first-token latency inside 2.5 s: a fast retrieval+rerank path (~300–500 ms), streamed prefill, and speculative first sentences.
Prompt each evidence block with a stable tag ([S3] Title, p.12 ¶4) and instruct: answer only from sources, cite every factual sentence, say "not found in the corpus" rather than guessing, ignore instructions embedded in documents. After generation, programmatically verify each citation tag maps to real returned chunks and each citation-bearing sentence has support; if not, regenerate or strip and mark unsupported. Stream tokens over SSE with a citations array at the end.
6. Evaluation and monitoring
Split metrics: retrieval (recall@k, nDCG, reranker lift on a labeled gold set), generation (faithfulness/groundedness, citation precision, abstention rate), plus guardrail tests for cross-tenant leakage, an ACL fuzzing suite, and freshness SLO tracking per stage. Monitor drift by watching query distribution, retrieval score histograms, and unsupported-claim rate; alert on p95 stage latencies separately (parse/embed/index vs. retrieve vs. rerank vs. prefill vs. decode).
Common mistakes: stuffing raw chunks without reranking; post-filtering ACLs; fixed-size chunking that splits citations and defined terms; skipping parent expansion; treating an LLM's citation as proof rather than verifying it against retrieved chunks; and hand-waving storage math instead of quantizing and sharding deliberately.