Scalable PDF Parsing and Cited RAG Service
Medium · ML System Design · Software Engineer · Technical Screen
Prompt
Architect a production Retrieval-Augmented Generation (RAG) platform that ingests enterprise PDF files and answers user questions with verifiable, page-accurate citations. Many uploaded files combine two-column technical prose, borderless data tables, Roman-numeral front matter, and scanned image pages (for instance, a 50-page Lab Safety Handbook where a hazard rule starts near the bottom of physical PDF page 14—printed as "Page 10"—and finishes at the top of page 15).
Your design should satisfy these core requirements and operating constraints:
- Document intake: Extract native digital text layers when valid, run optical character recognition (OCR) on scanned pages, and preserve row/column relationships inside tables.
- Cited retrieval and Q&A: Return relevant passages and synthesized answers backed by exact page references.
- Live catalog mutations: Support uploading revised file versions and deleting documents so search indexes reflect only the latest active content.
- Grounding and latency: Curb unsupported model claims, ensure cited page numbers match the underlying source text, process uploads asynchronously in the background, and keep online retrieval latency below
1 second. - Target scale: Store roughly
5,000PDFs averaging50pages per file (~250,000pages total) while serving high-concurrency read traffic.
Scope & Expectations
- Complex layout extraction: Preserving true reading order and table structure across multi-column pages, embedded tables, and scanned images.
- Passage and metadata schema: Structuring indexed chunks with document identifiers, version numbers, and page-level provenance.
- Grounded citation mechanics: Designing hybrid search, prompt assembly, and post-processing so answers attach accurate page numbers without hallucinating digits.
- Version and deletion lifecycle: Updating or removing documents cleanly so stale chunks never appear alongside current ones.
Step-by-step walkthrough
Clarify requirements and frame the problem
Retrieval-Augmented Generation (RAG) is a pattern where a system searches an external document collection for relevant passages and places them into a language model's prompt so the model answers from real source text rather than from memory. Here, our RAG system splits cleanly into two halves connected by search indexes:
- Offline ingestion converts uploaded PDFs into clean, searchable text and table passages, while anchoring every character to the exact page and 2D bounding box it came from.
- Online question answering retrieves the best passages for a user's question and generates an answer in which every factual claim cites the exact page that supports it.
Success is judged per claim: an answer only counts as right when both the statement is accurate and its citation opens a page that actually states that fact. A fluent answer with an invented or off-by-two page number is a failure.
The three hardest parts of this specific problem
- Extracting non-linear layouts in reading order: multi-column pages, embedded tables, and scanned images (OCR, Optical Character Recognition, which converts pixel images of text into machine-readable characters) break standard left-to-right PDF text extractors.
- Making page citations accurate by construction: language models transpose digits and confuse cover-page offsets, so the model must never type raw page numbers from memory.
- Zero-downtime updates and deletes: replacing or deleting a PDF must never leave a blind gap where the document vanishes from search, and must never mix chunks from v1 and v2 in the same answer.
Functional requirements
- Upload, update (new version), and delete PDFs asynchronously; handle native selectable text, scanned pages via OCR, and structured tables.
- Answer natural-language questions with explicit document and page citations plus bounding-box coordinates for UI highlighting; also expose a retrieve-only endpoint.
- Enforce document-level permissions so callers retrieve passages strictly from PDFs allowed by their group memberships.
Non-functional targets and explicit assumptions
- Accuracy over guesswork: high citation alignment, and an explicit
"Not found in accessible documents"abstention when evidence is missing. - Latency: retrieval p95 (95th percentile latency) under 500 ms; answer streaming begins within 1–2 seconds, finishing in a few seconds; asynchronous ingestion makes a 50-page PDF searchable within 10 minutes (p95).
- Scale & concurrency: 5,000 PDFs averaging 50 pages each (250,000 pages), up to 100 queries/s at peak, with room to grow 10–100x.
- Physical page index vs. printed page label: we store both the 1-based physical page position in the PDF file (
page_index = 14) and the human-visible printed number (page_label = "10"or"iv", shifted by cover pages and Roman-numeral front matter). Citations display"page 10 (PDF p. 14)"and deep-link topage_index = 14.
Back-of-the-envelope numbers
Estimate storage, memory, and compute from first principles before choosing databases or sharding strategies:
Corpus size 5,000 PDFs x 50 pages/PDF = 250,000 pages total Scanned share assume 30% scanned pages = ~75,000 pages need OCR Chunks ~2 chunks/page (~400 tokens + tables) = ~500,000 chunks (~100/PDF) Vector memory an embedding is a fixed-length numeric vector capturing text meaning: 500,000 x 1,024 floats x 4 bytes = ~2.05 GB (float32) HNSW graph in-memory graph links (~32 links x 4 B + metadata) = ~80-100 MB Full re-embed 500,000 chunks x ~450 tokens = ~225M tokens total Object storage raw PDFs (~5 MB avg incl. scans) = ~25 GB rendered page PNGs (~200 KB/page) = ~50 GB Weekly updates assume 5% of docs updated/week = ~250 PDFs (~12,500 pages/week) Query load 20,000 employees x 10 queries/day = 200,000 queries/day over 10 business hours (36,000 s) = ~5.6 queries/s avg; design for 100/s peak Reranker peak 100 queries/s x 50 candidates = 5,000 (query, passage) pairs/s LLM prompt peak ~8 passages x 450 tokens + system = ~4,000 input tokens/query 100 queries/s x 4,000 tokens = ~400,000 prompt tokens/s at peakFour concrete lessons fall straight out of this math:
- Do not shard the vector index: ~2.1 GB of vectors plus graph metadata fits easily inside the RAM of a single server, where an approximate nearest-neighbor search over 500K vectors takes 5–20 ms. We run multiple replicas for high availability and read throughput, not sharding.
- Ingestion cost is GPU parsing, not disk: 75 GB of object storage costs pennies per month; running layout detection and OCR across 250,000 pages is a one-time GPU batch job, followed by a light ~12,500 pages/week steady state.
- Query latency and GPU budget live in reranking and LLM generation: evaluating 5,000 passage pairs/s and 400K prompt tokens/s at peak requires dedicated GPU batching, rate-limit headroom, and caching.
- 100x growth path: at 500,000 PDFs (~50M chunks), vectors grow to ~200 GB in float32 (~50 GB with
int8scalar quantization, which compresses each 4-byte float to a 1-byte integer with minimal recall loss), at which point we shard by tenant without changing the API or data model.
API design
POST /v1/documents multipart PDF + {title?, acl_groups[]} -> 202 Accepted {doc_id, version: 1, status: "PROCESSING"} PUT /v1/documents/{doc_id} upload replacement PDF -> 202 Accepted {doc_id, version: n+1, status: "PROCESSING"} -> 200 OK {doc_id, version: n} (when file SHA-256 matches active version) GET /v1/documents/{doc_id} -> {active_version, versions: [{version, state, quality}]} PATCH /v1/documents/{doc_id}/acl {acl_groups[]} -> 200 OK DELETE /v1/documents/{doc_id} -> 202 Accepted (hidden immediately; async chunk purge) POST /v1/retrieve {query, top_k: 8, filters?: {doc_ids?}} -> 200 OK {passages: [{doc_id, version, text, score, page_spans: [{page_index, page_label, start, end, bboxes}]}]} POST /v1/answer {query, conversation_id?, filters?} -> 200 text/event-stream: streamed answer tokens, followed by final event: {answer_id, abstained: bool, sentences: [{text, supported: bool, citations: [{doc_id, version, page_index, page_label, bboxes}]}]} GET /v1/documents/{doc_id}/versions/{v}/pages/{page_index} -> rendered page image + boxes POST /v1/feedback {answer_id, helpful: bool, bad_citation_index?}Why these API contracts matter:
- Asynchronous
202 Acceptedon writes: OCR and table extraction on a 100-page scanned PDF can take minutes, so uploads return a pollable version status immediately while the previous version stays live. - Version-pinned citations: every citation carries
version, so clicking a citation from last week's answer opens the exact historical page image used to generate it (with a banner if a newer version now exists). - SHA-256 upload deduplication: re-uploading byte-identical PDFs returns
200 OKwithout burning OCR/embedding compute. - Standalone
/v1/retrieve: lets us benchmark retrieval accuracy independently of the LLM and serves as a graceful fallback if the LLM provider has an outage.
- Asynchronous
Data model: documents, versions, pages, and chunks
We keep PostgreSQL as the single authoritative source of truth for metadata, permissions, and parsed blocks, while treating the vector index and keyword index as derived, rebuildable views:
-- Authoritative Metadata DB (PostgreSQL) documents PK (doc_id) tenant_id, title, owner_id, acl_groups text[] (GIN-indexed) active_version int, status ('ACTIVE' | 'DELETING' | 'DELETED'), updated_at document_versions PK (doc_id, version) file_sha256, pdf_object_key, page_count, parser_version, embed_model state ('UPLOADED' | 'PARSING' | 'CHUNKING' | 'EMBEDDING' | 'INDEXED' | 'ACTIVE' | 'SUPERSEDED' | 'PURGED' | 'FAILED') expected_chunks int, quality jsonb {ocr_pages, mean_ocr_conf, tables_count, warnings} pages PK (doc_id, version, page_index) page_label text, text_source ('TEXT_LAYER' | 'OCR'), ocr_confidence float, width float, height float, page_image_key text blocks PK (doc_id, version, block_id) page_index int, bbox [x0, y0, x1, y1], block_type ('TITLE' | 'HEADING' | 'PARAGRAPH' | 'LIST' | 'TABLE' | 'FIGURE' | 'FOOTNOTE'), reading_order int, section_path text, body_text text, table_cells jsonb -- Derived Search Record (stored with identical chunk_id in Vector Index + BM25 Keyword Index) chunk chunk_id "{doc_id}:{version}:{seq}" (deterministic ID for safe retries) doc_id, version, doc_title, tenant_id, acl_groups[], active (bool) chunk_type 'TEXT' | 'TABLE' | 'FIGURE' header "Lab Safety Handbook > 3. Laser Rooms > 3.4 Bay C" (embedded, never cited) body the passage text page_spans [{page_index, page_label, start, end, bboxes}] embedding float32[1024] of (header + "\n" + body)See how
page_spanssolves paragraphs that cross a page break without losing exact page attribution:Chunk body (520 chars total): chars 0..295 -> "Laser goggles rated OD 5+ are mandatory inside Bay C." chars 296..520 -> "Visitors must sign the entry log before crossing the yellow line." page_spans metadata on this chunk: span 0: {page_index: 14, page_label: "10", start: 0, end: 295, bboxes: [[72, 640, 540, 710]]} span 1: {page_index: 15, page_label: "11", start: 296, end: 520, bboxes: [[72, 72, 540, 125]]}Storing
blocksin PostgreSQL also means that when a better embedding model comes out next quarter, we re-chunk and re-embed straight fromblockswithout re-running expensive PDF OCR.High-level architecture
Upload / Update / Delete User Question | | v v +------------------+ raw PDF +------------------+ +---------------------+ | Document API |------------->| Object Store | | Query API | +------------------+ | PDFs + page PNGs | | Authn + user groups | | +------------------+ +---------------------+ | write version row ^ | v | v +------------------+ | +---------------------+ | Metadata DB |<-----+ +------------------------+ | Retrieval Service | | (PostgreSQL) | | | Ingestion Workers | | 1. Embed query | | docs, versions, | +---| (queued per stage) | | 2. Dense || BM25 | | pages, blocks | | - route: native / OCR | | 3. RRF + DB ACL | +------------------+ | - layout & XY-cut | | 4. GPU Reranker | ^ | - tables & clean | +---------------------+ | | - chunk & embed | | | | | +------------------------+ v v | | | upsert +------+ +------+ | | v |Vector| | BM25 | | | +------------------------+ | HNSW | |Index | | | | Vector Index (HNSW) |<--->|3 rep | |2 rep | | | | Keyword Index (BM25) | +------+ +------+ | | +------------------------+ v | +---------------------+ +------------ authoritative ACL & active_version ----------| Answer Service | | Tagged prompt, LLM | | Citation Verifier | +---------------------+- HNSW (Hierarchical Navigable Small World) is a multi-layer proximity graph kept in RAM that finds approximate nearest-neighbor vectors in logarithmic-like steps (milliseconds for 500K vectors).
- BM25 (Best Matching 25) is a classic keyword-scoring algorithm based on exact term frequency and inverse document frequency; it catches exact part numbers, policy codes (
"ISO-27001"), and SKUs that semantic vector embeddings often blur together. - Each ingestion stage communicates through its own durable queue so CPU-heavy chunking and GPU-heavy layout/OCR pools scale and retry independently.
Deep dive 1: parsing multi-column layouts, tables, and scans
Standard PDF libraries extract characters in whatever order the PDF writer emitted them, which scrambles multi-column pages and turns tables into soup. We use a 6-stage multimodal parsing pipeline:
1. Smart per-page routing (native text vs. OCR). Running OCR on clean digital PDFs wastes GPU time and introduces character errors (
"0"vs"O"), so we only route a page to OCR when: (a) it has near-zero extractable characters despite visible pixels, (b) a high fraction of characters lack valid Unicode mappings (ToUnicodeCMap corruption), or (c) a single raster image covers most of the page. Native pages extract exact words with 2D bounding boxes straight from the PDF text layer; scanned pages get words, boxes, and confidence scores from OCR.2. Multimodal layout detection. We render each page at 150–200 DPI and detect structural blocks (
TITLE,HEADING,PARAGRAPH,LIST,TABLE,FIGURE,PAGE_HEADER,PAGE_FOOTER,FOOTNOTE) using a detector trained on document layout datasets (such as DocLayNet) or a LayoutLM-family multimodal model (a transformer that jointly attends to word tokens, their 2D(x0, y0, x1, y1)bounding boxes, and visual page features). Using visual + spatial features distinguishes a bold section heading from a running page header and sees column boundaries clearly.3. Reconstructing reading order with recursive XY-cut. Consider a two-column page:
+---------------------------------------------------+ | Q4 Safety Manual (Full-Width) | <- horizontal cut below title +------------------------+ +-----------------------+ | 1. Gloves must be worn | | 2. Goggles are needed | | in all lab rooms. | | near chemical vats.| +------------------------+ +-----------------------+ ^ vertical whitespace gap Naive top-to-bottom read: "1. Gloves must be worn 2. Goggles are needed in all lab rooms..." (BROKEN) Recursive XY-cut order: Title -> full left column -> full right column (CORRECT)Recursive XY-cut repeatedly splits a page along the widest full-span horizontal or vertical whitespace gap and recurses inside each sub-rectangle. Full-width titles and wide tables split horizontally first, then two-column regions split vertically so Column 1 finishes completely before Column 2 begins. Pages where XY-cut finds no clean rectangular split (for example, L-shaped text wrapping around an inset chart) fall back to a learned sequence-to-sequence reading-order model (such as LayoutReader).
4. Parsing tables as structured cells. Flattening a table into plain text loses row-and-column alignment:
- Native tables drawn with vector ruling lines are reconstructed directly from line intersections (exact and fast).
- Borderless and scanned tables run through a table-structure recognition model (such as Table Transformer) to detect rows, columns, column headers, and merged cells, populated with text-layer or OCR words inside each cell's box.
- Tables are serialized as Markdown (or HTML
rowspan/colspanwhen cells merge). Wide/long tables exceeding 500 tokens are split into row batches, repeating the column header row in every chunk so each slice stays self-contained. We also prepend a short generated summary ("Table 2: laser eyewear optical density ratings by wavelength") for better embedding recall while feeding exact table cells to the LLM. - If table-structure confidence is low, we fall back to a vision-language model (VLM) on the cropped table image — verified against source tokens: we accept the VLM's Markdown only if at least 90% of its alphanumeric tokens match the underlying text-layer/OCR tokens, preventing hallucinated numbers.
5. Stripping repeating headers and footers safely. Beyond layout-model
PAGE_HEADER/PAGE_FOOTERlabels, a statistical pass catches running boilerplate like"Internal Use — Engineering Ops"or"Page 3 of 50"without deleting real body text:import re from collections import Counter def normalize_line(text: str) -> str: """Lowercase and replace digit runs with '#' so 'Page 3 of 50' matches 'Page 14 of 50'.""" return re.sub(r"\d+", "#", text.strip().lower()) def find_boilerplate(pages, margin_band: float = 0.08, min_share: float = 0.30, min_pages: int = 3): """Find normalized lines repeating in the top or bottom 8% margin band across pages.""" doc_counts = Counter() for page in pages: # Count each normalized margin line at most once per page (y=0 is top of page) seen_on_page = set() for line in page.lines: in_top_margin = line.y_bottom <= margin_band * page.height in_bottom_margin = line.y_top >= (1.0 - margin_band) * page.height if in_top_margin or in_bottom_margin: norm = normalize_line(line.text) if norm: seen_on_page.add(norm) doc_counts.update(seen_on_page) # Use 30% rather than 50% because bound manuals often alternate left/right page headers min_occurrences = max(min_pages, min_share * len(pages)) return {norm for norm, count in doc_counts.items() if count >= min_occurrences} def is_margin_boilerplate(line, page_height: float, boilerplate_set: set, margin_band: float = 0.08) -> bool: """Only strip a matching line when it ALSO sits inside the top/bottom margin band.""" in_margin = (line.y_bottom <= margin_band * page_height) or (line.y_top >= (1.0 - margin_band) * page_height) return in_margin and (normalize_line(line.text) in boilerplate_set)Before stripping footers, we extract
page_label(preferring the PDF catalog's/PageLabelsdictionary when present, otherwise parsing the footer page number). Checkingin_marginduring removal ensures a recurring word like"Summary"is never accidentally deleted from the middle of a body table.6. Quality gates. Each page records
ocr_confidence. Low-confidence pages trigger a human review queue and display an"OCR low-confidence scan"badge alongside citations.Deep dive 2: structure-aware chunking and single-page source units
If we force every chunk to stop hard at a page break, paragraphs and sentences split in two at the bottom of page 14 retrieve poorly. If we ignore page breaks completely, a chunk spanning pages 14–15 cannot tell which single page holds a cited fact.
We get both coherent retrieval and exact single-page citations by separating the retrieval chunk from the prompt source unit:
- Chunking at ingestion time: walk blocks in reading order, starting a fresh chunk at every section heading, packing complete sentences up to ~400 tokens (hard cap 600), keeping tables whole (or row-batched with headers), carrying a 1-sentence overlap within the same section, prepending the section breadcrumb
header("Lab Safety Handbook > 3.4 Bay C"), and recording character-levelpage_spans. - Splitting into single-page source units at prompt time: before calling the LLM, we split each retrieved chunk along its
page_spansso every prompt tag (S1a,S1b, ...) lives on exactly one page:
def build_source_units(retrieved_chunks): """Split retrieved chunks at page boundaries so every tagged unit sits on exactly one page.""" units = [] for chunk_idx, chunk in enumerate(retrieved_chunks, start=1): for span_idx, span in enumerate(chunk.page_spans): # Example: chunk 1 spanning pages 14 and 15 becomes 'S1a' (p.14) and 'S1b' (p.15) suffix = chr(ord("a") + span_idx) units.append({ "tag": f"S{chunk_idx}{suffix}", "doc_id": chunk.doc_id, "version": chunk.version, "doc_title": chunk.doc_title, "page_index": span.page_index, "page_label": span.page_label, "bboxes": span.bboxes, "text": chunk.body[span.start:span.end], }) return units- Chunking at ingestion time: walk blocks in reading order, starting a fresh chunk at every section heading, packing complete sentences up to ~400 tokens (hard cap 600), keeping tables whole (or row-batched with headers), carrying a 1-sentence overlap within the same section, prepending the section breadcrumb
Deep dive 3: hybrid retrieval and citation-grounded generation
1. Parallel hybrid search + Reciprocal Rank Fusion (RRF). Given a user query (rewritten into a standalone query if part of a multi-turn chat), we run dense vector search (top 50) and BM25 keyword search (top 50) in parallel, both pre-filtered by
tenant_id,acl_groups, andactive = true. Because cosine similarity (0.81) and unbounded BM25 scores (14.7) live on incompatible scales, we merge them using Reciprocal Rank Fusion, which combines rank positions without score calibration:def reciprocal_rank_fusion(ranked_chunk_lists, k: int = 60): """Merge multiple ranked ID lists using 1 / (k + rank); higher fused score wins.""" fused_scores = {} for ranked_ids in ranked_chunk_lists: for rank, chunk_id in enumerate(ranked_ids, start=1): fused_scores[chunk_id] = fused_scores.get(chunk_id, 0.0) + 1.0 / (k + rank) return sorted(fused_scores, key=fused_scores.get, reverse=True)2. Authoritative permission and version check. Search index updates can lag PostgreSQL by a couple of seconds after an ACL revocation or document deletion. Before reranking our ~50 unique candidates, one fast primary-key lookup against PostgreSQL enforces immediate consistency:
SELECT doc_id, active_version FROM documents WHERE doc_id = ANY(:candidate_doc_ids) AND tenant_id = :tenant_id AND status = 'ACTIVE' AND acl_groups && :user_groups; -- PostgreSQL '&&' checks that the two arrays share >= 1 groupAny candidate chunk whose
(doc_id, version)is absent from this query result is discarded immediately.3. Cross-encoder reranking and abstention. A cross-encoder is a transformer that reads
(query, passage)concatenated together so every query word attends to every passage word — much more accurate than single-vector similarity, though too slow to run on all 500K chunks. Reranking <= 50 survivors on GPU takes ~50–120 ms. We keep the top 8 chunks above a calibrated relevance threshold; if zero chunks pass, we abstain cleanly without calling the generator.4. Closed-tag prompting and deterministic citation resolution. We format
build_source_units(top_8_chunks)into the LLM prompt with explicit source tags and page metadata, instructing the LLM to cite only[S1a]-style tags before each sentence's period and never write raw page numbers:System: Answer ONLY using the sources below. End every factual sentence with supporting source tags before the period, e.g. "... rated OD 5+ [S1a]." If the sources do not contain the answer, state that clearly. Never write page numbers yourself. [S1a] (Lab Safety Handbook, page 10) 3.4 Bay C: Laser goggles rated OD 5+ are mandatory... [S1b] (Lab Safety Handbook, page 11) ...visitors must sign the entry log before crossing...Application code then parses tags (handling both
[S1a]and grouped[S1a, S1b]) and maps them deterministically back to(doc_id, version, page_index, page_label, bboxes):import re TAG_BRACKET_RE = re.compile(r"\s*\[(S\d+[a-z](?:\s*[,;]\s*S\d+[a-z])*)\]") SINGLE_TAG_RE = re.compile(r"S\d+[a-z]") def resolve_citations(sentences, source_units): """Map closed-set [S1a] tags to exact page metadata; drop any hallucinated tag.""" unit_by_tag = {unit["tag"]: unit for unit in source_units} resolved = [] for raw_sentence in sentences: cited_units = [] for bracket_content in TAG_BRACKET_RE.findall(raw_sentence): for tag in SINGLE_TAG_RE.findall(bracket_content): if tag in unit_by_tag and unit_by_tag[tag] not in cited_units: cited_units.append(unit_by_tag[tag]) clean_text = TAG_BRACKET_RE.sub("", raw_sentence).strip() resolved.append({"text": clean_text, "citations": cited_units}) return resolved5. Entailment verification (including cross-page claims). Even with valid tags, an LLM might attach
[S2a]to a sentence actually supported by[S1a], or synthesize a cross-page sentence supported only by[S1a, S1b]together. An entailment cross-encoder (a fast natural-language-inference model scoring whether premise text logically implies a hypothesis sentence) verifies each sentence as it streams:def verify_citations(resolved_sentences, all_units, entails_fn, threshold: float): """Keep citations that logically support each sentence, checking combined spans too.""" for item in resolved_sentences: claim = item["text"] # 1. Check each cited single-page unit individually verified = [u for u in item["citations"] if entails_fn(u["text"], claim) >= threshold] # 2. Cross-page sentence: check cited units concatenated together if single units fell short if not verified and len(item["citations"]) > 1: combined_premise = " ".join(u["text"] for u in item["citations"]) if entails_fn(combined_premise, claim) >= threshold: verified = list(item["citations"]) # 3. Fallback: if the model cited the wrong tag, scan the 8 prompt units for true support if not verified: for candidate in all_units: if entails_fn(candidate["text"], claim) >= threshold: verified = [candidate] break item["citations"] = verified item["supported"] = len(verified) > 0 return resolved_sentencesEnd-to-end retrieval latency budget (
< 500 msp95 target):Query embedding (bi-encoder) ~15-30 ms Parallel HNSW vector top-50 || BM25 top-50 ~10-30 ms Reciprocal Rank Fusion + PostgreSQL ACL/version SQL ~5-10 ms Batched GPU cross-encoder reranking (<= 50 pairs) ~60-150 ms -------------------------------------------------------------- Total /v1/retrieve p95 ~100-230 ms (well under 500 ms) LLM first token: ~500-900 ms; sentence entailment runs concurrently with token streamingDeep dive 4: atomic version switching and purging stale chunks
Naive
"delete old chunks, then re-index"leaves a 10-minute hole where the PDF disappears from search. Naive"upsert over old chunks"mixes v1 and v2 paragraphs during ingestion. Instead, we use stage-new, atomic pointer flip, purge-old:Time ---> v1 chunks in index: [active=true ................................] [active=false] -> deleted v2 chunks in index: [ingest: active=false] -> [active=true ..........................] DB active_version : [ v1 ] *FLIP* [ v2 ] ^ Single atomic SQL UPDATE; readers ALWAYS see pure v1 or pure v2!Update workflow (
version n->version n+1):- Write
document_versions(doc_id, n+1, state='UPLOADED')unlessfile_sha256matches versionn. - Ingest and upsert all
n+1chunks under deterministic IDs"{doc_id}:{n+1}:{seq}"withactive = false. Versionncontinues serving cleanly. - Validate completeness: verify both HNSW and BM25 hold exactly
expected_chunksrecords for(doc_id, n+1)and OCR quality gates pass. - Set
active = trueonn+1chunks in both indexes. For ~1 second both versions pass index pre-filtering, while PostgreSQL'sactive_version = ncheck dropsn+1so versions never mix. - Flip the authoritative pointer atomically in PostgreSQL:
UPDATE documents SET active_version = :new_version, updated_at = now() WHERE doc_id = :doc_id AND status = 'ACTIVE' AND active_version < :new_version; -- prevents an older slow upload from overwriting a newer one- Set
active = falseon versionnchunks, invalidate retrieval cache keys tagged withdoc_id, and delete versionnchunks from both indexes after a short grace window (state = 'PURGED'). Keep old page PNGs per retention policy so historical answer links keep rendering.
Instant deletes and safety nets:
- Delete:
UPDATE documents SET status = 'DELETING'hides the document from the PostgreSQL post-check in milliseconds, followed by asynchronous index deletion, object-store cleanup, zero-count verification, andstatus = 'DELETED'. - Daily orphan sweeper: scans
(doc_id, version)groups in HNSW and BM25 and deletes any group that is neitheractive_versionnor currently ingesting, healing any worker crash mid-purge. - Blue/green index rebuilds (building a fresh index alongside the live one and swapping an alias once validated) handle embedding-model or parser upgrades with instant rollback.
- Write
ML evaluation: labels, models, and offline metrics
To improve an ML pipeline systematically, we evaluate parsing, retrieval, and generation separately rather than eyeballing end-to-end answers:
-
Evaluation datasets:
- Golden QA set (~500 questions): curated with domain experts and stratified across native prose, two-column pages, tables, scanned OCR pages, cross-page paragraphs, plus 10% unanswerable questions, each annotated with gold
(doc_id, page_index, span)and reference answer. - Parsing benchmark (~200 annotated pages): ground-truth reading order, HTML table cell trees, and scan transcriptions.
- Citation-entailment set (~500 sentence-unit pairs): human-labeled
supported / unsupportedto calibrate our verifier threshold and validate any LLM-as-judge (checking human-judge agreement via Cohen's kappa, a chance-corrected agreement score from-1to1, requiringkappa >= 0.80).
- Golden QA set (~500 questions): curated with domain experts and stratified across native prose, two-column pages, tables, scanned OCR pages, cross-page paragraphs, plus 10% unanswerable questions, each annotated with gold
-
Stage-by-stage offline metrics:
- Parsing: OCR Character Error Rate (CER), reading-order pairwise accuracy, header/footer removal precision & recall, and TEDS (Tree-Edit-Distance-based Similarity, scoring HTML table row/column tree accuracy).
- Retrieval: page-level Recall@8 (fraction of answerable questions where all gold supporting pages appear in the top 8 retrieved chunks), MRR (Mean Reciprocal Rank,
1 / rankof the first gold hit), and nDCG@10 (Normalized Discounted Cumulative Gain, rewarding placing all gold chunks near rank 1), broken down by stratum (tables and scans almost always trail prose!). - Generation: citation precision (share of emitted citations whose page unit genuinely supports the sentence, release gate
>= 0.95), citation recall (share of factual claims backed by a valid citation), exact-page accuracy, and unanswerable abstention rate (gate>= 0.80).
-
Serving, scaling, failure modes, monitoring, and A/B testing
Serving & caching
- Indexes: 3 stateless Retrieval pods backed by 3 in-RAM HNSW replicas (~2.1 GB each) and 2 BM25 replicas.
- Permission-safe caching: cache query embeddings (
query_text -> float32[1024]) and raw candidate lists keyed by(normalized_query, hash(sorted_user_groups)), tagged bydoc_idfor invalidation on updates. Every cache hit still runs the 5 ms PostgreSQLdocumentscheck so ACL revocations and deletes take effect immediately. - Ingestion fairness: per-tenant fair queuing prevents one 500-PDF bulk upload from starving single-file updates.
Graceful failure handling
Component failure System behavior OCR / parse fails on v(n+1)Mark v(n+1)FAILEDafter retries;v(n)stays live uninterrupted; alert owner.BM25 index unavailable Degrade to dense HNSW retrieval only; emit degraded-mode metric. GPU reranker overloaded/down Bypass reranker and take top 8 from RRF fusion; citations stay verified. LLM provider down / timeout Fall back to /v1/retrieveUI: show top cited page snippets with highlight boxes.PostgreSQL Metadata DB down Fail closed ( 503): never serve unverified permissions or deleted documents.Production monitoring & online A/B testing
- Alerts: p95 ingestion lag > 10 min, OCR mean confidence drop, non-zero orphan chunks after daily sweep, spike in unsupported-sentence verifier flags, empty-retrieval rate, or p95
/retrieve> 500 ms. - Online A/B test: randomize at the user level (
hash(user_id)) so a user sees consistent behavior across follow-up questions; index/chunking changes read from blue/green indexes. Primary metric: helpful-rating rate and citation click-through without wrong-citation report; guardrails: verifier unsupported-sentence rate across all traffic (unbiased by who clicks thumbs-up), latency, and cost per query. Compute variance using user-clustered standard errors over at least a full 7-day business cycle.
Summary of key design choices
- Deterministic PDF text/boxes + layout/table models + token-checked VLM fallback: preserves exact text and highlight coordinates while still handling complex tables and scans.
- Cross-page chunks for retrieval, single-page
S1a/S1bunits for prompting: keeps semantic context intact across page breaks while guaranteeing every citation tag maps to exactly one page. - Closed-set tags + entailment verification: code — never the LLM — emits page numbers, eliminating digit hallucinations and front-matter offset bugs.
- Hybrid HNSW + BM25 + cross-encoder reranking on unsharded 2 GB RAM replicas: sub-250 ms p95 retrieval over both semantic paraphrases and exact identifiers without premature sharding complexity.
- Stage-new, atomic pointer flip, purge-old + PostgreSQL post-check: zero downtime during updates, instant deletes and ACL revocations, and zero mixed-version answers.
Intuition & how it works
Think of this system like a meticulous legal paralegal preparing a tabbed evidence binder for a judge. First, in the back office (offline ingestion), the paralegal takes messy two-column contracts, spreadsheets, and faded photocopies, transcribes them cleanly in true human reading order, and stamps the exact binder tab and bounding box onto the back of every paragraph card. Later, when a lawyer asks a live question (online RAG, or Retrieval-Augmented Generation — retrieving relevant source passages and placing them into a language model's prompt so it answers from evidence rather than memory), the paralegal pulls the 8 best cards, slices any card that crosses a page turn into single-page pieces labeled with sticky codes like [S1a] and [S1b], asks the drafter (the LLM) to cite only sticky codes, swaps each code back to its stamped page number in software, and has a fact-checker verify that each cited page actually proves its sentence.
A naive RAG pipeline fails on real-world PDFs at every step. Feeding a PDF to a plain text extractor reads straight across two-column layouts into garbled sentences, flattens tables into unlabelled number soup, and returns empty strings on scanned images that need OCR (Optical Character Recognition, converting pixel images of text into characters). Slicing that raw text into blind 500-word chunks loses track of where page 12 ended and page 13 began, asking the LLM to type page numbers directly invites digit hallucinations or Roman-numeral cover-page offset errors ("iv" vs PDF page 4), and updating a file via "delete old chunks, then re-index" makes the document vanish from search for several minutes.
Walk through a concrete 4-step trace on a 50-page Lab Safety Handbook PDF (doc_id = "doc_42", version = 1):
- Multimodal ingestion: Physical PDF page 14 has two columns and a rule at the bottom (
"Laser goggles rated OD 5+ are mandatory inside Bay C.") that continues onto the top of page 15 ("Visitors must sign the entry log before crossing the yellow line."), above a footer reading"Page 10 of 46"(shifted by 4 Roman-numeral front-matter pages). Layout detection + recursive XY-cut (splitting whitespace gaps so Column 1 finishes before Column 2) strips the repeating footer after recordingpage_label = "10", and stores one coherent chunk (doc_42:1:19) with two character-levelpage_spans: chars0..53-> PDF page14(label"10"), chars54..119-> PDF page15(label"11"). - Hybrid retrieval + permission check: An engineer asks "What eyewear and entry rules apply to Bay C?" Dense vector search (HNSW, an in-memory nearest-neighbor graph) and keyword search (BM25, exact term-frequency matching) each fetch 50 candidates, merge them via Reciprocal Rank Fusion (
1 / (60 + rank)), verify in PostgreSQL thatdoc_42is'ACTIVE'onversion = 1and matches the engineer'sacl_groups, and pass survivors to a GPU cross-encoder (a model scoring query and passage together) to pick the top 8 chunks in ~160 ms. - Single-page tagging & verified generation: Because chunk
doc_42:1:19spans two pages, the prompt builder splits itspage_spansinto[S1a](PDF p. 14 / label"10") and[S1b](PDF p. 15 / label"11"). The LLM generates "Bay C requires OD 5+ laser goggles and a signed visitor entry log before crossing the yellow line [S1a, S1b]." Code resolves[S1a, S1b]to pages 14 and 15, and an entailment model (scoring whether premise text logically proves a claim) verifies thatS1a + S1btogether support the sentence. - Concurrent update (
v1 -> v2): While engineers queryv1, EHS uploadsv2. Workers ingestdoc_42:2:*withactive = false, verify chunk counts, setactive = true, flipdocuments.active_version = 2in one atomic SQLUPDATE, and asynchronously purgedoc_42:1:*— zero downtime and zero mixed-version answers.
Key trade-offs
- Structured parsing pipeline vs. calling a vision-language model (VLM) on every page. Sending every page image to a VLM for Markdown is simple to build and strong on messy layouts, but VLMs lack exact word-level bounding boxes for UI highlighting, cost far more per page, and occasionally invent or alter numbers. Using native text extraction + OCR + layout/table models as the deterministic base, and invoking a token-verified VLM only on low-confidence tables, preserves exact provenance at a fraction of the cost.
- Cross-page chunks with
page_spansvs. strict single-page chunks. Cutting every chunk at page boundaries makes page numbers trivial to store, but slices sentences and tables in half at page breaks, hurting retrieval recall. Tracking character-rangepage_spanson section-bounded ~400-token chunks and splitting them into single-pageS1a/S1bunits at prompt time gives coherent retrieval and exact single-page citations, in exchange for slightly richer chunk metadata. - Closed-set tag citations (
[S1a]) vs. LLM-generated page numbers. Asking the LLM to output(Document, Page 12)saves a tiny regex parser, but allows digit transpositions, unvalidatable numbers, and printed-label vs. physical-index confusion. Closed-set tags guarantee every surviving citation points to a real page and bounding box that was actually in the prompt. - Hybrid (HNSW + BM25) + GPU cross-encoder vs. vector-only retrieval. Running a single vector index is operationally simpler, but embeddings blur exact policy codes, part numbers, and SKUs, and bi-encoder top-8 precision lags behind a cross-encoder. Adding BM25 + GPU reranking raises Recall@8 and precision substantially, at the cost of running two index types and ~60–150 ms of GPU reranking latency.
- Streaming sentence verification vs. blocking until full verification. Streaming answer tokens while running entailment sentence-by-sentence keeps time-to-first-token near ~1 second (citation chips light up right after each sentence), whereas buffering the whole response prevents an unsupported sentence from ever flashing on screen at the cost of 2–4 seconds of upfront wait.
- Index pre-filtering + PostgreSQL post-check vs. index-only filtering. Pre-filtering inside HNSW/BM25 avoids scanning unauthorized chunks, while the 5 ms PostgreSQL post-check closes the asynchronous replication lag window after deletes or ACL revocations — trading a tiny SQL query per request (and failing closed if PostgreSQL is down) for strict security and version consistency.
Common mistakes
- Letting the LLM type raw page numbers in prose, leading to hallucinated page numbers and no bounding boxes for UI highlighting.
- Writing a citation regex that only matches single tags like
[S1a], which fails whenever the model groups citations as[S1a, S1b]and leaves ugly raw brackets in the user-facing answer. - Checking entailment only one page unit at a time, which falsely flags legitimate cross-page claims supported jointly by
[S1a, S1b]at a page break. - Confusing the PDF's 1-based physical
page_indexwith the printedpage_label, causing citations in manuals with cover pages or"i, ii, iii"prefaces to land several pages off. - Extracting multi-column pages without layout reading-order reconstruction, weaving left-column and right-column lines together into nonsense.
- Flattening tables into plain whitespace-separated text, severing numbers from their row and column headers, or splitting wide tables across chunks without repeating the column header row.
- Running OCR blindly on every page (corrupting clean digital text and wasting GPUs) or skipping OCR (silently indexing scanned PDFs as empty).
- Deleting old chunks before indexing an updated PDF (causing a multi-minute search blackout) or upserting without a version ID (leaving orphaned tail chunks when v2 is shorter than v1).
- Sharding a ~2 GB vector index across distributed partitions, adding network hops and operational failure modes when the entire 500K-vector index fits comfortably in RAM on replicated nodes.
- Enforcing permissions after LLM generation (leaking restricted facts into synthesized prose) or sharing an answer cache across users in different permission groups.
Follow-up questions
- How would you evaluate retrieval quality specifically with respect to page-citation accuracy? Build a stratified golden evaluation set (~500 expert-verified questions covering prose, multi-column layouts, tables, scans, cross-page facts, and ~10% unanswerable questions), where each answerable item records the exact gold
(doc_id, page_index, char_span)supporting it. Evaluate the retrieval component in isolation with page-level Recall@k (whether every required goldpage_indexappears among thepage_spansof the topk = 8chunks sent to the LLM) and MRR (Mean Reciprocal Rank,1 / rankof the highest-ranked chunk containing the gold page). Then evaluate end-to-end citation accuracy with citation precision (fraction of emitted citations verified as entailing their sentence), citation recall (fraction of factual claims carrying a supporting citation), and exact-page vs. off-by-N error rates (an off-by-constant error immediately diagnoses apage_labelvs.page_indexbug). In production, track the entailment verifier's unsupported-sentence rate and user"wrong citation"feedback reports. - How would you keep recurring page headers and footers from polluting chunk embeddings? Combine visual layout detection with a document-wide margin frequency pass before chunking. First, the layout detector classifies
PAGE_HEADERandPAGE_FOOTERregions visually; second, a statistical pass inspects lines sitting inside the top or bottom 8% vertical band of each page, normalizes digits ("Page 3 of 50"and"Page 42 of 50"both become"page # of #"), and flags lines appearing on at least 30% of pages (using 30% rather than 50% catches alternating left/right headers in bound documents). Extract any printedpage_labelfrom the footer (or the PDF's/PageLabelscatalog) first, then strip flagged lines only when they appear inside the top/bottom margin band so matching words inside body paragraphs or tables are never removed, and place the document title once cleanly in the chunk's contextualheader. Verify on the golden set that Recall@8 improves without regressing recall on short 2–3 page memos. - How would you enforce permissions so queries only surface content from PDFs the caller is allowed to read? Enforce access control at both candidate retrieval time (pre-filtering) and pre-prompt verification time (authoritative post-check), never after LLM generation. Store authoritative
tenant_idandacl_groupsondocumentsin PostgreSQL and replicate them onto every chunk in HNSW and BM25 so searches pre-filter totenant_id = user.tenant AND acl_groups OVERLAPS user.groups— avoiding the "post-filter starvation" bug where an unfiltered top-50 returns zero allowed chunks for a user who can view only 1% of the corpus (at 1% selectivity = 5,000 vectors, exact brute-force scoring over the allowed bitmap also runs in <5 ms). Before reranking or building the prompt — including on retrieval cache hits — run one indexed SQL check (SELECT doc_id, active_version FROM documents WHERE doc_id = ANY(:ids) AND status = 'ACTIVE' AND acl_groups && :user_groups) so permission revocations and deletions take effect instantaneously rather than waiting for async index updates, failing closed (503) if PostgreSQL is unreachable. Finally, namespace any retrieval cache byhash(sorted_user_groups)and write an immutable audit log recording whichdoc_ids fed every generated answer.
Follow-up questions
- How would you evaluate retrieval quality specifically with respect to page-citation accuracy?
- How would you keep recurring page headers and footers from polluting chunk embeddings?
- How would you enforce permissions so queries only surface content from PDFs the caller is allowed to read?
Similar questions
- Selecting Sorting Algorithms Under Production Constraints
- Batch Document Embedding and Filtered Vector Retrieval
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models
- Hybrid Talent Search and Ranking Architecture