Enterprise Hybrid Document Ingestion and Semantic Search

Medium · ML System Design · Software Engineer · Onsite

Prompt

Architect an enterprise-grade document intake and hybrid retrieval platform capable of processing messy, mixed-format business files—such as photographed expense receipts, multi-page scanned PDF contracts, and .docx reports—and serving both exact lexical queries and meaning-based vector search.

Your architecture must satisfy these core capabilities and operational guarantees:

  • Asynchronous batch intake & ML enrichment: Accept single uploads alongside large multi-file imports in the background; run OCR on images and scanned pages; extract structured fields (such as invoice ID, issue date, and vendor/sender name) with an NLP model; and compute dense text embeddings for semantic similarity.
  • Duplicate-free fault tolerance: Recover cleanly when an OCR worker, NLP extractor, or embedding endpoint errors out mid-flight so retries never create duplicate chunks or double-counted metadata.
  • Burst elasticity & pipeline visibility: Absorb steep upload surges without dropping work, track stage-by-stage processing latency, and automatically pinpoint files wedged in queues.

Scope & Expectations

  • Service topology and end-to-end data flow: Map out the decoupled ingestion stages from initial client upload through OCR, layout chunking, metadata extraction, vector encoding, and hybrid search serving.
  • Purpose-built storage tiers: Justify where raw binaries, intermediate stage outputs, relational document state, keyword postings, and vector embeddings live, including multi-tenant isolation.
  • Idempotency, retries, and partial failures: Detail the deterministic keys, task leases, and fallback paths that handle transient crashes, unreadable pages, or poison files safely.
  • Throughput scaling and stuck-job detection: Explain how queues, worker pools, and database sweepers handle large backfills fairly and surface stalled tasks before SLAs breach.

