Building a Citation-Accurate Document Q&A Service over PDFs
System DesignModel answerLast updated
Design a service that ingests text, scanned and table-heavy PDFs, answers questions with page-level citations, and keeps its index correct as documents are replaced or removed.
Design a Citation-Accurate Q&A Service over PDFs
Your team wants an internal service where users upload PDFs and then ask natural-language questions. Answers must be generated by an LLM from the uploaded content, and every claim must point back to the exact page it came from.
What the system must do
- Ingest PDFs that contain a mix of selectable text, scanned pages needing OCR, and tables.
- Answer questions with context drawn from the documents and explicit page-level citations.
- Handle changes: users can replace or delete a document, and the search index must always reflect the current version only.
Quality and performance goals
- Faithfulness: keep hallucination low, and make sure each citation really matches the text that supports the claim.
- Latency: ingestion may be asynchronous. Retrieval (before LLM generation) should finish in well under a second.
- Scale: thousands of documents, with many concurrent readers.
Sizing assumptions
- About 5,000 PDFs, averaging 50 pages each.
- Read traffic is high and concurrent; writes are comparatively rare.
What your answer should cover
- Parsing: how you deal with multi-column pages, tables, and scans.
- Indexing: the data model for chunks and their metadata (document ID, page, and so on).
- Citation correctness: how you ensure the page numbers shown to the user are right.
- Lifecycle: how you version documents and remove stale chunks without serving mixed or deleted content.
Include a rough capacity estimate, the main components, and the trade-offs behind your choices.
Hints
Hint 1
Start with arithmetic: pages, chunks per page, embedding dimension and bytes per vector. The result tells you whether you need sharding or only read replicas.
Hint 2
Do not let the LLM write page numbers. Give each retrieved chunk an opaque tag, have the model cite tags, and resolve tags to pages in your own code, then validate.
Hint 3
Treat each document version as an atomic unit: build the new version invisibly, then switch the active pointer in one step, and clean up the old chunks afterwards.
Hint 4
For layout, think in stages: classify the page, extract text or OCR, detect regions, recover reading order, then build structure-aware chunks that never silently cross page boundaries.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and capacity
- Corpus: 5,000 docs x 50 pages = 250K pages. At roughly 3 chunks per page (500-800 tokens), that is about 750K chunks.
- Vectors: 750K x 1024 dims x 4 bytes is about 3 GB raw, around 5-6 GB with an HNSW graph. That fits on one machine, so scale reads with replicas, not shards.
- OCR load: if 30% of pages are scans, that is about 75K pages. At roughly 1 s per page per GPU worker, 20 workers backfill everything in about an hour. Steady-state updates take seconds to minutes.
- Clarifying questions: multi-tenant or not? Cite physical page index or printed label (store both)? How quickly must a delete take effect (assume seconds)? Expected QPS (assume hundreds)?
Query latency budget (excluding generation): embed query ~20 ms, hybrid search ~30 ms, rerank top-50 ~100 ms, so under about 200 ms. Stream the LLM output on top.
2. Architecture
- Upload: store the PDF in object storage at
doc_id/version/file.pdf, write metadata to Postgres, publish an ingest event. - Page fan-out: one task per page for parallelism and cheap retries.
- Page workers: classify the page (native, scanned, mixed); extract text with coordinates, or OCR with word boxes; run a layout model to label regions (title, paragraph, table, figure, header/footer, caption); run a table-structure model on table regions.
- Chunker and embedder: structure-aware chunks, dense embeddings plus a sparse/BM25 representation.
- Index: a vector store with metadata filtering (pgvector, Qdrant, OpenSearch) plus lexical search, with 3+ read replicas behind a load balancer.
- Query service: access filter, hybrid retrieval with reciprocal rank fusion, cross-encoder rerank, prompt assembly, generation, citation validation.
3. Parsing hard layouts
- Multi-column: naive extraction interleaves columns. Detect blocks with the layout model, cluster by x-coordinate, read each column top to bottom and columns left to right, or use a reading-order model. Full-width headings reset the flow.
- Tables: detect the region, rebuild cells, serialize to Markdown/HTML so row/column relations survive. Make the table its own chunk with caption and nearest heading prepended. For long tables, chunk by row groups and repeat the header row in each. Add an LLM-written one-line summary as an extra embedding target, since questions rarely match raw cell text.
- Scans: OCR only pages or regions with no text layer. Keep per-word confidence; flag low-confidence pages and down-weight their chunks.
- Figures: index the caption (optionally a vision-model description) linked to the figure's bounding box.
- Chunking rules: respect section boundaries, prepend the heading path to embedded text, and never let a chunk cross a page boundary silently. Either split at the boundary or store
page_start/page_endwith per-span offsets.
4. Data model
Postgres
documents(doc_id, tenant_id, title, active_version, status, acl_groups, timestamps)document_versions(doc_id, version, content_hash, storage_uri, ingest_status, page_count)
Vector store, one record per chunk
chunk_id = hash(doc_id, version, page, block_idx)doc_id, version, tenant_id, acl_groupspage_start, page_end, page_label,bbox,block_type,section_pathtext, text_hash, ocr_confidence, dense and sparse vectors,is_active
5. Getting page numbers right
The model never writes page numbers.
- Wrap each retrieved chunk as
[S3] (doc: Title, p. 12) text.... - Instruct the model to answer only from sources, tag each claim with
[S#], and say "not found" when evidence is insufficient. Prefer structured output such as{claims:[{text, source_ids}]}. - Validate afterwards: drop tags not present in the context, map valid tags to
(doc_id, version, page, bbox)from stored metadata, and optionally run an entailment check between each claim and its cited chunk. Remove or regenerate unsupported claims. - In the UI, show the snippet and highlight the bbox so the user verifies in one click.
Upstream, reduce hallucination with hybrid search (exact terms such as IDs and clause numbers), reranking, and a score threshold that makes the system abstain on weak context.
6. Versioning and purging
Use a blue/green flow per (doc_id, version):
- Update: create version n+1 and ingest it with chunks marked
is_active=false. Version n continues to serve. - Commit: when every page succeeds, flip
active_versionto n+1 in a single transaction and activate the new chunks. Queries always filter on the active version, so users never see a mix. - Delete: set the document to tombstoned immediately; query filters exclude it within seconds, even before physical removal.
- Garbage collection: an async job deletes chunks of superseded or tombstoned versions after a grace period (for in-flight queries), then removes old blobs per retention policy.
- Failure handling: a failed ingest leaves the active version untouched; orphaned inactive chunks are swept by GC. Use
content_hashto skip re-ingesting identical files, andtext_hashto reuse embeddings for unchanged chunks.
7. Scaling reads
Replicas behind a load balancer, a cache for frequent queries and query embeddings, and tenant/ACL filters applied inside the vector search rather than after it. The index is small enough that sharding is unnecessary at this size; revisit it if the corpus grows by about 10x.
8. Trade-offs and common mistakes
- Heavier layout models improve quality but raise ingest cost; since ingest is asynchronous, favor quality.
- Larger chunks give more context but blur citations; smaller chunks give sharper page attribution but need more context assembly. Table and heading-aware chunks are a good middle ground.
- Mistakes: letting the LLM invent page numbers, confusing printed labels with physical indexes, deleting old chunks before the new version is live, filtering ACLs after retrieval, and using only dense search so exact identifiers are missed.
- Evaluate with a labeled set measuring retrieval recall@k, citation precision (does the cited page really support the claim), and abstention rate on unanswerable questions.