Design a document processing pipeline with human review
Every finance and legal team has a pile of PDFs that someone retypes into a system: invoices into the ERP, contract terms into the CLM, claims into the policy system. LLMs and vision-language models have made extraction dramatically better, but "better" is not "always right," and a wrong bank account number on an invoice is a real loss. So the design is less about the model and more about the pipeline around it: classify, extract, validate, decide confidence, and send the right fields (not whole documents) to humans.
Requirements
Functional
- Ingest documents from email inboxes, uploads, SFTP and APIs: PDFs (digital and scanned), images, Word files.
- Classify document type (invoice, credit note, contract, receipt, other) and split multi-document files.
- Extract a schema per type: invoice header, line items, totals, tax, vendor bank details; contract parties, dates, renewal terms, liability caps.
- Validate against business rules and reference data (vendor master, purchase orders).
- Route low-confidence or failed-validation fields to a review UI; post approved results downstream.
Non-functional
- Field-level accuracy targets per field (higher for amounts and bank details than for descriptions).
- Every value traceable to a location on a page (bounding box) and to who approved it.
- Throughput for month-end peaks; latency measured in minutes, not milliseconds.
- PII and confidentiality: documents encrypted, access by role, retention rules.
Scale estimates (assumptions)
| Quantity | Assumption | Result |
|---|---|---|
| Documents per month | 3M | about 1.2 per second average |
| Month-end peak | 5x for 3 days | about 6/s sustained |
| Pages per document | 3 average | 9M pages/month |
| Fields per document | 25 header plus line items | |
| Straight-through rate | 80% target | 600,000 documents/month touch a human |
| Review time | 45 seconds per flagged document | about 7,500 reviewer hours/month |
The last two rows are the business case. Raising straight-through processing from 80% to 90% halves human workload, so confidence calibration matters more than squeezing another point of raw accuracy.
High-level architecture
Rendering diagram…
Request flow
Rendering diagram…
Components
| Component | Responsibility | Notes |
|---|---|---|
| Ingestion | Receive files, compute content hash, dedupe, virus scan | Duplicate invoices are a classic fraud and error source |
| Pre-processing | Split bundles, fix rotation, OCR scanned pages | Digital PDFs keep their text layer; scanned ones need OCR |
| Layout parsing | Reading order, tables, key-value regions | Docling, cloud document AI services, or layout models |
| Classifier | Document type and routing | Small model or VLM call; cheap and fast |
| Extractor | Fill the schema per type | VLM with page images and OCR text, or a specialized extraction model |
| Validator | Arithmetic, formats, reference data, cross-field rules | Deterministic code; the most reliable component you have |
| Confidence router | Decide straight-through vs review per field | Thresholds tuned per field and per vendor |
| Review UI | Show flagged fields next to the highlighted page region | Keyboard-first; reviewers process hundreds per day |
| Corrections dataset | Store every human change | Eval set and training data |
Data model
CREATE TABLE documents (
id UUID PRIMARY KEY,
tenant_id UUID,
source TEXT,
content_hash TEXT,
doc_type TEXT,
status TEXT, -- received | extracted | in_review | approved | posted | rejected
received_at TIMESTAMPTZ
);
CREATE TABLE extracted_fields (
document_id UUID,
field_path TEXT, -- "invoice.total", "line_items[2].amount"
value TEXT,
normalized JSONB, -- typed value: amount plus currency, ISO date
confidence REAL,
page INT,
bbox REAL[4],
extractor_ver TEXT,
validation TEXT[], -- failed rule ids
PRIMARY KEY (document_id, field_path)
);
CREATE TABLE reviews (
document_id UUID,
field_path TEXT,
old_value TEXT,
new_value TEXT,
reviewer_id UUID,
reason TEXT,
reviewed_at TIMESTAMPTZ
);
Field-level rows (rather than one JSON blob per document) are what make field-level routing, accuracy metrics and audit trails easy.
Deep dives
Choosing the extractor
Three families, often combined:
- Managed document AI services (AWS Textract, Azure Document Intelligence, Google Document AI) with prebuilt invoice and receipt models. Fast to adopt, decent confidence scores, limited flexibility.
- Layout-aware open models and parsers such as Docling (which uses layout analysis and a table-structure model) to turn pages into clean structured text and tables, then an LLM fills the schema.
- Vision-language models given page images plus OCR text and a JSON schema. Most flexible, handles messy layouts and new document types with no training, but you must build your own confidence signals.
For invoices I would start with a VLM plus structured outputs against a strict schema, with OCR text included to reduce transcription errors on numbers. For high-volume vendors with fixed templates, cheaper specialized models can take over later.
Confidence that means something
LLMs do not give calibrated confidence for free. Useful signals:
- Agreement between two independent extractions (different model, or same model with different prompts).
- Whether the value appears verbatim in the OCR text near the claimed bounding box.
- Validation results (totals add up, tax rate is plausible, date is in range).
- Vendor history: a vendor whose invoices were always correct before earns a lower review rate.
Combine them into a per-field score, then set thresholds per field using the corrections dataset: pick the threshold that keeps the error rate on auto-approved values below target. Bank details and totals get strict thresholds; free-text descriptions get loose ones.
Validation is the backbone
Most real errors are caught by plain code: line items sum to subtotal, subtotal plus tax equals total, currency matches vendor, PO number exists and amounts match within tolerance (three-way match with goods receipt), invoice number not already paid. A changed bank account always goes to review regardless of confidence, since it is the most common invoice fraud pattern.
Designing the review UI
Reviewers should never re-key a whole document. Show only flagged fields, with the source region highlighted on the page image, prefilled values, and keyboard shortcuts to accept or correct. Record why they changed something (OCR error, wrong field, missing). Measure reviewer time per document; it is the cost driver.
Learning from corrections
Every correction is a labeled example. Use them three ways: as a growing eval set (run it on every prompt or model change), to tune confidence thresholds, and to add few-shot examples or fine-tune extraction for difficult vendors. Watch for drift when a big vendor changes its invoice template.
Trade-offs and pitfalls
- Document-level vs field-level review. Sending whole documents to humans wastes most of their time. Route fields.
- Trusting model confidence. Self-reported confidence ("I am 95% sure") is poorly calibrated. Use external signals.
- Line items are hard. Tables spanning pages, merged cells and missing borders break naive extraction. Use table-structure models and validate sums.
- Hallucinated values. A VLM may invent a plausible PO number. Require values to be grounded in page text where possible.
- Idempotent posting. Retries must not post the same invoice twice to the ERP. Use the document id as an idempotency key and check duplicates by vendor plus invoice number.
- Data handling. Contracts and invoices are confidential. Use providers with zero data retention or self-hosted models where required, and encrypt at rest.
Checklist
- Ingestion dedupes by content hash and by vendor plus invoice number.
- Extraction uses a strict schema per document type with bounding boxes.
- Deterministic validation covers arithmetic, formats and reference data.
- Confidence is computed from external signals and thresholds are set per field from real corrections.
- Bank detail changes always go to review.
- Review UI shows only flagged fields with highlighted source regions.
- Corrections feed an eval set that gates every model or prompt change.
- Posting downstream is idempotent and fully audited.