Step-by-step walkthrough

  1. Clarify requirements and frame the ML tasks

    In an enterprise HR and finance platform (such as Workday), employees and automated integrations upload everything from crumpled receipt photos and scanned vendor invoices to born-digital Word contracts. The core engineering challenge is not rendering a search bar—it is building an asynchronous ingestion pipeline (a background workflow where upload returns immediately while heavy processing runs later) that passes messy files through slow, failure-prone machine learning stages and makes every document searchable exactly once, without leaking data across enterprise customers (tenants).

    Scope and clarifying assumptions:

    • Document mix: Scanned PDFs, digital PDFs, Word documents (.docx), and mobile receipt photos (.jpg/.png). Typical size is 1 to 5 pages (~500 KB), with an upper limit of 100 MB or 2,000 pages.
    • Two freshness lanes:
      • Interactive lane: An employee uploads one expense receipt and expects extracted fields and searchability in under 2 minutes at p95 (95% of uploads).
      • Bulk lane: A new enterprise customer migrates 2 million historical invoices; finishing within 24 hours is acceptable, provided it never slows down interactive users.
    • Strict security (multi-tenancy + ACLs): Every query must enforce tenant isolation plus per-document Access Control Lists (ACLs) (for example, an employee's receipt is visible only to that employee, their manager, and the finance group). Search must never return—or hint at—a document the caller lacks permission to open.
    • Hard deletion: Deleting a document must hide it from search immediately and purge raw bytes, OCR caches, metadata, and vectors asynchronously.

    Functional requirements: 1. Asynchronous single-file and large-batch upload with queryable per-batch progress and per-document status. 2. OCR (Optical Character Recognition)—converting pixel images of text into machine-readable words, coordinates, and confidence scores—for images and scanned PDFs, while skipping OCR on clean born-digital documents. 3. Dense embeddings (fixed-length lists of numbers, such as 768 floats, where documents with similar meaning sit close together in space) for semantic search, paired with a keyword index for exact strings like INV-2026-0042. 4. Structured metadata extraction (invoice number, issue date, vendor/payee, total, currency) via a layout-aware NLP model.

    Non-functional requirements: - Idempotent fault tolerance: Idempotency means retrying a failed step produces the exact same stored state as a single clean run—never duplicate chunks or double-counted documents. - Spike absorption and fairness: Month-end expense surges and multi-million-doc migrations queue safely without starving small tenants. - End-to-end observability: Track stage-by-stage latency and automatically detect and recover documents stuck in queues.

    Framing the four ML tasks and their training labels:

    ML component           Input -> Output                                     Where training labels come from
    ---------------------  --------------------------------------------------  -------------------------------------------
    Document classifier    Page-1 text + layout -> doc_type (invoice, policy)  Tenant upload folders + human annotators
    OCR engine             Page image -> words, bounding boxes, confidences    Transcribed sample of scans & phone photos
    Field extractor (NLP)  Words + 2D boxes -> typed fields + confidences      Annotated forms + human-review corrections
    Embedding encoder      Document text chunk -> 768-d semantic vector        Pretrained multilingual model + click pairs
    
  2. Back-of-the-envelope capacity and compute math

    Size each stage explicitly so we know which hardware dominates cost and where queues will build up:

    Ingestion volume & raw storage
      Steady volume                    1,000,000 docs/day = ~12 docs/s average; daytime peak (3x) = ~35 docs/s
      Bulk migration spike             1 tenant registers 2,000,000 docs in 1 hour (~555 docs/s intake!)
      Raw object size (~500 KB/doc)    1M x 500 KB = 0.5 TB/day -> ~182 TB/year in S3
      Page volume (~4 pages/doc)       4M pages/day total; 50% are scans/images = 2,000,000 OCR pages/day
    
    Stage 1: OCR compute (assume ~5 pages/s per GPU for text detection + recognition)
      Steady GPU need                  2,000,000 pages / 86,400 s = ~23 pages/s -> 5 GPUs steady (~15 GPUs peak)
      2M-doc backfill (4M OCR pages)   40 bulk GPUs x 5 pages/s = 200 pages/s -> 20,000 s = ~5.6 hours
      Derived OCR JSON (~50 KB/page)   2M pages x 50 KB = ~100 GB/day in S3
    
    Stage 2: Chunking & embeddings (assume ~500 chunks/s per GPU for a 12-layer, 768-dim encoder)
      Chunks per doc                   ~500 tokens/page -> ~2,000 tokens/doc -> 6 chunks of ~400 tokens (15% overlap)
      Steady chunk rate                1M docs x 6 chunks = 6M chunks/day (~70 chunks/s) -> 1 GPU (2 for HA)
      2M-doc backfill (12M chunks)     12,000,000 / 500 chunks/s = 24,000 GPU-s = ~6.7 GPU-hours
      1-year vector footprint          6M/day x 365 = ~2.2B vectors
        Raw float32 (768 x 4 B = 3 KB) 2.2B x 3 KB = ~6.6 TB raw vectors
        int8 quantized (768 x 1 B)     ~1.7 TB raw vectors (~2.8 TB in RAM including HNSW graph + metadata)
        Largest single tenant (2%)     ~44M vectors -> ~34 GB raw int8 (~55 GB RAM with HNSW graph; fits 1 node!)
    
    Stage 3: Metadata extraction
      Invoices & receipts (40% share)  400,000 docs/day -> tiny on a compact layout-NLP model (~20 ms/doc)
      Why NOT use a frontier LLM for all 400k docs?
                                       400k x ~2,200 tokens = ~880M tokens/day (high cost & latency);
                                       reserve LLM fallback strictly for the ~5% low-confidence documents!
    
    Search serving
      Query load                       3M searches/day = ~35 QPS average, ~150 QPS peak; target p95 < 400 ms
    

    Three takeaways that drive the architecture: 1. Intake spikes (555 docs/s) exceed steady GPU capacity (35 docs/s) by 15x, so upload must decouple from processing via durable queues. 2. OCR dominates GPU spend (15 GPUs vs. 2 for embeddings), making content-hash OCR caching and born-digital text detection high-leverage optimizations. 3. Partitioning vectors by tenant_id plus int8 quantization (compressing 32-bit floats to 8-bit integers with < 1% recall loss) shrinks memory ~4x and keeps even the largest customer on a single shard.

  3. Ingestion and search APIs

    1. Create a batch (optional callback webhook for async completion)
    POST /v1/batches
      { "lane": "bulk", "expected_count": 120000, "callback_url": "https://tenant.example/webhooks/docs" }
      -> 201 { "batch_id": "b_71" }
    
    2. Register up to 1,000 files and receive presigned direct-to-S3 upload URLs
    POST /v1/batches/{batch_id}/files
      { "files": [ { "client_file_id": "inv-0001", "filename": "march_hotel.pdf",
                     "size_bytes": 482113, "sha256": "9f2c..." } ] }
      -> 200 { "uploads": [ { "client_file_id": "inv-0001", "doc_id": "d_8c1",
                              "upload_url": "https://s3.../raw/...?X-Amz-Signature=..." } ] }
    
    3. Poll batch & document status (or receive webhooks: `batch.completed`, `document.failed`, `document.needs_review`)
    GET  /v1/batches/{batch_id}          -> { "received": 12, "processing": 140, "indexed": 119840,
                                              "needs_review": 6, "failed": 2 }
    GET  /v1/documents/{doc_id}          -> status, current_stage, quality_flags[], extracted_fields{}, last_error
    POST /v1/documents/{doc_id}/reprocess -> bumps `generation` to re-run extraction/indexing cleanly
    DELETE /v1/documents/{doc_id}        -> hides from search immediately; enqueues async storage purge
    
    4. Hybrid search + relevance feedback
    POST /v1/search
      { "query": "hotel receipts from Berlin offsite", "mode": "hybrid",
        "filters": { "doc_type": ["invoice", "receipt"], "date_from": "2026-01-01" }, "page_size": 20 }
      -> 200 { "search_id": "s_5e", "results": [ { "doc_id": "d_8c1", "snippet": "...",
               "highlights": [ { "page": 1, "bbox": [72, 410, 290, 428] } ],
               "fields": { "invoice_number": "INV-2026-0042", "total": "1240.00 EUR" } } ] }
    
    POST /v1/search/{search_id}/feedback  { "doc_id": "d_8c1", "rank": 2, "action": "open" | "download" }
    
    • Presigned URLs bypass API servers: A presigned URL is a temporary, cryptographically signed link allowing the client to PUT file bytes straight into Amazon S3 (or multipart PUTs for large 100 MB files over flaky networks) without streaming gigabytes through our web tier.
    • Upload idempotency via (tenant_id, batch_id, client_file_id): If a client times out and retries POST /files, it gets back the exact same doc_id rather than creating a duplicate record. S3 verifies the sha256 checksum on upload so corrupted transfers fail immediately.
  4. Storage architecture and data model

    Following the separation-of-concerns principle, four specialized stores each hold what they are built for:

    1. Object Store (S3 — raw files & immutable stage outputs, encrypted with per-tenant KMS keys)
       raw/{tenant_id}/{doc_id}                               original uploaded file
       derived/{tenant_id}/{doc_id}/g{generation}/
         pages/{page_num}.png                                 deskewed 300-DPI page images
         ocr/{start_page}_{end_page}.json                     words, 2D bounding boxes, confidences
         chunks.jsonl                                         ~400-token chunks + page/bbox offsets
         fields.json                                          extracted metadata + confidences
    
    2. Relational Metadata DB (Postgres, sharded by `tenant_id` — source of truth & state machine)
       documents         doc_id PK, tenant_id, batch_id, lane, client_file_id, content_sha256,
                         page_count, status, stage, generation (int, starts at 1), indexed_generation,
                         quality_flags[], acl_groups[], duplicate_of, created_at, updated_at, indexed_at
                         UNIQUE (tenant_id, batch_id, client_file_id)
                         partial INDEX (status, updated_at)
                           WHERE status NOT IN ('registered', 'indexed', 'failed', 'deleted', 'expired')
    
       tasks             task_id PK = sha256(doc_id : generation : stage : page_range)
                         doc_id, tenant_id, generation, stage, lane,
                         status ('queued' | 'running' | 'done' | 'failed' | 'dead'),
                         attempts, lease_token, lease_expires_at, next_attempt_at, last_error, output_uri
                         partial INDEX (status, lease_expires_at, next_attempt_at)
                           WHERE status IN ('queued', 'running')
    
       extracted_fields  PK (doc_id, generation, field_name), raw_value, normalized_value,
                         confidence, page, bbox, model_version, source ('model' | 'llm_fallback' | 'human')
       ocr_cache         PK (tenant_id, content_sha256, page_range, ocr_model_version) -> output_uri
       review_tasks      review_id PK, doc_id, generation, reason, status, created_at, resolved_at
       outbox            id PK, queue_name, payload_json, delay_seconds, created_at, published_at
    
    3. Keyword Search Index (OpenSearch — BM25 exact/lexical text + structured filters)
       id = "{doc_id}:{generation}:{chunk_idx}"
       fields: tenant_id, doc_id, generation, acl_groups[], doc_type, text, invoice_number, vendor, doc_date
    
    4. Vector Database (Qdrant / Milvus — HNSW approximate nearest-neighbor search)
       collection = "chunks_{embedding_model_version}", partitioned by `tenant_id`
       id = "{doc_id}:{generation}:{chunk_idx}"
       vector = 768-d int8-quantized embedding
       payload = { tenant_id, doc_id, generation, acl_groups[], doc_type, doc_date }
    

    Why separate these four stores? - S3 stores terabytes of PDFs, PNGs, and chunks.jsonl for pennies per gigabyte. Keeping chunks.jsonl in S3 means retraining the embedding model next quarter never requires re-running expensive OCR. - Postgres provides ACID transactions for task coordination, structured queries over extracted_fields, and a transactional outbox (writing DB state changes and outgoing queue messages in one atomic commit so tasks are never lost on crash). - OpenSearch + Vector DB are treated as derived views rebuildable from Postgres + S3. Separate vector storage lets us tune HNSW (Hierarchical Navigable Small World—a multi-layer graph index for fast millisecond nearest-neighbor search), int8 quantization, and model-version collections independently of keyword indices.

  5. High-level architecture and end-to-end data flow

     Clients / Integrations
       | 1. Register batch & files --------> [ Ingest API ] ---> [ Postgres Metadata DB ] <---------------+
       | 2. Direct PUT (presigned URL)                             (documents, tasks, outbox)             |
       v                                                                   |                              |
     [ S3: raw/ ] --ObjectCreated--> [ Upload Queue ]                      | [ Outbox Relay ]             |
                                            |                              v                              |
                                            v                     [ Admission Controller ]                |
                                   [ Validator Worker ]             (interactive reserve +                |
                                    (SHA-256, MIME, AV,              per-tenant fair slots)               |
                                     page count, dedupe)                   |                              |
                                                                           v                              |
       +---------------- Stage Work Queues (SQS: interactive + bulk per stage, each with DLQ) ----------+ |
       |                                                                                                | |
       |  [1. Classify] -> [2. OCR (GPU, 10-pg slices)] -> [3. Layout & Chunk] -+-> [4a. Extract (NLP)]-+ |
       |                   (skipped if clean digital text)                      +-> [4b. Embed (GPU)] --+ |
       |                                                                                   |              |
       |                                                                          (fan-in when both done) |
       |                                                                                   v              |
       |                                                                            [5. Index Worker]     |
       +------------------------------------------------------------------------------------------------+ |
             | stage JSON / chunks.jsonl            | task & field updates ------------------------------->+
             v                                      |                     | bulk upserts + delete old gen
      [ S3: derived/ ]                              v                     v
                                           [ Review Queue & UI ]   [ OpenSearch ] + [ Vector DB ]
                                                                           ^              ^
     [ Search API ] --- embed query + parallel tenant/ACL-filtered BM25 & ANN + RRF fusion + rerank
     [ Sweeper (1m cron) ] --- detects expired leases & stuck docs      [ Kafka ] ---> Webhooks & Audit
    

    Step-by-step data flow for one scanned 25-page invoice: 1. Register & Upload: Client registers the file (status = 'registered') and PUTs bytes to s3://.../raw/{tenant}/{doc_id}. 2. Validate: S3's ObjectCreated event triggers the Validator, which verifies the SHA-256 hash, scans for malware, checks page limits, checks ocr_cache within the same tenant (never across tenants, which would leak confidential file existence!), and sets status = 'received'. 3. Admit & Classify: The Admission Controller enqueues classify, which detects a scanned invoice (no usable embedded text) and splits the 25 pages into three parallel 10-page OCR tasks (1_10, 11_20, 21_25). 4. Parallel OCR -> Fan-in: GPU workers write word boxes to derived/.../ocr/. Each finishing range atomically decrements a remaining-ranges counter on the documents row (UPDATE ... RETURNING); the range that hits 0 enqueues layout_chunk. 5. Chunk -> Parallel Extract & Embed -> Index: layout_chunk reconstructs reading order and writes chunks.jsonl, fanning out to extract_fields and embed_chunks in parallel. When the second branch finishes (coordinated via SELECT ... FOR UPDATE on the document row so two simultaneous completions cannot miss each other), it enqueues index. The Index Worker bulk-upserts chunks into OpenSearch and the Vector DB, deletes any older generation, marks status = 'indexed', and emits a webhook event.

    Why SQS-style work queues for pipeline tasks, and Kafka for status events? In Kafka, consumers commit one offset per partition, so one 2,000-page PDF taking 8 minutes blocks offset commits for faster documents behind it unless you build custom state tracking. SQS tracks every message independently with a visibility timeout (hiding an in-progress message from other workers while extendable via heartbeats) and a Dead-Letter Queue (DLQ) (a side queue capturing messages that repeatedly crash workers). Kafka is used downstream for ordered status/webhook event streams where replay matters.

  6. Deep dive 1: idempotency, retries, and partial failures

    Because queues guarantee at-least-once delivery (a worker can crash right after writing to S3 or the Vector DB, before acknowledging the queue message), every stage must be idempotent across four distinct scenarios:

    Duplicate scenario                         Deterministic key                            Result
    -----------------------------------------  -------------------------------------------  -------------------------------
    Client retries `POST /files` on timeout    UNIQUE (tenant_id, batch_id, client_file_id) Returns existing `doc_id`
    Queue delivers the same task twice         task_id = hash(doc_id, gen, stage, pg_range) Same S3 URI + CAS lease check
    Same PDF uploaded twice in one tenant      (tenant_id, content_sha256, ocr_model_ver)   Keeps both docs (catches double
                                                                                            expense fraud!) but reuses OCR!
    Document reprocessed after model/human fix `generation` integer (g1 -> g2)              Writes `:g2:` chunks, deletes `<2`
    

    Worker execution with fencing leases and transactional outbox: A lease is a time-limited lock (lease_token, valid for 300 seconds) stored on the tasks row. Even if Worker A freezes during a garbage-collection pause, its lease expires, Worker B takes over with a new lease_token, and when Worker A wakes up its Compare-And-Set (CAS) update (WHERE lease_token = :my_token) affects 0 rows—preventing split-brain corruption:

    import random
    
    LEASE_SECONDS = 300
    MAX_ATTEMPTS = 5
    
    
    def retry_delay_seconds(attempt, base_seconds=10, max_seconds=900):
        """Exponential backoff with full jitter so recovering GPU services aren't slammed in lockstep."""
        ceiling = min(max_seconds, base_seconds * (2 ** (attempt - 1)))
        return random.uniform(0, ceiling)
    
    
    def process_stage_task(message, db, object_store):
        """Idempotent stage handler for artifact-producing stages (OCR, layout, extraction, embedding)."""
        task_id = message["task_id"]
        task = db.get_task(task_id)
        if task is None or task["status"] in ("done", "dead"):
            return  # Duplicate queue delivery of already-completed work; safe to ack.
    
        # Atomic SQL: claim task ONLY if 'queued' and due, or 'running' with an expired lease.
        # Increments `attempts` in Postgres so even hard OOM crashes are counted!
        lease = db.try_acquire_lease(task_id, LEASE_SECONDS)
        if lease is None:
            return  # Another healthy worker currently owns this task.
    
        if lease["attempts"] > MAX_ATTEMPTS:
            db.mark_dead(task_id, lease, error_class="poison", reason="Exceeded max attempts (worker crash/OOM)")
            return
    
        output_uri = (
            f"derived/{task['tenant_id']}/{task['doc_id']}/g{task['generation']}/"
            f"{task['stage']}/{task['page_range']}.json"
        )
        try:
            # Skip heavy GPU inference if a prior attempt already wrote the deterministic S3 artifact!
            if not object_store.exists(output_uri):
                output_bytes = run_model_stage(task, lease)  # Heartbeats lease + SQS visibility every 60s
                object_store.put(output_uri, output_bytes)
    
            # Single DB transaction: CAS-verify `lease_token`, mark task 'done',
            # and insert next-stage task + outbox rows atomically.
            db.complete_and_enqueue_next(task_id, lease, output_uri)
    
        except TransientStageError as exc:
            # Timeouts, HTTP 503s, GPU throttling -> backoff + jitter retry.
            if lease["attempts"] >= MAX_ATTEMPTS:
                db.mark_dead(task_id, lease, error_class="transient_exhausted", reason=str(exc))
            else:
                delay = retry_delay_seconds(lease["attempts"])
                db.schedule_retry(task_id, lease, reason=str(exc), delay_seconds=delay)
    
        except PermanentStageError as exc:
            # Password-protected PDF, corrupt bytes -> fail immediately without wasting retries.
            db.mark_dead(task_id, lease, error_class="permanent", reason=str(exc))
    

    Idempotent index updates without search downtime or duplicate hits:

    def index_document_generation(doc, chunks, vectors, keyword_index, vector_db, db):
        """Bulk-upsert deterministic chunk IDs for `generation`, then clean up older generations."""
        doc_id = doc["doc_id"]
        gen = doc["generation"]
    
        # Guard against out-of-order reprocessing: abort if a newer generation already started.
        if gen < db.get_current_generation(doc_id):
            return
    
        keyword_batch = []
        vector_batch = []
        for chunk, vector in zip(chunks, vectors):
            # Deterministic ID ensures retries overwrite the exact same index record in place!
            chunk_id = f"{doc_id}:{gen}:{chunk['index']}"
            common_meta = {
                "tenant_id": doc["tenant_id"],
                "doc_id": doc_id,
                "generation": gen,
                "acl_groups": doc["acl_groups"],
                "doc_type": doc["doc_type"],
                "doc_date": doc["fields"].get("invoice_date"),
            }
            keyword_batch.append((chunk_id, {**common_meta, "text": chunk["text"], **doc["fields"]}))
            vector_batch.append((chunk_id, vector, common_meta))
    
        # 1. Batch-write the new generation first (500 chunks/call keeps HNSW graph updates efficient).
        keyword_index.bulk_upsert(keyword_batch)
        vector_db.bulk_upsert(vector_batch)
    
        # 2. Only AFTER the new generation is searchable, delete stale chunks from older generations.
        keyword_index.delete_where(tenant_id=doc["tenant_id"], doc_id=doc_id, generation_lt=gen)
        vector_db.delete_where(tenant_id=doc["tenant_id"], doc_id=doc_id, generation_lt=gen)
    
        # 3. Monotonic update: `SET indexed_generation = gen WHERE indexed_generation < gen`.
        db.advance_indexed_generation(doc_id, gen)
    

    Handling partial failures inside one document: - 1 corrupt page in a 300-page contract: 29 of the 30 OCR tasks succeed; 1 hits dead. Rather than throwing away 290 readable pages, the fan-in step proceeds once all 30 tasks reach a terminal state (done or dead), indexes the 290 pages, attaches quality_flags = ['partial_ocr_pages_121_130'], and opens a review_tasks ticket. - NLP metadata extractor fails while embeddings succeed: Index the text and vectors immediately (quality_flags = ['fields_pending']) and retry field extraction independently so semantic and keyword search already work.

  7. Deep dive 2: handling ingestion spikes, tenant fairness, and stuck documents

    1. Priority lanes protect interactive SLAs. Every stage has two queues: interactive and bulk. Dedicated minimum GPU pools (~30% of fleet) serve interactive exclusively, and shared workers poll interactive before bulk. A 2-million-file historical import therefore never delays an employee's single receipt upload past 2 minutes.

    2. Least-in-flight tenant admission prevents noisy-neighbor starvation. If Tenant A dumps 2,000,000 files into a plain First-In-First-Out (FIFO) bulk queue, Tenant B uploading 500 invoices behind them would wait 6 hours. Instead, validated bulk documents sit as status = 'received' in Postgres, and an Admission Controller feeds slots into the stage queues every few seconds by always picking the waiting tenant with the fewest documents currently in flight:

    from collections import deque
    
    
    def pick_next_tenant(pending_by_tenant, in_flight_by_tenant, max_in_flight_per_tenant):
        """Select the waiting tenant with the fewest active pipeline docs (ties broken by tenant_id)."""
        chosen_tenant = None
        lowest_in_flight = 0
        for tenant_id in sorted(pending_by_tenant):
            waiting_docs = pending_by_tenant[tenant_id]
            active_count = in_flight_by_tenant.get(tenant_id, 0)
            if not waiting_docs or active_count >= max_in_flight_per_tenant:
                continue
            if chosen_tenant is None or active_count < lowest_in_flight:
                chosen_tenant = tenant_id
                lowest_in_flight = active_count
        return chosen_tenant
    
    
    def admit_bulk_documents(pending_by_tenant, free_global_slots, in_flight_by_tenant, max_in_flight_per_tenant):
        """Pull up to `free_global_slots` docs fairly across tenants so 2M-doc imports never starve 500-doc batches."""
        admitted_doc_ids = []
        while free_global_slots > 0:
            tenant_id = pick_next_tenant(pending_by_tenant, in_flight_by_tenant, max_in_flight_per_tenant)
            if tenant_id is None:
                break
            admitted_doc_ids.append(pending_by_tenant[tenant_id].popleft())
            in_flight_by_tenant[tenant_id] = in_flight_by_tenant.get(tenant_id, 0) + 1
            free_global_slots -= 1
        return admitted_doc_ids
    

    3. Stage-specific autoscaling + downstream backpressure. - CPU workers scale in seconds on SQS queue depth and oldest-message age. - Bulk GPU workers (which take 3–5 minutes to boot and load weights) scale on estimated drain time: needed_gpus = backlog_pages / (5 pages_per_s x target_drain_seconds), capped by cluster budget. - Index workers cap concurrent HNSW batch writes to the vector DB's load-tested ceiling so ingestion spikes buffer harmlessly in SQS instead of crashing search nodes!

    4. Monitoring pipeline latency and catching stuck documents. Queue depth alone is misleading: a queue of depth 1 can hide a single document stuck for 4 hours! We track stage latency histograms (p50/p95/p99), oldest-message age per queue, DLQ counts, and run a 1-minute DB Sweeper against Postgres's small partial index on unfinished documents:

    -- 1. Recover hung/crashed workers whose lease expired without finishing.
    SELECT task_id, doc_id, stage, attempts
    FROM tasks
    WHERE status = 'running' AND lease_expires_at < now();
    
    -- 2. Recover tasks stranded in 'queued' (e.g., delayed outbox or dropped broker message).
    SELECT task_id, doc_id, stage
    FROM tasks
    WHERE status = 'queued' AND next_attempt_at < now() - interval '15 minutes';
    
    -- 3. Surface genuinely stuck documents for dashboards and on-call paging.
    -- Excludes terminal states ('indexed', 'failed', 'deleted', 'expired') AND bulk 'received' docs waiting fairly for admission.
    SELECT doc_id, tenant_id, lane, stage, status, updated_at
    FROM documents
    WHERE status NOT IN ('registered', 'indexed', 'failed', 'deleted', 'expired')
      AND (
        (lane = 'interactive' AND created_at < now() - interval '2 minutes')
        OR (lane = 'bulk' AND status <> 'received' AND updated_at < now() - interval '1 hour')
      );
    

    Documents still in 'registered' after their 15-minute presigned upload URL expires get a quick S3 HEAD check: if bytes arrived (dropped S3 event), enqueue validation; otherwise mark status = 'expired'.

  8. Deep dive 3: the ML models (OCR, metadata extraction, and chunk embeddings)

    1. Smart OCR routing & quality scoring. - Verify embedded PDF text before skipping OCR: Many scanned PDFs contain garbled legacy OCR text layers. If extracted characters per page are < 50 or the dictionary-word ratio is < 40%, route the page through image normalization (EXIF orientation fix, deskewing, 300-DPI resize) and GPU OCR. - Non-blocking quality flags: Compute per-page OCR confidence right inside the OCR worker; low-quality pages still proceed to indexing with quality_flags while asynchronously opening a human-review task:

    def compute_ocr_quality_flags(
        words_with_conf,
        min_mean_conf=0.80,
        low_word_threshold=0.60,
        max_low_word_fraction=0.20,
    ):
        """words_with_conf: list of (word_text, confidence_0_to_1) for a single page."""
        if not words_with_conf:
            return ["empty_ocr_page"]
    
        conf_sum = 0.0
        low_word_count = 0
        for _, conf in words_with_conf:
            conf_sum += conf
            if conf < low_word_threshold:
                low_word_count += 1
    
        page_flags = []
        if (conf_sum / len(words_with_conf)) < min_mean_conf:
            page_flags.append("low_mean_ocr_confidence")
        if (low_word_count / len(words_with_conf)) > max_low_word_fraction:
            page_flags.append("high_garbled_word_share")
        return page_flags
    

    2. Two-tier NLP metadata extraction + deterministic validators. - Tier 1 (fast default): A compact layout-aware transformer (such as a fine-tuned LayoutLM-style token classifier that reads both words and their 2D (x0, y0, x1, y1) bounding boxes—rectangular page coordinates) extracts invoice_number, invoice_date, vendor_name, total_amount, and currency in ~20 ms. - Deterministic code validators: Even a 0.95-confidence neural net can misread a digit, so code checks that subtotal + tax == total (within rounding), dates parse cleanly, and currency codes match ISO-4217. - Tier 2 (targeted LLM fallback): Only the ~5% of documents with low confidence or failed math checks invoke a structured-output LLM prompt, and unresolved failures queue for human review—whose corrections feed right back into Tier-1 fine-tuning!

    3. Layout-aware chunking + contextualized embeddings. - Split along headings, paragraphs, and table rows into ~400-token chunks with 15% overlap. - Prepend a compact document context header before embedding each chunk: "DocType: Invoice | Vendor: Hotel Adlon | Date: 2026-03-14 | Page 2/3 — <chunk text>". Without that header, page 2's line-item table lacks the hotel's name and fails semantic queries like "Hotel Adlon catering charges". - Encode chunks with a 12-layer, 768-dim multilingual encoder, tagging every vector with embedding_model_version.

  9. Hybrid search serving, offline/online evaluation, and A/B testing

    Hybrid retrieval with in-query permission filtering: Exact invoice IDs (INV-2026-0042) need BM25 (keyword frequency scoring), while conceptual queries ("lodging bills from the Berlin trip") need semantic vector search. Because raw BM25 scores (0 to 30+) and cosine similarities (-1 to 1) live on incompatible scales, we merge both top-100 lists using Reciprocal Rank Fusion (RRF)—scoring each item solely by its rank 1 / (60 + rank)—and optionally re-score the top 50 candidates with a cross-encoder reranker (a transformer reading (query, chunk) side by side for high precision):

    def reciprocal_rank_fusion_to_docs(ranked_chunk_lists, top_k_docs=20, rrf_k=60):
        """Merge keyword and vector ranked lists of (chunk_id, doc_id) into deduplicated top documents."""
        chunk_rrf_score = {}
        chunk_to_doc = {}
        for ranked_list in ranked_chunk_lists:
            for rank, (chunk_id, doc_id) in enumerate(ranked_list, start=1):
                chunk_rrf_score[chunk_id] = chunk_rrf_score.get(chunk_id, 0.0) + 1.0 / (rrf_k + rank)
                chunk_to_doc[chunk_id] = doc_id
    
        # Collapse chunks to parent documents using each document's strongest chunk score.
        best_doc_score = {}
        for chunk_id, score in chunk_rrf_score.items():
            doc_id = chunk_to_doc[chunk_id]
            if score > best_doc_score.get(doc_id, 0.0):
                best_doc_score[doc_id] = score
    
        sorted_docs = sorted(best_doc_score, key=best_doc_score.get, reverse=True)
        return sorted_docs[:top_k_docs]
    

    Security rule: tenant_id and acl_groups filters are pushed inside both OpenSearch and Vector DB graph traversal—never applied after fetching a global top 100, which would return empty pages to restricted users and leak document counts.

    Offline evaluation, online metrics, and experimentation: - Offline regression suite: - OCR: Character Error Rate (CER) (edit distance divided by true character count) across 2,000 labeled scans/photos. - Extraction: Exact normalized field match + confidence calibration across 3,000 held-out forms. - Search: Recall@100 (share of relevant docs retrieved into the top 100) and nDCG@10 / MRR (Normalized Discounted Cumulative Gain and Mean Reciprocal Rank, rewarding relevant hits placed near rank #1) on 500 human-graded enterprise queries. - Online metrics & A/B testing: Track search success rate (user opens or downloads a result within 2 minutes without immediate query reformulation) and p95 latency (< 400 ms). Compare new rerankers via team-draft interleaving—blending results from Ranker A and Ranker B into one list per query and seeing which model gets more opens, requiring ~10x less traffic than standard user-split A/B tests across small enterprise tenants.

  10. Scaling, failure recovery, and summary of trade-offs

    Failure handling matrix:

    Failure scenario                         Automated recovery behavior
    ---------------------------------------  -------------------------------------------------------------------
    OCR / Embedding GPU service outage       Circuit breaker pauses that stage's consumers so tasks don't burn
                                             all 5 retries; SQS buffers up to 14 days while other stages continue
    Vector DB / OpenSearch write errors      Index task backs off & retries (deterministic chunk IDs = idempotent);
                                             nightly reconciler compares Postgres `indexed_generation` vs. indices
    Bad model deploy (NaNs or garbage text)  1% canary gate + output norm/schema checks; `model_version` column
                                             lets us query affected `doc_id`s and trigger a new `generation`
    Poison PDF (zip bomb / 50k-pixel image)  Container memory + CPU timeouts kill worker; DB `attempts` hits 5 ->
                                             marked `dead` (plus SQS DLQ backstop) without blocking healthy docs
    Tenant deletes a document                Postgres marks `deleted` (hidden immediately); purge job deletes index
                                             entries, `ocr_cache`, and ALL S3 object versions (not just markers)
    

    Summary of key trade-offs: - Async stage queues vs. synchronous upload processing: Gives instant uploads, independent GPU/CPU scaling, and fault isolation, at the cost of eventual consistency (seconds to minutes before searchability). - SQS work queues vs. Kafka for tasks: Per-message visibility timeouts and DLQs prevent one 2,000-page PDF from blocking fast 1-page receipts. - Deterministic keys + CAS leases vs. distributed 2-phase commits: Achieves exact-once indexed state across S3, Postgres, OpenSearch, and Vector DB without brittle cross-system locks. - Partial indexing + async review vs. strict all-or-nothing rejection: Keeps 299 good pages searchable when 1 scan page is unreadable, trading minor UI badge complexity for far higher utility.

Intuition & how it works

Think of an enterprise document ingestion system like a busy mailroom and digital library for thousands of companies. Trucks arrive unpredictably—sometimes one employee drops off a single crumpled taxi receipt, and sometimes a new corporate client unloads 2 million archived PDF invoices at once. If the front desk clerk tried to photocopy, read, summarize, and shelve every single page before handing you a receipt slip, the line would wrap around the block, and if the scanner jammed on page 8, the clerk might start over and shelve two duplicate copies of pages 1 through 7. Instead, a smart mailroom stamps each envelope with a permanent tracking barcode at the front window, drops it into sorted conveyor bins (interactive vs. bulk), and lets specialized stations (OCR scanning, NLP field reading, semantic indexing) write their outputs into labeled slots keyed by that exact barcode so retrying a jammed page simply overwrites its own slot.

A naive synchronous design fails immediately in production for three reasons. First, running OCR (Optical Character Recognition, turning pixel images into text) and neural embeddings (converting text into dense numeric vectors that capture meaning) inside the HTTP upload request times out whenever a customer uploads a batch spike 15x larger than steady GPU capacity. Second, retrying failed queue messages without idempotency (designing every write so repeating it produces the exact same stored state, never duplicates) creates duplicate search hits and corrupted metadata. Third, searching only with vectors misses exact strings like invoice number INV-2026-0042, while searching only with keywords misses paraphrases like "hotel bills from the Berlin trip" when the receipt says "Accommodation — Adlon Kempinski."

Here is how a single crumpled receipt photo (march_hotel.jpg) moves through the system:

  1. Idempotent intake: The client calls POST /files with client_file_id = "exp-42" and a SHA-256 hash (a cryptographic fingerprint of the file's bytes), receives deterministic doc_id = "d_8c1" plus a presigned URL (a temporary signed link to upload bytes straight to S3), and PUTs the image without touching API server memory.
  2. Queued GPU stages: The validator checks the hash and routes "d_8c1" into the fast interactive SQS lane. An OCR worker acquires a 5-minute lease (a temporary database lock with a unique fencing token), extracts words and bounding boxes (2D page coordinates), and writes derived/{tenant}/d_8c1/g1/ocr/1_1.json to S3.
  3. Parallel NLP & embedding: A layout worker builds a 400-token chunk (chunks.jsonl) and fans out two tasks in parallel: a compact layout-NLP model extracts vendor = "Hotel Adlon" and total = "1240.00 EUR", while an encoder GPU computes a 768-dimensional semantic vector.
  4. Safe indexing & hybrid search: Once the second parallel branch finishes, the index worker batch-upserts deterministic chunk ID "d_8c1:1:0" into both OpenSearch (for exact keyword BM25 matching) and the Vector DB (for HNSW approximate nearest-neighbor vector search), enforcing tenant_id and user ACL (Access Control List) filters directly inside every search query.

Key trade-offs

  • Asynchronous queue-decoupled pipeline vs. synchronous upload processing. Decoupling every stage with queues lets uploads succeed in milliseconds during 500-doc/s bursts and isolates a crashed OCR model to its own queue, trading away instant read-after-write consistency (interactive uploads become searchable in ~15–60 seconds rather than 0 seconds).
  • SQS-style work queues vs. Kafka log partitions for stage tasks. SQS tracks each message's visibility timeout (how long a leased message stays hidden before redelivery) and Dead-Letter Queue (DLQ) (a holding queue for repeatedly failing messages) independently, so one 2,000-page PDF taking 5 minutes never blocks 1-page receipts behind it—whereas Kafka partition offsets shine for ordered downstream webhook and audit streams.
  • End-to-end idempotency via deterministic keys vs. distributed transactions. Distributed two-phase commits across S3, Postgres, OpenSearch, and a Vector DB are slow and brittle. Using deterministic keys (client_file_id, task_id, chunk_id = doc_id:generation:index), Compare-And-Set (CAS) lease completions, and a transactional outbox (committing DB state and outgoing queue rows in one Postgres transaction) makes at-least-once retries 100% safe.
  • Dedicated Vector DB + OpenSearch vs. a single all-in-one search engine. Running OpenSearch for BM25 plus a dedicated vector engine (like Qdrant or Milvus) adds a dual-write index worker and nightly reconciler, in exchange for independent scaling, int8 vector quantization (shrinking 32-bit floats to 8-bit integers for a 4x RAM reduction), and isolated per-model-version vector collections at multi-billion-chunk scale.
  • Two-lane priority + per-tenant admission vs. maximum raw throughput. Reserving ~30% of GPUs for interactive uploads and throttling bulk tenants by least-in-flight slots leaves occasional idle interactive capacity overnight, but guarantees a 2-million-doc customer migration never starves another customer's 2-minute receipt SLA.
  • Compact layout-NLP model + LLM fallback vs. LLM-for-everything. Running a small fine-tuned layout transformer on 400,000 daily invoices costs a fraction of a cent per thousand docs and finishes in 20 ms, while invoking a large language model only on the ~5% of documents that fail confidence or math checks (subtotal + tax == total) captures LLM flexibility without paying for ~880M tokens/day.
  • Partial indexing with quality flags vs. all-or-nothing rejection. Indexing 299 clean pages when page 125 is smudged—and flagging the missing page for async human review—requires clear UI badges (partial_ocr), but makes documents immediately useful instead of blocking business workflows on single-page flaws.

Common mistakes

  • Streaming file uploads through web servers or running OCR synchronously. Large batches exhaust API memory and connection pools; always upload directly to object storage via presigned URLs and process asynchronously.
  • Retrying failed tasks with random UUID chunk IDs. If an index worker inserts 6 chunks with random IDs and times out on the 7th, the retry inserts 6 duplicates unless chunk IDs are deterministically keyed as {doc_id}:{generation}:{chunk_index}.
  • Deleting old chunks before writing the new generation. If a worker crashes right after deleting generation = 1, the document vanishes from search; always bulk-upsert generation = 2 first and delete generation < 2 second.
  • Updating Postgres and publishing to SQS as two separate non-atomic calls. A process crash between db.commit() and sqs.send_message() silently orphans the document forever; write an outbox row inside the same Postgres transaction and have a relay publish it.
  • Race conditions at parallel fan-in points. When extract_fields and embed_chunks finish in the same millisecond, checking "is my sibling done?" without locking the documents row (SELECT ... FOR UPDATE) lets both workers see the other as unfinished, so neither enqueues index.
  • Sharing a content-hash OCR cache across enterprise tenants. Cross-tenant caching leaks whether a competitor uploaded the exact same contract, mixes per-tenant encryption keys, and violates hard-deletion guarantees; always scope caches by (tenant_id, content_sha256).
  • Applying permission (ACL) filters after vector top-K retrieval. Fetching the global top-100 vectors and discarding 99 unauthorized chunks returns nearly empty pages to restricted employees and leaks confidential match counts; push tenant_id and acl_groups inside the index query itself.
  • Watching only queue length instead of oldest-message age and DB state. A queue length of 2 looks healthy on a graph even if those 2 documents have been wedged for 6 hours; pair queue-age alerts with a 1-minute Postgres sweeper query over non-terminal documents.

Follow-up questions

  • When OCR confidence is very low on a smudged scan, how do you route that file for human verification without stalling automated indexing? During the OCR stage, compute per-page quality signals—mean word confidence, fraction of words below 0.60 confidence, and dictionary-word ratio—and pair them with downstream deterministic extraction checks like subtotal + tax == total and valid date parsing. When a page crosses a tuned bad-quality threshold, the pipeline still chunks, embeds, and indexes whatever text was recovered, attaches a low_ocr_quality badge to the documents row, and writes a row to a separate review_tasks queue so automated ingestion never blocks on a human. When a reviewer later corrects the garbled text or invoice fields side-by-side with the page image, saving the fix increments generation (g1 -> g2), re-runs chunking/indexing idempotently, and logs the human edit as high-value training data—supplemented by a small 1% random audit of high-confidence pages to catch blind spots.
  • How would you roll out a newly trained embedding encoder and rebuild billions of stored vectors with zero search downtime? Embeddings from two different model versions live in incompatible geometric spaces and must never be mixed in one index, so build a brand-new shadow collection (chunks_v2) in the background by reading the already-chunked chunks.jsonl artifacts straight from S3 in the low-priority bulk lane—skipping OCR completely (~1,200 GPU-hours for 2.2B chunks, or ~2.5 days on 20 bulk GPUs). While the backfill runs, dual-write newly uploaded documents into both chunks_v1 and chunks_v2. Once chunks_v2 catches up and passes the offline regression gate (Recall@100 and nDCG@10) plus an online canary test, atomically flip a per-tenant routing alias from v1 to v2 (ensuring queries are embedded with the exact model version their target alias points to) and retain chunks_v1 for a 14-day instant-rollback window before dropping it.
  • Which offline and online metrics evaluate hybrid retrieval quality, and how can search click logs improve future ranking despite position bias? Offline, maintain a stratified 500-query golden set covering exact ID lookups, metadata-filtered queries, and semantic paraphrases, gating every change on retriever Recall@100 (did the right document enter the candidate pool?) and ranker nDCG@10 / MRR (did it land near position #1?). Online, measure search success rate (user opens or downloads a result within 2 minutes without retyping the query) and compare rankers efficiently using team-draft interleaving (merging two rankers' top hits into one list per search to see which wins more opens). Because users naturally click rank #1 far more than rank #8 regardless of quality (position bias), estimate rank examination probabilities via minor top-result randomization on 1% of traffic and apply inverse propensity weighting (upweighting clicks on lower-ranked results) to train a cross-encoder reranker and fine-tune future embedding models—strictly honoring per-tenant data-sharing agreements.

Follow-up questions

Similar questions

More Workday interview questions

All 3 Workday questions →