Design a Large-Scale Batch Inference Pipeline
Machine LearningModel answerLast updated
Design a production-grade batch inference system that runs a language model over millions of daily documents with exactly-once semantics, versioning, and operational reliability.
Background
Your team owns a platform that runs a text classification model over large document collections every day. The raw documents land in object storage (partitioned by date), and the results must be written to a data warehouse for analytics and compliance queries.
Daily volume is on the order of tens of millions of documents with noticeable day-to-day spikes. The warehouse is read by downstream teams who need confidence that every document was scored, no document was scored twice, and they can always trace a result back to the exact model and data that produced it.
What you need to design
Address all four areas below. For each one, go beyond naming tools — explain the mechanism and the reasoning behind your choices.
1. Correctness under failure Workers will crash mid-shard. A network partition will cause a result to be delivered twice. Explain how the pipeline guarantees that each document ends up with exactly one result row in the warehouse regardless of these failures.
2. Autoscaling The pipeline must absorb volume spikes up to 3× baseline without manual tuning. Describe what signals drive scaling and how you size the work units to make that safe.
3. Artifact and data versioning An auditor asks: "What exact model, preprocessing steps, and source data produced this row?" Describe the metadata schema and the naming conventions that make that query possible, even six months later.
4. Operational health Define the metrics you would track and the alerts you would set to detect a silent failure (for example, a 5 % drop in document count) before downstream consumers notice.
Expected deliverables
- A component-level description of the pipeline (orchestrator, workers, storage, metadata store)
- A concrete explanation of the commit protocol that enforces exactly-once semantics
- A data model for versioning and lineage
- A monitoring and alerting strategy with specific metric names and thresholds
Hints
Hint 1
Start by sizing the problem: estimate token volume, GPU-seconds required, and how many GPUs you need to finish within a time budget. Real numbers force the design to make sense — spot instances, autoscaling signals, and shard size all fall out of the math.
Hint 2
Exactly-once doesn't mean executing each shard exactly once — that's too hard to guarantee. It means making the commit idempotent: at-least-once execution plus a conditional write that only the first successful attempt can win.
Hint 3
Versioning is a data model problem, not just a naming convention. Think about what columns a downstream query needs to reconstruct full lineage, and work backwards to the tables that need to exist in your metadata store.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify scope and estimate scale first
Before drawing any components, state assumptions and do back-of-envelope math. This separates candidates who've thought about production systems from those who just name technologies.
Assume:
- 10M documents/day at baseline, spikes to 30M (3×)
- Average ~1K tokens per document → ~10B tokens/day baseline
- Prefill-heavy classification: roughly 5K tokens/s per GPU
- 10B ÷ 5K = 2M GPU-seconds ≈ 560 GPU-hours
- Target SLA: results published within 6 hours of partition landing
- 560 ÷ 6 ≈ 95 GPUs at baseline, ~285 at 3× spike
This is a throughput-bound job, not latency-bound. That justifies large batches, spot instances, and autoscaling — all specific choices grounded in the numbers.
Component architecture
Object storage (raw/dt=YYYY-MM-DD/)
│
└─► Partition sensor → Orchestrator (Airflow DAG per partition)
│
├─ Step 1: Snapshot — list all objects, record etags and a content hash
│ → write immutable input manifest to metadata store
├─ Step 2: Register pipeline run (run_id, model_version, snapshot_id)
├─ Step 3: Shard manifest → N shards, enqueue to work queue (SQS or similar)
│
│ [Autoscaled GPU worker pool — KEDA scaling on queue depth]
│ - Pull shard lease with visibility timeout + heartbeat
│ - Load model artifact by digest (never by "latest")
│ - Length-bucketed batching → inference
│ - Write output to staging: out/{run_id}/{shard_id}/{attempt_id}.parquet
│ - Conditional commit to metadata store (first writer wins)
│
├─ Step 4: Validate — reconcile committed row counts against manifest
├─ Step 5: Publish — MERGE committed files into Iceberg/Delta table
└─ Step 6: Mark run complete, emit metrics and lineage events
Keep per-document parallelism inside the work queue, not inside Airflow. Airflow's scheduler cannot manage 10^5+ tasks without degrading; shards of ~50K documents each (~5–10 min of work) are the right unit of orchestration.
Exactly-once semantics: the commit protocol
Workers execute at-least-once — that's unavoidable. Exactly-once output is achieved by making the commit idempotent.
- Every attempt writes to a unique path keyed by
(run_id, shard_id, attempt_id). Retries never overwrite prior attempts. - After writing, the worker issues a conditional insert to the metadata store:
INSERT INTO shard_commits (run_id, shard_id, attempt_id, row_count, file_uri) WHERE NOT EXISTS (run_id, shard_id). This can be a Postgres unique constraint or a DynamoDB conditional expression. The first successful writer wins; all subsequent attempts fail the condition and their output files are garbage-collected. - The publish step reads only committed file URIs. It runs a
MERGE ON (doc_id, run_id)inside a single Iceberg/Delta table transaction, making re-running publish a no-op.
Two common mistakes to avoid:
- Don't rely on S3 put-if-absent to enforce uniqueness. S3 has no atomic conditional write in the general case; the commit point must be a transactional metadata store or the table format's own transaction log.
- Per-document errors don't fail the shard. Malformed or over-length documents are written to a separate
errorstable with a typed reason code. The shard still commits. This avoids indefinitely retrying a shard that contains one bad document.
Partial completion and resumability. A run is resumable: re-triggering re-enqueues only shards without an existing commit record. A run is only marked complete when committed shard count equals N and the total committed row count reconciles against the manifest document count.
Autoscaling
Use queue depth as the primary scaling signal (KEDA works well here). Scale-out is aggressive; scale-in should be conservative to avoid thrashing on bursty arrivals.
Use a mix of on-demand and spot instances. Spot is safe here because shards are small enough (~5–10 min) that the expected cost of a preemption is low, and the retry mechanism handles it. Track spot preemption rate as an operational metric.
Versioning and lineage
The metadata store needs four tables to answer any lineage query:
input_snapshot — (snapshot_id, partition_date, manifest_uri, doc_count, content_hash). The manifest records per-object etags, so a mutated or late-arriving file in S3 is detectable.
model_artifact — (model_version, registry_uri, weights_sha256, tokenizer_version, prompt_template_hash, label_map_version). The prompt template and preprocessing steps are part of the model version — changing either requires bumping the version.
pipeline_run — (run_id, snapshot_id, model_version, code_image_digest, config_hash, status, started_at, finished_at). run_id is derived from a hash of its inputs, so identical inputs yield the same run ID (idempotent triggering).
Output rows carry (doc_id, label, score, model_version, run_id, snapshot_id, inferred_at).
Downstream consumers query a view like sentiment_current that is pointed at an approved model_version. Swapping model versions updates the view definition, not the underlying history.
Workers always load weights by digest from an immutable model registry (MLflow, SageMaker, or equivalent). "Latest" tags are forbidden in production workers.
Monitoring and alerting
| Category | Metric | Alert threshold |
|---|---|---|
| Completeness | Manifest doc count vs. published row count + error row count | Any gap > 0 blocks run completion |
| Completeness | Shards committed / N | Alert if < 100 % after expected duration |
| Timeliness | Partition-landed → results-published latency | Alert at 80 % of SLA window |
| Throughput | Tokens/s per GPU, GPU utilization | Alert if utilization < 60 % sustained (idle fleet) |
| Cost | Cost per 1M documents | Alert on > 20 % week-over-week change |
| Reliability | Retry rate, dead-letter queue depth, OOM count, spot preemption rate | DLQ > 0 triggers investigation |
| Data quality | Label distribution shift vs. rolling baseline | Statistical alert (e.g., PSI > 0.1) |
| Data quality | Null/invalid output rate per shard | Alert if > 0.1 % of a shard |
| Lineage | Any output row with missing run_id or model_version | Alert immediately |
The completeness reconciliation step (Step 4 above) is not optional — it is the primary defense against silent data loss, which is harder to detect than an outright job failure.