Design a production-grade AI-powered Intelligent Document Processing (IDP) system

    Organizations across insurance, banking, healthcare, logistics, and government all face the same intake problem: a flood of documents — invoices, claims, applications, contracts, KYC packets, forms — arriving as PDFs, scans, faxes, and email attachments. A production Intelligent Document Processing (IDP) system turns that unstructured intake into trusted, structured data that downstream systems (underwriting, payments, case management) can act on directly. The hard part isn't calling an LLM on a PDF — it's engineering for trust and throughput at scale. A single extraction model tops out around ~80% field accuracy, which sounds fine until you multiply it across millions of fields a day: naively routing every uncertain field to a human reviewer builds a queue that grows faster than any team can staff it. The real design problem is deciding, stage by stage, when a deterministic rule should beat a probabilistic model, and how to keep that ~20% error rate from becoming an operational bottleneck. This reference architecture treats the human-in-the-loop review queue as a first-class engineering problem — not an afterthought — and hardens every stage of the pipeline for production: reliability, security, compliance, and observability included. (Educational reference, not legal advice.)

    AI & Machine Learning, 23 components, about 55 min

    1. Scope

    In scope

    • • Multi-channel intake (upload/API, fax, email, scan/mobile) with an immutable, versioned store
    • • Classification, OCR, and field extraction across structured and unstructured documents
    • • Raising EFFECTIVE accuracy: an LLM ensemble/consensus + deterministic auto-verification against systems of record
    • • A confidence-calibrated gate that sends only uncertain FIELDS to review, plus an active-learning loop that shrinks the queue
    • • Production operations: reliability (idempotency, DLQ, autoscaling), safe model deployment, SLOs, DR
    • • Compliance & security: encryption, residency, PII/PHI redaction, WORM audit, tenant isolation
    • • Observability + MLOps: tracing, evals, calibration + drift monitoring

    Out of scope

    • • Downstream business logic that consumes the structured output (underwriting, payments, adjudication)
    • • Any one organization or the verbatim text of a specific regulation (illustrative only)
    • • Foundation-model pre-training; we serve hosted / fine-tuned models
    • • End-user experiences beyond the reviewer console

    2. Functional requirements

    Must have

    • • Ingest a document from any channel and persist an immutable, versioned copy before processing
    • • Classify document type and extract required fields with a calibrated confidence per field
    • • Verify fields against systems of record + business rules and auto-correct deterministic errors
    • • Route only genuinely-uncertain fields to review; auto-approve consensus / high-confidence fields
    • • Emit structured output to the system of record with full lineage to the source page
    • • Capture every human correction and feed it back to improve the models
    • • Produce an immutable audit trail for every document, field, and decision

    Nice to have

    • • Straight-through processing for known, clean form types
    • • Human-on-the-loop sampling QA over the auto-approved stream
    • • Multi-language OCR and extraction
    • • Real-time status webhooks to submitting systems

    3. Non-functional requirements

    Effective field accuracy≥ 99% on auto-approved fields— Gate-enforced via ensemble + verification — not assumed from one ~80% model
    Automation rate≥ 90% of fields straight-through— Improves over time via active learning
    ThroughputLinear scale to peak— Stateless workers autoscale on queue depth
    Turnaroundp95 < 5 min automated; < 15 min if reviewed
    Availability / durability99.9% intake; no document ever lost— Store is the replayable source of record
    Privacy & residencyRedact before third-party calls; data + inference region-pinned
    AuditabilityEvery field → source page + model/prompt version (WORM)
    RecoverabilityIdempotent, replayable pipeline; RPO (recovery point objective) ≈ 0 on the store

    4. Back-of-envelope estimation

    Assumptions

    • • ~250,000 documents/day, average 5 pages (~1.25M pages/day)
    • • ~15 extracted fields per document
    • • ~30% of documents are unstructured (need the LLM ensemble)
    • • Single-model field accuracy ~80%; 3-model ensemble ≈ 90%; + auto-verify ≈ 97% effective
    • • Volume concentrated in ~10 business hours; page image ~150 KB
    • • Long-tail documents (KYC packets, contracts) can run 50-200+ pages; the Context Window Manager splits these into overlapping windows so a single call never exceeds the model's context budget.

    Derived numbers

    Avg page throughput~35 pages/s— 1.25M / (10 × 3600)
    Peak page throughput~100 pages/s— ~3× average
    Naïve review load~750k field-checks/day— 20% × 15 fields × 250k — the bottleneck
    After ensemble + verify~110k field-checks/day— ~3% flagged × 15 × 250k (≈7× lower)
    Reviewers needed~55— 110k ÷ (~300 fields/hr × ~7 hrs) — vs ~360 naïve
    Storage / year~68 TB/yr— 1.25M pages × 150 KB × 365

    5. API design

    POST/api/documents

    Submit a document (multipart or presigned) → { docId, status }; idempotency-key dedupes

    GET/api/documents/{docId}

    Status + extracted fields, per-field confidence, and verification state

    POST/api/documents/{docId}/review

    Reviewer submits field-level corrections → re-verified, written to SoR, logged for learning

    GET/api/documents/{docId}/audit

    Immutable lineage / audit trail for the document and every field

    POST/internal/intake/{channel}

    Channel adapters (fax / email / scan) push new documents

    6. High-level design

    What each box in the reference diagram is responsible for:

    Intake Gateway — Authenticates the channel, virus-scans, de-duplicates by content hash + idempotency key, assigns a docId. Every document is accepted and persisted before processing.
    Document Store — Immutable, versioned, encrypted, residency-pinned object store — the replayable source of record for every original page.
    Classifier — Identifies document type/layout. Deterministic rules/templates for known types; a vision/LLM classifier only when the layout is ambiguous.
    Router — Deterministic: detects format, splits multi-doc bundles, normalizes pages, and routes known layouts to the parser, unknown to the ensemble.
    OCR + Layout — Deterministic text + bounding-box extraction (Textract / Document AI / Tesseract). Tokens carry coordinates for lineage.
    PII / PHI Redaction — Detects and masks sensitive spans before any content leaves the trust boundary for a third-party model call.
    Context Window Manager — Splits long, unstructured documents into overlapping N-page windows sized to the target model's context budget before they reach the LLM Ensemble; reassembles and reconciles extracted fields across window boundaries.
    Template Parser — Deterministic extraction for fixed-layout forms via anchored rules + checksums. Fast, cheap, auditable — the default when the layout is known.
    LLM Ensemble — For unstructured docs: N models (or prompts/temperatures) extract to a strict schema; majority vote lifts effective accuracy above any single ~80% model and yields an agreement signal.
    Reference KB (RAG) — Retrieves product/domain/reference context to ground context-dependent fields; vector + graph store.
    Prompt Cache — Caches the model-side computation for the stable prompt prefix (system instructions, extraction schema, few-shot examples) so repeated Ensemble and Judge calls skip re-processing it — cutting cost and latency on every cache hit.
    Orchestrator — Sequences the pipeline (LangGraph-style), applies prompt caching on stable context, and routes by document type, confidence, and cost.
    LLM-as-Judge — Scores faithfulness of each extracted field with self-consistency; contributes to the calibrated confidence.
    Rule Validators — Deterministic checks: checksums, cross-field consistency, format/regex, reference-data lookups. Hard business rules never live in a probabilistic step.
    Auto-Verify & Correct — Cross-checks each field against systems of record and reference data; deterministically corrects verifiable errors and flags the rest — the biggest lever for keeping humans off the path.
    Calibrated Gate — Uses calibrated confidence (ensemble agreement + judge + validators + verification) against per-field, per-type thresholds to auto-approve or send that FIELD to review.
    Field-Level Review — Reviewer console showing the page, value, and source box — only for flagged fields, batched by type. Fast, auditable, and the source of learning labels.
    System of Record — Receives approved structured output with lineage attached; downstream systems consume it.
    Observability — OTEL spans → Langfuse; latency, cost, token, confidence, calibration, and automation-rate metrics per stage.
    Active Learning — Turns corrections into eval sets + few-shot/fine-tune examples, updates models behind shadow+canary rollouts, and tunes thresholds — shrinking the review queue over time.

    7. Data model

    Object store (S3/Blob): raw pages keyed by docId/version — immutable, encrypted, residency-pinned— WORM + retention; replay source
    PostgreSQL: documents(doc_id PK, type, status, source_channel, received_at, residency, retention_until)— Pipeline state
    PostgreSQL: fields(doc_id FK, name, value, method, confidence, agreement, verified, source_page, bbox, model_version, prompt_version)— Per-field lineage + verification
    Vector + graph: reference KB chunks + embeddings + entity links— RAG grounding; reindexed + eval-gated on updates
    Example bank: corrections(doc_id, field, predicted, corrected, reviewer, ts)— Feeds evals + few-shot / fine-tune
    Append-only audit log: events(doc_id, field?, actor, action, from_state, to_state, model_version, prompt_version, ts)— WORM audit trail
    Queue (Kafka/SQS): stage topics + review queue + dead-letter queue— Backpressure, idempotent retries, DLQ

    8. Deep dives

    Beating the human-in-the-loop bottleneck at ~80% base accuracy

    This is the crux. A single model at ~80% per-field accuracy means, on a 15-field document, an average of 3 wrong fields — naïvely routing every uncertain field to a person is ~750k checks/day and does not scale. The system attacks it on five fronts. (1) ENSEMBLE / CONSENSUS: run N independent extractions (different models, prompts, or seeds); where they agree — the common case — auto-approve, where they disagree escalate. Three ~80% models voting land near ~90% with a free disagreement signal. (2) AUTO-VERIFICATION: deterministically cross-check each field against systems of record, reference data, and business rules (does this ID exist? does the total equal the line items? is this a valid date?) — many "errors" are caught and CORRECTED with no human, pushing effective accuracy toward ~97%. (3) CONFIDENCE CALIBRATION: raw model probabilities are not trustworthy, so calibrate them (temperature scaling / isotonic) against held-out labels; a well-calibrated 95% can be safely auto-approved, so you review only what is genuinely uncertain. (4) FIELD-LEVEL, not document-level, review: a reviewer fixes the two flagged fields, not the whole 15-field doc, and similar exceptions are batched/clustered so one decision resolves many. (5) THE FLYWHEEL: every correction becomes an eval + few-shot/fine-tune example, so accuracy rises and the flagged fraction — and the queue — shrinks month over month. Net: ~750k → ~110k checks/day (~55 reviewers vs ~360), trending down.

    Deterministic vs. probabilistic: the decision rubric

    The guiding principle: use the cheapest, most auditable step that can be correct, and reserve the LLM for genuine ambiguity. For a fixed-layout form with a regulated or critical field — an ID, a date, a dollar amount — route to the deterministic template parser plus checksum/reference validation; it's fast, cheap, and easy to defend in an audit. For a variable layout or a semantic field — free text, stated intent — route to the LLM ensemble, but never let its output stand alone: it's always followed by the judge, the validators, and verification. The same split applies one level up. A hard business rule — eligibility, a limit, a total that must reconcile — is never owned by a probabilistic step; it lives in the deterministic validators. Classification follows suit: known templates match deterministically, and only genuinely ambiguous documents pay the cost of a model call.

    Preserving quality without runaway cost

    Ensembles and verification cost more per document than a single model call, so spend gets engineered just as deliberately as accuracy. Prompt caching on the stable prefix — system instructions, schema, reference context — cuts input cost and latency by up to ~90% on cache hits. Model routing tries a single cheap model first and only escalates to the full ensemble when confidence is low or the field is high-stakes, so most documents never touch the expensive path. Batching amortizes the remaining calls, and the judge gates acceptance against calibrated thresholds instead of defaulting straight to a paid human review. Cost, accuracy, and automation rate are all tracked per stage, so none of these trade-offs are invisible — a routing change that saves money but quietly tanks accuracy shows up immediately, not a quarter later.

    Production reliability & safe deployment

    Every stage of the pipeline is idempotent and keyed by (docId, version, stage), so a transient OCR or model failure simply re-runs without duplicating side effects. Messages that keep failing land in a dead-letter queue for inspection instead of blocking the pipeline, and — because the original documents are stored immutably — an entire run can be replayed from scratch if something needs to be reprocessed. Workers themselves are stateless and autoscale on queue depth, with backpressure protecting downstream systems during a traffic spike. Model and prompt changes never ship as a blind swap. They go out behind a SHADOW stage (scored silently against live traffic, with no user-facing effect) and then a CANARY (a small percentage of real traffic, with automatic rollback if eval metrics or calibration regress). Services deploy blue/green, SLOs on latency, cost, and accuracy are alerted on, and a documented disaster-recovery/replay path covers the worst case.

    Compliance, security & auditability

    Compliance is designed in from the start, not bolted on afterward. Original documents are stored immutably and encrypted, pinned to their required region — and inference is region-pinned too, so regulated data never crosses that boundary. PII/PHI is redacted before any content leaves for a third-party model call, and prompt/response logging is scoped so sensitive content is not retained where it should not be. Multi-tenant deployments isolate each tenant's data with least-privilege access. Every field carries full lineage — source page, bounding box, extraction method, model and prompt version — and every state transition is written to an append-only, write-once/read-many (WORM) audit log. Retention and deletion honor whichever clock applies (GDPR, HIPAA, SOC 2, and region-specific regimes are examples, not an exhaustive list), so any decision the system made is reconstructable years later.

    Observability, calibration & drift

    A partly-probabilistic pipeline fails quietly unless it's instrumented for it. Every stage emits OpenTelemetry (OTEL) spans into an LLM-observability platform like Langfuse: latency, tokens, cost, per-field confidence, ensemble agreement, and — the metric that actually matters here — calibration, meaning predicted confidence versus actual accuracy on the reviewed sample, alongside the automation rate. That instrumentation is what turns a silent failure into a visible one: a model update that quietly lowers accuracy, or a reference KB that has gone stale, shows up as a metric instead of a customer complaint. Drift monitors specifically watch calibration and auto-approve rates; a sustained drop automatically tightens thresholds — routing more fields to humans — and can trigger a rollback while the issue gets investigated.

    Context-window management for long documents

    Average documents run ~5 pages, but the unstructured slice includes 50-200+ page KYC packets, loan files, and contracts — comfortably larger than most models' practical context budget once the system prompt, schema, and few-shot examples are already resident. Two failure modes follow: OVERFLOW (a call that exceeds the token limit either errors outright or gets silently truncated by an SDK/gateway, dropping whatever fell off the end) and HALLUCINATION (a model asked to reason over more text than it can attend to well tends to lose track of earlier pages and fabricate values instead of reporting them missing). The Context Window Manager sits between redaction and the ensemble and enforces a hard budget: documents are split into overlapping N-page windows (overlap sized to the largest field that could span a page break — a line-item table, a multi-page clause), each window is extracted independently against the same schema, and results are reconciled by matching on stable anchors (document ID, page number, table row) rather than concatenated. A field that appears in two overlapping windows with disagreeing values is treated the same as ensemble disagreement — routed to auto-verification, then to review if still unresolved, never silently picked. Prompt caching (see the Prompt Cache node) keeps the system prompt/schema prefix cheap to repeat across windows, so windowing does not multiply cost the way a naive per-page call would. The manager fails LOUD if a single page (a poster-sized architectural drawing, a dense financial table) exceeds even one window's budget — it flags the document for a specialized path rather than truncating it and returning a partial, unflagged answer.

    Why prompt caching pays for itself here

    On every extraction call, most of the prompt never changes: the system instructions, the extraction schema, and the few-shot examples are identical from one call to the next. Only the page text actually varies. Without caching, the model reprocesses that entire fixed prefix from scratch on every single call — and this pipeline makes a LOT of calls per document: N ensemble models × M overlapping page-windows from the Context Window Manager, plus a Judge pass scoring each extracted field. A 200-page KYC packet split into a dozen windows, extracted by three ensemble models, is 36+ calls that all share the same prefix. Prompt caching lets the model provider hold onto the internal computation for that fixed prefix for a short window after the first call, and reuse it on every subsequent call instead of recomputing it. In practice this means the pipeline pays full price once — the first call that "writes" the cache — and every call after that, within the cache's lifetime, only pays for the new page text. Providers typically bill cached prefix tokens at a steep discount versus fresh ones, and skip the reprocessing time too, so cache hits are both cheaper and faster to first token. This is exactly what keeps the Context Window Manager's overlapping-window strategy affordable: without a cache, splitting one document into a dozen windows would mean paying to reprocess the prefix a dozen times over. The trade-off: cache entries expire on a short time-to-live (typically minutes), and ANY change to the cached prefix — a tweaked system instruction, an updated schema, a swapped few-shot example — invalidates it and forces a fresh (expensive) write. So prefix edits are not free to make casually, and cache-hit rate is worth tracking as its own metric alongside the latency/cost/token metrics already flowing into Observability — a silent drop in hit rate shows up as a cost or latency regression before anyone traces it back to a stale cache.

    9. Bottlenecks

    • Human review is designed DOWN, not just tolerated — ensemble consensus, auto-verification, field-level batching, and the active-learning flywheel keep it off the critical path and shrink it over time.
    • OCR/GPU throughput at peak — smooth with queue backpressure, autoscaling, and batched inference.
    • Ensemble cost on the unstructured slice — mitigated by cheap-first model routing, prompt caching, and escalate-only-on-low-confidence.
    • Confidence calibration can drift as models/data change — monitor predicted-vs-actual and recalibrate; an over-confident gate silently leaks errors.
    • Reference-KB staleness feeds wrong context into RAG and verification — needs a reindex pipeline with eval gating on updates.
    • Very long or dense documents (100+ page KYC packets, oversized tables) can still exceed a single window's budget — the manager must fail loud and route to a specialized path rather than silently truncate, or overflow becomes an unflagged hallucination risk.

    10. Trade-offs

    Where to spend human review

    Choose: Per-field review driven by calibrated confidence and verification failures, not per document.

    Instead of: Review whole documents below a threshold: simpler queue, far more human time.

    Most fields on a flagged document are fine; reviewing only uncertain fields multiplies reviewer throughput.

    Model or rule

    Choose: Deterministic checks (checksums, totals adding up, lookups against systems of record) before and after the model.

    Instead of: Trust model confidence alone.

    A rule that verifies a field turns a probabilistic answer into a certain one for free.

    Hosted model or self-hosted

    Choose: Hosted models with redaction and regional endpoints, self-hosted only where residency rules demand it.

    Instead of: Self-host everything: control, at the cost of GPU operations and slower model upgrades.

    Residency and privacy decide this, not preference.

    11. Failure modes

    Confidence not calibrated after a model upgrade

    Wrong fields auto-approved.

    Mitigation: Re-fit calibration on a labelled holdout before release and sample auto-approved fields for QA continuously.

    New document layout appears

    Extraction accuracy drops for that type.

    Mitigation: Drift detection on layout and confidence; route to review and feed corrections into training.

    Review queue grows faster than staff

    Turnaround SLO missed.

    Mitigation: Prioritize by deadline and value, raise auto-approval only where QA supports it, and alert on queue age.

    12. What interviewers probe

    Answer each one yourself before opening it.

    How do you know a 0.9 confidence means 90% correct?Show a strong answer

    Measure calibration (reliability diagrams, expected calibration error) on labelled data and fit temperature or isotonic scaling per field type.

    How do you reprocess a million documents after a fix?Show a strong answer

    The immutable raw store plus versioned pipeline lets you replay through a backfill queue at a controlled rate, writing new versions rather than overwriting.

    How do you prove what the system decided and why?Show a strong answer

    Lineage per field: source page and bounding box, model and prompt version, confidence, verification results and reviewer action, in a WORM audit log.

    Where does PII leave your boundary?Show a strong answer

    Ideally nowhere: redact before third-party calls, or use providers under a data processing agreement in the required region.

    Sign in to track this guide in your curriculum progress.