High-Volume Batch Inference Pipeline
Classify 100 million records before 6 a.m., make every retry harmless, and agree in advance what ships when the run falls behind.
- Kind
- Case study
- Level
- Core
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 20 Nov 2026
Practise this as a worksheet: High-Volume Batch Inference Pipeline
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: classify 100 million records overnight, publish by 6 a.m., and when the run is behind, let a policy agreed in advance decide what ships.
30-Second Cheat Sheet
- The job: classify 100 million records overnight and publish the labels by 6 a.m., inside a six-hour window.
- The reader: the morning operations team plans the day's work and outreach from those labels. A late or untrusted file costs them a morning.
- The visible problem is throughput. The hard problem is recovery: crashes, throttling, malformed output and a job that is behind at 4 a.m.
- The decision before the run: may a clearly labelled partial result be published, or is everything held?
- The shape: snapshot → partition → infer → validate → checkpoint → publish or hold. Deterministic orchestration around a model call, no chat agent.
- The dangerous constraint: meet the deadline or handle it by policy, and never produce duplicate results or a silently partial dataset.
- The variant: a bank document platform reuses the same spine and adds OCR, schema-constrained extraction, human review and reprocessing by model version.
1. Finish 100 Million Records Before 6 a.m., or Know Exactly What Ships
The product
- A catalogue team must classify 100 million records overnight.
- The labels are published by 6 a.m., inside a six-hour window.
- The morning operations team reads them to plan the day's work and outreach.
- A late or untrusted file costs them a morning.
Throughput is visible, recovery is hard
- Workers crash.
- The model provider throttles.
- Some model output is malformed.
- At 4 a.m. the job may be behind.
- Before the run starts, the customer decides: may a clearly labelled partial result be published, or is everything held?
The terms that carry the whole case
| Term | Meaning |
|---|---|
| Batch inference | Runs a model over a large, fixed set of records offline, rather than answering live requests one at a time |
| Snapshot | A frozen, versioned copy of the input, pinned with the model, prompt and output-schema versions. Nothing in it changes during the run. |
| Partition | A bounded slice of the snapshot |
| Partition manifest | Lists every partition and its status |
| Lease | A time-limited claim a worker holds on a partition. If the worker dies, the lease expires and the partition becomes available again. |
| Idempotency key | Makes repeating a write produce the same single result. Here it is the triple (job_id, record_id, model_version). |
| Checkpoint | A durable record of how far a partition has progressed. It advances only after the result write succeeds. |
| Quarantine | A holding area, with a reason and lineage, for records that retrying will never fix |
| ETA | Estimated time of arrival: the live forecast of when the job will finish |
The core idea in five boxes
freeze the snapshot → leased workers classify → validate → write each result once → on time?
Yes → publish everything.
No → apply the policy agreed in advance.
Freeze the job, process it in replayable pieces, and let a pre-agreed policy decide what gets published.
The diamond is the important part. When the run is not on time, nobody improvises: the branch leads to a rule the customer already signed off.
The same spine, a bank variant
- A bank extracts structured data from millions of documents on the same spine.
- It adds:
- OCR (optical character recognition: turning scanned pages into text, often where document pipelines quietly lose accuracy).
- Schema-constrained extraction.
- Human review.
- Reprocessing by model version.
2. Follow Tuesday's 6 a.m. Catalogue Job
- One night, end to end, as the source tells it.
- No chat agent picks the next task anywhere. Every step is ordinary, deterministic orchestration around a model call.
- Create and freeze. Operations creates Tuesday's job. The input and the model, prompt and schema versions freeze, so nobody can make a silent prompt tweak mid-run.
- Partition and lease. The planner partitions the snapshot and queues the work. Workers pull partitions under leases.
- Label and validate. The model labels a record. Typed validation checks the output's shape and accepts or rejects it.
- Retry or quarantine.
- A provider 429 (HTTP "Too Many Requests") is retried later.
- Garbage JSON goes to quarantine instead of an infinite retry loop.
- Write once, then checkpoint. Each success is written once under its idempotency key. Only then does the checkpoint advance.
- 4 a.m., behind. The named owner either publishes the 90% that is done or holds everything, exactly as agreed before the run.
snapshot → partition → infer → validate → checkpoint → publish or hold
One record through the night
The record ID and timings are illustrative; the steps and rules are the source's.
| Moment | What happens to r-1042 | What is written durably |
|---|---|---|
| Job creation | Belongs to snapshot snap-tue, frozen with model, prompt and schema versions |
Job record with deadline and publish policy |
| Partition lease | Its partition is leased to worker 7; the queue message carries only IDs | Lease with a visibility timeout |
| First model call | Provider returns 429; nothing ran, so nothing is written | Retry scheduled with backoff |
| Second model call | Model returns a label; typed validation accepts it | Result upserted under (job_id, r-1042, model_version) |
| After the write | Checkpoint advances past r-1042, then the lease is acknowledged | Checkpoint offset |
| Worker 7 crashes later | Lease expires; another worker replays the partition from the checkpoint | Same key, so the upsert changes nothing |
| 4 a.m. | Reconciliation counts r-1042 as a unique committed result | Counted toward the agreed publish rule |
What is out of scope, and the human's narrow job
- Interactive question answering is out of scope.
- The human responsibility is narrow and deliberate: a named owner chooses among contingency options agreed before launch.
- They do not invent a new option at 4 a.m.
3. What You Need to Design
The task
- Design the pipeline starting from its dangerous constraint:
- The 6 a.m. deadline must be met or handled by policy.
- Retries and crashes must never produce duplicate results or a silently partial dataset.
- Explain the system end to end at interview depth.
- Then take follow-ups on:
- Capacity arithmetic
- Idempotency and replay
- Retry and quarantine policy
- The 4 a.m. runbook
- Cost
- Rollout
Who it's for
- Engineers preparing for Forward Deployed Engineer, solutions or applied-AI interviews.
- Especially a round that asks for a batch inference or document-processing pipeline.
FDE = an engineer who sits with the customer, finds the real problem and ships a working system in their environment.
What it assumes you know
- Queues and worker pools
- Idempotent writes
- Rate limits
- Calling a model through an API
The four prompts this case covers
- The source consolidates four related prompts into one read.
- The nightly classification batch is the anchor; every other prompt is a change on top of it.
| Prompt | What it contributes | Where it is taught |
|---|---|---|
| High-Volume Batch Inference System, 100M records before 6 a.m. (anchor) | Design, requirements, sizing, failure policy, evaluation, rollout and delivery | Design walkthrough, Practice (full casebook) |
| OpenAI-style practice prompt: Enterprise Document-Processing Platform (a bank, millions of documents) | Extraction schema, confidence, human review and format drift on the same spine | Bank document platform deep dive |
| Nightly PDF summarisation is too expensive (cost drill) | Change detection and sampled quality audits | Cost pivots deep dive, first card |
| Batch embedding job became too expensive (scenario 13) | Incremental indexing and the changed-versus-embedded comparison | Cost pivots deep dive, second card |
How the sections divide the work
- Design walkthrough: read in order; it is the answer you talk through.
- Technical deep dives: the follow-up mechanics.
- Practice (in the full casebook): test yourself before reopening the walkthrough.
- Quick review: the night before the interview.
Quick Recall: Lines to Say in the Interview
- "Throughput is the visible part. Recovery is the hard part."
- "Before the run, the customer decides: labelled partial result, or hold everything."
- "Snapshot, partition, infer, validate, checkpoint, then publish or hold."
- "The checkpoint advances only after the result write succeeds."
- "One result per job, record and model version, however many times a worker retries."
- "A 429 is retried later. Garbage JSON goes to quarantine."
- "At 4 a.m. the named owner picks an option agreed before launch. Nobody invents one."
Design walkthrough
The goal: a replayable, cost-controlled nightly batch that finishes by 6 a.m., never duplicates or silently drops a result, and follows a pre-agreed policy when it falls behind.
30-Second Cheat Sheet
- Restate it as recovery: "Complete a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule."
- Ask first: can the batch be partial, or is it all-or-nothing? It sets retry, checkpoint cadence and the spend on the last 10%.
- Size it live: 100M / 21,600 s ≈ 4,630 rps; 5,320 rps with 15% headroom; 270 tokens a record ≈ 27B tokens a run.
- Orchestration owns the workflow: snapshot, manifest, leased queue, workers behind a rate coordinator, typed validation, idempotent sink.
- Commit order: sink write → checkpoint → lease ack. Key on (
job_id,record_id,model_version). - Failure policy before the run: fail closed, degrade, queue, human intervention, with five rehearsed drills.
- The 4 a.m. answer: find the bottleneck, pull the smallest lever, use a contingency mode that already has a named owner.
- Roll out by ladder: representative benchmark → 1% → 10% → deliberate failure drills.
Opening line (source's): "Complete a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule."
1. Restate the Throughput Prompt as a Recovery Problem
The prompt and the three voices
- The prompt: classify 100 million records every night before 6:00 a.m.
- Three people want different things at once:
- Business owner: "We just need classifications ready by morning."
- Data platform lead: "Only if it doesn't break the warehouse."
- On-call engineer: "Only if we can rerun it safely when the model or upstream feed fails."
- That disagreement, more than the throughput number, is the problem to solve.
Restate before drawing
- Lead with this sentence as written: "Complete a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule."
- Interviewers use it as a checkpoint: are you solving the business problem or only the throughput problem?
Spoken answer (the source's longer, technology-neutral opening): "We need a nightly batch inference system that classifies about 100 million records and finishes before 6:00 a.m. The design has to account for model rate limits, cost constraints, and downstream capacity so the output is usable by morning. I'd first clarify who consumes the results, what happens if we're behind schedule, and what replay and audit requirements exist before choosing the execution architecture."
Weak vs corrected opening
| Version | What it says | Why |
|---|---|---|
| Weak | "We should build a batch classifier with a fast inference service and a scheduler." | Names tools |
| Corrected | "The customer needs reliable nightly classification results delivered before business users need them, with predictable cost and a clear recovery path when the batch falls behind." | Names value |
The case in one sentence
- Classify 100 million records overnight, finish within a six-hour window, recover predictably from failures, and know what can be published if the deadline can't be met.
- The first design choice is the customer's answer to one question: partial results, or all-or-nothing?
Map the stakeholders
| User | Workflow | Current pain | What the system gives them | Owns which decision |
|---|---|---|---|---|
| Morning operations team (end user) | Consumes classifications before planning and outreach | Output late or untrusted | Usable results by 6 a.m., with explicit status | Not retry semantics |
| On-call data platform engineer (operator) | Restarts failed jobs, checks lag, judges whether a partial run is safe | Alert fatigue, manual cleanup, unclear rerun safety | Bounded replay, a forecast, a runbook | Not whether stale output is acceptable for a campaign |
| Model owner | Versions and approves the model | Input contract drift, wrong artifact in production | Version pinning, the approved artifact per run | Not the downstream SLA |
| Security owner | Reviews access to source records, outputs, logs | Sensitive data in queues and checkpoints | Opaque identifiers, encryption, audit trail | Access and retention |
| Business sponsor | Justifies the recurring cost | A nightly fire drill | A predictable process at a known unit cost | The contingency policy, jointly with operations |
SLA = service level agreement: the promise to the customer, usually with penalties.
- Read the last column carefully.
- The business doesn't decide batch retry semantics.
- The on-call engineer doesn't decide whether a stale classification is acceptable.
- The model owner doesn't own the downstream SLA.
- That division stops one enthusiastic stakeholder from steering the whole design.
2. Ask the Partial-Result Question First
- The brief is incomplete on purpose. The interviewer may confirm volume and deadline, then stop. The gap is the test.
- Ask first: can the batch be partial, or must it be all-or-nothing?
- A late but correct job can be rerun or explained.
- A job that silently drops or duplicates records is much harder to trust.
- The answer sets the retry strategy, the checkpoint cadence and how much to spend on the last 10% of records.
RPM = requests per minute. Providers often cap requests and tokens per minute separately.
The questions to ask in the room
| Question to ask | What it's really asking | What you then decide |
|---|---|---|
| Is 6 a.m. a hard publication deadline? Is partial output acceptable? | If we miss 6 a.m., do we publish 90% of scores or hold everything? | Reconciliation, fallback, and publication policy |
| What is the record-size and token distribution, beyond the mean? | Are most records 200 tokens, or is there a fat tail of 8k-token files? | Throughput, batching, and cost forecast |
| Is inference deterministic and which model/prompt/schema versions must be replayable? | If we rerun Tuesday's job, must we get the same labels from the same model snapshot? | Snapshot and idempotency key |
| What provider quotas, tenant limits and regional restrictions apply? | Does the provider cap us at 2k RPM, and must EU records stay in the EU? | Rate coordination and worker pool |
| Which errors are transient versus permanent? | Is a 429 a retry, or is bad JSON a quarantine forever? | Retry vs quarantine and review |
| Who owns a missed deadline and which fallback model is approved? | At 4 a.m., who can switch to the cheaper model, and is that model allowed at all? | The 4 a.m. runbook |
| Must output be complete, ordered, auditable or available incrementally? | Can downstream start reading finished partitions, or must the file be whole and ordered? | Sink and publication contract |
The fuller map of design axes
- Adds downstream capacity, residency, pre-partitioned data, native batch APIs, ordering and a cost ceiling.
| Question | Design axis it unlocks |
|---|---|
| Who consumes the output, and what breaks if it is late? | SLA: whether the deadline is hard, soft or tiered by segment |
| Can the batch be partial, or must it be all-or-nothing? | Retry strategy, checkpointing, downstream handoff |
| What happens when the job is behind at 4 a.m.? | Recovery decision: speed up, reduce scope, fallback model, or partial results |
| How often does the model change, and who approves it? | Version pinning, validation and rollout control |
| What downstream system receives the classifications, and what can it absorb? | Sink capacity, so inference finishing doesn't overwhelm the consumer |
| What audit, retention or residency constraints apply? | Storage, logging and data movement |
| Are records pre-partitioned by tenant, region or date? | Whether ingestion becomes part of the design |
| How many tokens per record, and is the tail heavy? | Batching, rate limiting, throughput planning and cost exposure |
| Native batch APIs? Global and per-tenant rate limits? | A simple worker pool versus a submission scheduler |
| Does downstream need ordering, or only exactly-once logical results? | Checkpointing, output naming, safe partition replay |
| Is there a hard cost ceiling, and which degraded mode is preferred? | Keeps the design from becoming an uncontrolled compute bill |
When the interviewer withholds an answer
- State the assumption and keep moving.
Spoken answer (source's reusable form): "Given the missing details, I'm going to assume the records are independently partitionable, partial results are only useful if they're explicit and auditable, and the highest-risk constraint is finishing by the deadline without duplicates. That means I'll prioritise shardable work, checkpointed progress, idempotent writes, and rate limiting before I optimise for cost or advanced scheduling. If any of those assumptions are wrong, the design changes in specific ways, so I'd want to validate them early."
Each assumption carries a risk
| Assumption fails | What breaks |
|---|---|
| One record depends on another record's result | Naive parallelism breaks correctness |
| A tenant expects strict completion | A degraded mode that skips low-priority work breaks the contract |
| The provider's batch API has different semantics from synchronous calls | A naive retry loop can duplicate output |
- The batch API's turnaround must also fit the deadline.
- The OpenAI Batch API documented at this review offers a 24-hour completion window.
- So it can't by itself guarantee this case's six-hour publication target.
- Use a contracted compatible service or a separately capacity-tested synchronous/self-hosted path.
3. State Requirements as Testable Constraints
- Separate what the system must do from how well, and keep mechanisms out of both lists.
- "Batch the model calls" is a feature.
- "Finish by deadline" is a constraint.
- "Scale workers up and down" is a mechanism, not an outcome.
Functional requirements
- In plain terms: create, inspect, pause and replay jobs; freeze the input and model configuration; partition and process records; validate typed outputs; write once logically; retry transient failures and quarantine permanent ones; reconcile and publish by the agreed policy.
| # | Requirement |
|---|---|
| F1 | Freeze a nightly input snapshot, partition it, classify every record under quota, and publish usable output before the deadline |
| F2 | Partition work into independent, balanced units so the system scales by parallelism rather than by heroics |
| F3 | Schedule and autoscale workers, batching model calls where the provider supports it |
| F4 | Rate-limit globally and per tenant, so retries never stampede the provider into self-inflicted throttling |
| F5 | Checkpoint progress and write idempotently, so a replay never produces duplicate logical results |
| F6 | Forecast completion continuously and invoke a pre-agreed contingency mode when the deadline is at risk |
| F7 | Retry transient errors with backoff; quarantine permanent ones with triage context |
| F8 | Expose pause and replay-failures as authorised, idempotent operations |
Non-functional requirements
- Each row is phrased so a test can pass or fail it.
- The formula to write on the board:
required rate = (N_records / T_window) × (1 + h), wherehis the headroom fraction.
| Constraint | Stated so it can be tested |
|---|---|
| Deadline and latency | Six-hour window. 100M records in 6 hours ≈ 4,630 records/s, or 5,320 with 15% headroom. The budget covers queueing, batching, writeback, validation and reconciliation, not only inference |
| Availability | Accepts and processes work throughout its window, sized against the tail of large or slow records, not the mean, because the slowest few percent (stragglers) decide when the batch finishes |
| Correctness | No missing or duplicate logical results; bounded replay from durable checkpoints after any crash |
| Reliability | Durable checkpoints and recoverable workers; queue messages carry opaque IDs, not payloads |
| Quality | An agreed error rate, confidence threshold or validation pass rate before publishing |
| Freshness | Results available downstream within an agreed time after the source closes |
| Security | Tenant isolation; records and results secured; authorisation on job APIs and data paths; inputs, prompts and outputs protected per the customer's access and retention rules across every hop |
| Compliance | An auditable record of which snapshot, model version and partition produced every classification |
| Operability | Observable ETA and explicit incident ownership |
| Cost | Bounded spend and provider calls; cost per million records measured. Retries re-spend full tokens (5% retries ≈ 5% more spend; a retry storm can double it), and stragglers keep workers warm, so both are watched as cost lines |
Prioritise with a strict ladder
- Must: independent partitioning, deadline protection, idempotent writes, restartable execution.
- Should: autoscaling, batching where it helps, global plus per-tenant limits.
- Could: ranking low-value records, richer per-customer scheduling, manual override tooling.
Fence the MVP
MVP = minimum viable product: the smallest version that real users actually use.
- Excluded:
- Cross-job optimisation across unrelated workloads
- Any per-record interactive feedback loop
- A training pipeline in the batch path
- Arbitrary ad hoc queries
- Optimal cost in every failure mode
- Why: each extra responsibility makes deadline risk harder to reason about.
Trace every requirement to a design element
- If a box on the whiteboard has no row here, ask why it exists.
| Requirement | Design element |
|---|---|
| Partition work independently | Input sharding, partition metadata, and per-shard task queues |
| Schedule and autoscale workers | Queue depth monitoring, worker pool, and autoscaling policy |
| Batch model calls where appropriate | Request bundling layer and provider batch submission path |
| Rate-limit globally and by tenant | Central admission controller and tenant quota enforcement |
| Checkpoint progress and write idempotently | Durable checkpoint store and idempotent output sink |
| Forecast completion and invoke contingency plans | Progress estimator and alerting / fallback controller |
| Finish by deadline | Scheduling policy that favors the critical path |
| No missing or duplicate logical results | Idempotency keys, replay-safe writes, and reconciliation checks |
| Bounded cost | Spend guardrails, batch sizing policy, and degraded-mode rules |
| Restart without full replay | Partition-level checkpoints and resumable task state |
Spoken answer (to "What are the requirements?"): "Functionally, freeze the job, process partitions, validate, write once, retry or quarantine, then publish by policy. Non-functionally, hit the six-hour window, isolate tenants, and know at 4 a.m. whether partial output is allowed."
4. Size From the Deadline and the Tail
- The first design that comes to mind (a queue, a few workers, a model endpoint) works at average load.
- It ignores the deadline, the retry rate and the hard last 5% of records. So derive the numbers live.
The rate arithmetic
- Window: 6 × 3,600 = 21,600 s.
- Base rate: 100,000,000 / 21,600 ≈ 4,630 records/s. That's the floor.
- Planning rate: + 15% headroom for retries, stragglers and reconciliation → 4,630 × 1.15 ≈ 5,320 records/s.
| Scenario | Records | Window | Base rate | With 15% headroom |
|---|---|---|---|---|
| Current batch | 100M | 6 hours | ~4,630 rps | ~5,320 rps |
| 10x growth | 1B | 6 hours | ~46,300 rps | ~53,200 rps |
- The 10x row is a design test, not a forecast. Nobody expects a billion records tomorrow. It shows whether the design is fragile or absurdly overbuilt.
- Keep headroom and growth apart.
- Headroom covers noise inside one batch.
- Growth covers next quarter's larger batch.
- Mixing them hides both. State average, peak, growth and headroom separately, not one point estimate.
Tokens, not records, set the real load
| Quantity | Arithmetic | Result |
|---|---|---|
| Tokens per record | 250 input + 20 output, before retries | 270 |
| Tokens per run | 100M × 270 (records × tokens, not a rate × one hour) | 27 billion |
| Sustained token rate | 5,320 × 270 | ≈ 1.43 million tokens/s |
| Requests | ~5,320 records/s packed 64 per request | ≈ 83 requests/s, or 4,988 RPM, before retries |
| Input tokens/minute | Under the 250-in assumption | ≈ 79.8M |
| Output tokens/minute | Under the 20-out assumption | ≈ 6.38M |
- Include retries, long-tail records and output variance in the estimate.
- Let the token figure, not the record count, drive partitioning and component choice.
- Quota is often the real ceiling: the provider's tokens-per-second (or per-minute) quota.
- Input and output limits must fit separately.
- Request packing doesn't remove token quota.
- CPU workers can look idle while the run is throttled at the provider.
- All of these are illustrative planning numbers. Replace them with the customer's measured p50 and p95 tokens per record, model latency, batch efficiency, provider throttling, sink throughput and hot partitions.
p50 / p95 = the value half / 95% of records fall under.
Spoken answer (source's): "At 100 million records, I would plan for about 4,630 records per second before retries. If the average prompt is smaller than expected, model throughput becomes easier; if the tail of large records is heavier, we need more headroom or more aggressive partitioning. I would size the system around the tail, not the mean."
Cost follows from the same arithmetic
- The capacity deep dive works it through. The short version:
- Retries of calls that actually ran re-spend their full 270 tokens.
- An up-front 429 doesn't establish that useful inference completed; billing follows the provider contract.
- The 15% headroom reserves capacity. It doesn't automatically add 15% billed tokens to a hosted run.
- So the cost ceiling belongs inside the rate-limit coordinator's backoff behaviour, not in a separate finance conversation.
5. Draw the Architecture End to End
Division of labour
- The model (a classifier or an LLM, a large language model that reads and writes text) performs classification or extraction.
- Deterministic orchestration owns partitioning, deadlines, retries and publication.
- No autonomous agent needed: the next task is always "the next partition in the manifest".
Follow one partition through
- The scheduler accepts an idempotent job request and records its deadline, publication policy, and model, prompt and schema versions.
- The planner freezes an immutable input snapshot and creates the partition manifest. The ETA forecaster starts watching remaining work.
- Durable leases assign opaque record IDs to autoscaled workers. Workers fetch the scoped input themselves and batch calls where the provider allows it.
- A shared rate coordinator applies provider and per-tenant quotas before any worker calls the model.
- Workers validate the typed output, then upsert it under (
job_id,record_id,model_version) so a replay can't duplicate a result. - Only after a successful sink write does the worker advance the durable checkpoint and acknowledge the lease.
- Advance only across a contiguous range of committed or policy-finalised records, not past the highest ID returned by an out-of-order batch.
- Track completion ranges or a bitmap so one failed earlier record can't be skipped.
- Transient errors retry; permanent errors enter quarantine.
- Reconciliation compares results, failures and the manifest. Publication follows the customer's pre-agreed complete-or-partial rule.
Each layer owns a different kind of truth
- Planner: what "this batch" means.
- Queue: coordinates delivery. A manifest lease epoch records current ownership.
- Visibility timeouts don't prevent every duplicate delivery, or a paused worker resuming after its lease expires.
- Fence sink and checkpoint updates with the current lease epoch and reject stale workers.
- Sink: what has been published.
- When two components disagree after a crash, that ownership tells you which to believe.
Lease epoch = a counter that rises each time a partition is re-leased, so writes from an older holder can be rejected.
Control plane and data plane
- Control plane (coordinates the run): scheduler, job planner, partition manifest, ETA forecaster, operations console.
- Data plane (moves records into durable output): durable work queue, rate-limit coordinator, inference workers, checkpoint store, result sink, external model.
- They scale and change at different rates, which is why they're drawn apart.
Control-plane detail:
- Scheduler or API with an idempotency key → planner freezes snapshot, model version, deadline and policy → manifest tracks ranges, attempts and checkpoints, with the ETA forecast and operations console beside it.
- Freeze the snapshot before leasing any work.
- Only opaque lease IDs cross into the durable queue (visibility timeout, retry and dead letter).
Data-plane detail:
- Workers read each range once → chunk into batches of 64 → ask the rate and concurrency coordinator → call the external model with deadlines → validate typed output → quarantine bad output / upsert valid output keyed by
job_id,record_id,model_version→ advance the checkpoint after the write → acknowledge or release the lease. - The coordinator owns every grant-or-delay decision, so it owns backpressure.
- The external model is untrusted in the operational sense: it can time out, return 429s or return invalid output. The worker is written to expect all three.
The nine components
"Closed" = stops the run rather than guess. "Degrades" = keeps working at reduced capacity.
| # | Component | Responsibility | State owned | Fails how |
|---|---|---|---|---|
| 01 | Job planner | Accepts the nightly run, freezes the input snapshot, creates the batch plan | Run metadata, snapshot pointer, deadlines | Closed: a broken snapshot hash or unknown model version stops the run |
| 02 | Partition manifest | Lists balanced work units and their status | Partition IDs, ranges, attempts, checkpoints | Closed: a corrupted manifest is never guessed around |
| 03 | Durable work queue | Hands out partitions to workers with leases | Lease state, visibility timeout, retry eligibility | Degrades: an expired lease is reissued; dead-letter after too many attempts |
| 04 | Rate-limit coordinator | Shapes outbound calls to stay under quota | Token budget, concurrency budget | Degrades: slows leases rather than letting retries stampede |
| 05 | Autoscaled inference workers | Batch records and call the model | Ephemeral execution state | Degrades: a crash loses no committed work; the lease expires |
| 06 | Checkpoint store | Persists completed ranges and partial progress | Last successful offset, result hashes | Closed: a corrupted checkpoint fails the partition, never skips it |
| 07 | Idempotent result sink | Writes final classifications once per record | Final output by record key | Degrades: bounded buffer and backpressure, then circuit-break |
| 08 | ETA forecaster | Estimates completion and lag risk | Progress rate, remaining work, backlog | Degrades: a missing forecast is itself an alert |
| 09 | Operations console | Shows run status, warnings, intervention controls | Human-facing incident and rollout state | Degrades: runbook and pager still work without it |
The seven-step happy path
- Snapshot the input and build the manifest, recording the dataset version, deadline and run policy.
- Split into partitions balanced by processing cost. Tenant, payload-size band or historical latency beats record count alone: two partitions with the same row count can take very different times.
- Lease work to workers through the durable queue, so the planner never waits on any worker.
- Batch records and ask the rate-limit coordinator for capacity before calling the model.
- Write rows to the idempotent sink, and only after the write succeeds, checkpoint the completed range.
- Retry transient errors per policy; quarantine permanent ones with triage context.
- Reconcile the manifest and publish the completed dataset.
- The source's figure labels step 5 by its checkpoint alone; the sink write comes first, as the data-plane figure shows.
- A checkpoint that ran ahead of the write would record progress that doesn't exist.
Three trust boundaries
- After the planner freezes the snapshot, the run can't drift if upstream data changes.
- The model call is external, so the worker assumes timeouts, throttling, malformed responses and partial failures.
- Publication must be idempotent, so replays can't create duplicate classifications.
MVP vs later
- MVP: planner, manifest, queue, worker fleet, checkpointing, idempotent sink, a basic ETA panel.
- Later: smarter rebalancing, historical throughput prediction, tenant-aware scheduling.
- Common mistake: presenting those later items as the architecture itself.
- Draw the flow, but speak in obligations: every component protects the deadline, cost, replayability or operator confidence.
6. Make Duplicate Work Harmless
- A crashed worker will redo some work. You can't prevent that. The choice is whether a repeat is dangerous or harmless.
- A unique key prevents duplicate rows, but a replayed model call can produce a different value.
- Preserve the first validated commit with insert-if-absent or a conditional write.
- Compare the result hash on a repeat and record a conflict rather than silently replacing an accepted label.
- Here "upsert" means that immutable logical-result contract, not unconditional last-write-wins.
Be precise about the claim
- Workers may run more than once.
- Leases + idempotent sink + checkpoint-after-write give an exactly-once effect: one logical result per key.
- Avoid claiming physical exactly-once execution: the model may still be called twice for the same record.
The ordering rule
commit the output → advance the checkpoint → acknowledge the queue lease
This table is an authored trace of the source's ordering rule.
| Crash point | What survives | What happens on replay | Cost |
|---|---|---|---|
| Before the model call | Lease only | Lease expires; another worker reads the range from the last checkpoint | None beyond the delay |
| After the model call, before the sink write | Nothing new | The record is reprocessed from the checkpoint | One repeated model call |
| After the sink write, before the checkpoint | The result row | Reprocessed; the upsert by the same key changes nothing | One repeated model call |
| After the checkpoint, before the lease acknowledgement | Result and checkpoint | The lease expires; the replay starts after the checkpoint | Little or none |
- Every crash point replays safely, but may still pay for another model call. Track replay cost as its own number.
The key
- Business identity plus model version: (
job_id,record_id,model_version). Never the worker or the attempt. - "Why not just
record_id?" Without the model version, a rerun under a new model silently overwrites yesterday's answer, and replay loses its meaning.
Idempotency at every write boundary
- A duplicate create doesn't create a second job.
- A duplicate lease renewal doesn't invalidate the original lease.
- A duplicate result write overwrites the same logical record.
- A duplicate pause or replay request is harmless.
Versioning
- When the model, schema or validation policy changes, old and new results must stay distinguishable.
- The job contract deep dive gives the three durable records and the API; the worker-loop deep dive gives the required ordering and two tests.
- Caveat: this case supplies a flowchart and test descriptions, not executable worker code or evidence that those tests ran.
7. Decide the Failure Policy Before the Run
- A failure policy goes beyond "we retry". It answers what to retry, for how long, against which snapshot, with what evidence, and who is paged.
- Every external dependency and every irreversible action needs one.
The basic split
| Error class | Examples | Policy |
|---|---|---|
| Transient | Throttling, network failure, temporary sink outage | Retry with exponential backoff, jitter and a cap on attempts |
| Permanent source error | An invalid file under the frozen input contract | Quarantine with reason and lineage |
| Malformed model output | Can be stochastic, not permanent | One bounded validation retry, then quarantine or review. Never loop until a lucky answer appears |
Jitter = a random delay so retries don't arrive in lockstep.
- The one-liner: a 429 is a retry; bad JSON goes to quarantine rather than looping forever.
The four failure policies
| Failure policy | Example triggers |
|---|---|
| Fail closed | Broken snapshot hash, unauthorised worker, corrupted checkpoint, unknown model version |
| Degrade | Transient downstream throttling, temporary feature store slowness, short-lived queue depth spikes |
| Queue | Quota reduction, noncritical partition backlog, scheduled maintenance window |
| Human intervention | 45% complete at 4 a.m. with no plausible path to deadline, repeated sink throttling, repeated crash loop, or any case where delayed output is worse than no output |
- Memorise one trigger per row. An interviewer who invents a novel failure wants you to classify it into this table on the spot.
Five failure drills
- Each drill runs detect → contain → recover → prevent. Read across a row for the full response.
| Drill | Detect | Contain | Recover | Prevent |
|---|---|---|---|---|
| 1. The 4 a.m. incident | Progress metrics, partition completion, deadline projection, not the pager at 5:59 | Freeze risky retries, preserve the checkpoint, snapshot evidence: lease holder, active partitions, error budget, queue depth, sink health, quota state | Raise concurrency within safe limits if reachable; otherwise degraded mode | Tighter scheduling assumptions, earlier canaries, a forecast visible long before the final hour |
| 2. Provider quota reduction | Spike in rate-limit responses, drop in successful calls per minute | Immediate backoff and a circuit breaker | Rebalance across remaining capacity, smaller batches, defer low-priority partitions | Quota-aware scheduling, preflight capacity checks, a runbook naming which tenant classes pause first |
| 3. Hot partition, stragglers | Partition duration histograms, worker idle time | Split the hot partition or reassign workers if the snapshot model allows | Redistribute load; cap retries per shard | Partition keys with better cardinality; detect "elephant" tenants before the run |
| 4. Worker crash after the model call | Lease expiry | Nothing is marked complete until every row is durable | Resume from the immutable snapshot; overwrite identical results or skip finalised rows | Deterministic record keys; complete only after all rows are written |
| 5. Result sink throttles | Sink latency, queue age | Bounded retries with jitter, then circuit-break the sink and slow intake upstream | Past the retry budget, move partitions to a dead-letter path or durable retry queue and page a human | Escalation policy in the runbook before launch |
- The same shape across all five: never push harder against a failing dependency.
- Slow the arrival rate at the coordinator.
- Preserve evidence before repair.
- Escalate when the deadline is no longer recoverable.
Circuit breaker = a switch that stops calling a dependency after repeated failures. The pending work stays durable in the queue.
Reconciliation is the last line
- Compares the manifest count, the successful unique results and the quarantined records.
- Publish only when the manifest ID sets and stored policy agree:
- Every input ID has exactly one selected validated result or an explicitly permitted terminal failure.
- No unknown IDs and no overlapping states.
- Counts alone can hide one missing and one duplicated ID.
- Write an immutable publication manifest with model-cohort and completeness metadata, then atomically promote its version pointer, so consumers never see a half-published run.
Soundbite (the ownership statement): "This design contains blast radius by tenant, region, workflow, and dependency; it retries only within a bounded policy; it preserves evidence before repair; and it escalates when the deadline is no longer recoverable."
8. Answer the 4 a.m. Question Before It Is Asked
- The signature follow-up: the job is 45% complete at 4 a.m.
- The forecaster should already have flagged it. If this is the first anyone hears of it, the monitoring failed before the job did.
Compute what is still required
Illustrative assumption: the window opened at midnight.
| Quantity | Arithmetic | Result |
|---|---|---|
| Observed rate | 45,000,000 done ÷ 14,400 s (four hours) | ≈ 3,125 records/s |
| Remaining work | 55 million records in 7,200 s | Needs ≈ 7,640 records/s |
| Gap | 7,640 vs 3,125 observed, and vs the 5,320 plan | Roughly 2.4× the observed rate, well above plan |
- That gap tells you whether adding workers can possibly be enough.
The console answers three questions, not just turns red
- Can we still finish by 6:00 a.m.?
- Which lever do we pull first?
- What is the blast radius if we keep going?
Find the bottleneck first
- It's one of four: compute saturation, a hot partition, provider throttling (quota pressure), or downstream backpressure from the sink.
Then the smallest intervention that restores schedule confidence
| Lever | Condition / caveat |
|---|---|
| Raise concurrency | Only if the provider quota and the sink both have headroom. More workers against a throttled provider just produce more 429s |
| Split slow partitions | The split must keep deterministic IDs so the work stays replayable |
| Switch remaining work to an approved fallback model | A fallback changes what the output means, so it's approved and versioned in advance. Put it in a distinct execution cohort and select one accepted result per input ID in the publication manifest. The key includes model_version, so two versions can coexist; their presence alone doesn't say which one downstream should use |
| Publish only the subset that meets the bar | Only if partial publication is allowed |
Temporary vs persistent
- Temporary throttling: the coordinator reduces concurrency and keeps the run stable.
- Persistent, or success impossible: stop taking new leases → checkpoint everything → page the customer with a recovery plan and the exact incomplete count.
- Never silently publish a partial dataset.
Both branches preserve state
- ETA forecaster detects miss risk.
- Still reachable → coordinator reduces concurrency → workers continue on safe partitions.
- Not reachable → planner stops leasing → checkpoint store preserves completed, in-flight and quarantined partitions → console pages the customer → sink rejects duplicates on replay.
- Even the "give up" branch is an orderly stop: no partition is lost, and on resume the idempotent sink absorbs the replays.
Contingency modes: business decisions agreed before launch
- The product owner and operations lead agree them before the first run, not after the first miss. Each has a named owner.
- Continue at full accuracy until the cutoff.
- Switch to a cheaper or smaller model.
- Reduce low-value record classes.
- Narrow scope to the highest-priority segments.
- Pause nonessential enrichment.
When partial results are publishable
- Only under a partial-acceptance policy the customer defined.
- Partial regime: completed partitions publish when each unit is independently valid and clearly labelled.
- All-or-nothing regime: downstream can't handle mixed vintages.
- State which regime applies. If partial, define the exact publish gate and the completeness metadata that travels with the file.
Mixed vintages = records labelled by different runs or models side by side.
Two more probes in this part of the round
- Rebalance a hot partition:
- Detect early through lag, runtime histograms and queue age.
- Split with a deterministic key so the work stays replayable.
- If in flight, move only the unprocessed remainder and record the new ownership in the manifest.
- Avoid paying twice after a timeout:
- Treat the timeout as ambiguous: the call may or may not have completed.
- Idempotency keys, durable checkpoints and write-side deduplication protect the logical result, but can't guarantee a repeated inference call is free.
- Reconcile the provider request ID or batch status before resubmission, when that API supports it.
9. Defend Four Trade-Offs With a Verdict First
- State each verdict in one sentence before you justify it.
- Slogans such as "always batch bigger" cost you more than a missing detail: they show you haven't thought about when the slogan fails.
| Trade-off | Verdict |
|---|---|
| Larger batches vs tail latency | Batch as large as needed for throughput, but small enough that a failed or slow partition can be retried without jeopardising the window. Batch size is a risk-control knob |
| Provider API vs self-hosting | Provider when time-to-value and operational simplicity dominate; self-hosting when latency control, cost predictability or data residency justify the burden |
| Dynamic repartitioning vs manifest simplicity | Start with a static manifest (easier to replay and audit) and explain how skew is detected and the offending slice split manually |
| Full quality vs fallback model at deadline risk | Switch remaining work to a cheaper, faster fallback only if the output is still useful and clearly marked, under a publishability policy the business owns |
- The same verdicts govern scale, latency and cost:
- Shard the immutable manifest and autoscale workers to the measured records per second.
- Batch calls while respecting output size and tail latency.
- Use global rate control, so a local increase in workers can't overload the provider.
The riskiest assumption
- The backlog is evenly distributed and model runtime is stable.
- When challenged, agree rather than defend.
Spoken answer (source's): "If skew is worse than expected, I would treat partition imbalance as the first-class risk, because a few hot shards can dominate the batch window. I would size the system so that we can split or retry those shards without restarting the entire job."
10. Measure Deadline, Duplicates and Stragglers
- "The job finished" proves little. A batch can finish and still have published duplicates, spent twice its budget, or been rescued by one operator at 5:50.
- The scorecard separates throughput, correctness and cost, and gives each metric an owner.
| Metric | What it proves | Calculation and source | Strong threshold | Owner |
|---|---|---|---|---|
| Completion forecast vs deadline | The run will land before 6 a.m. | Completed work / remaining work plus observed throughput | Never crosses the deadline without a contingency activated | Operations |
| Duplicate logical result count | Replay is safe and the sink truly idempotent | Comparing logical keys, not storage rows | Zero duplicate committed logical results; duplicate attempts tracked separately | Data engineering |
| Records per second | Sustained throughput meets the required rate | Worker telemetry and sink acknowledgments | At or above the forecast needed to finish | Platform |
| Tokens per second | Explains cost and quota pressure better than records | Request logs, model client instrumentation | Doesn't rise faster than the representative distribution | ML platform |
| Straggler age | No single partition monopolises the fleet | Partition timestamps and duration histograms | Oldest active partition within the recovery budget | Batch platform |
| Retry rate | Failures are transient, not systemic | Retry counters and failure taxonomy | Within the normal band by failure class | On-call |
| Cost per million records | Unit economics hold under retries and stragglers | Cloud billing plus model usage logs | Inside the approved budget envelope | Finance / platform |
- Also track: predicted vs actual ETA, partition skew, duplicate-key conflicts, quarantine rate and reasons, typed-output validity, provider quota errors and throttles, lease retries, the oldest queued partition, unique committed records, sink p95 latency and replay spend.
Build the dashboard top-down
| Layer | Shows | Who reads it |
|---|---|---|
| Headline | Will the batch complete by 6:00 a.m.? Forecast, remaining partitions, contingency mode | Business user: is it on track? |
| Levers | Records/s, tokens/s, retry rate, straggler age, queue depth, sink lag | Operator: which subsystem is slowing it? |
| Correctness | Duplicates, rejected inputs, checkpoint freshness, replayed partitions | Engineer: trace a retry spike to a quota cut or a bad input cohort |
Four layers of evaluation, kept distinct
- Technical health
- Model quality from sampled evaluation
- Adoption by downstream teams
- Business outcome
- A green pipeline says nothing about whether the labels are right.
Recovery needs its own evidence
- Test on representative token sizes.
- Deliberately crash a worker after the sink write but before the acknowledgement.
- Inject provider quota exhaustion and a sink outage; show restart and reconciliation under each.
- A clean demo run doesn't prove recovery.
11. Roll Out Through a Load-Test Ladder
- The customer's real question is "when can this be trusted in production?", harder than "does it work?".
- Treat launch as a sequence of controlled reductions in uncertainty, each with a gate and an owner.
| Stage | Gate | Owner |
|---|---|---|
| Week 0-1 | Agree who consumes the output, whether partial results have value, and the cost ceiling | FDE with the business sponsor |
| Week 1-2 | Benchmark the representative token distribution: short records, long records, edge cases, known skew, not a toy sample | Platform / ML infrastructure; data owner confirms representativeness |
| Week 2-3 | 1% load test: parsing, auth, model invocation, sink writes and checkpointing hold under real concurrency | Engineering, operations and business jointly |
| Week 3-4 | 10% load test: retry behaviour, throttling and downstream capacity still fit the deadline envelope. A failed 1% gate blocks it, not "a little delayed" | Same joint gate |
| Week 5 | Practise failure on purpose: crash a worker, cut quota, kill a downstream dependency, drain and restore a queue | Batch platform (crash), dependency owner (quota), on-call (incident log) |
| Week 6-8 | Confirm bounded replay, durable checkpoints and graceful degradation rather than retry-storm oscillation | Batch platform |
| After pilot | Define contingency modes with named owners before the job is ever late | Product owner and operations lead |
- The benchmark comes first: a wrong input distribution makes every later estimate wrong (throughput, queue pressure, quota burn, downstream lag).
- Before launch, also assign the contingency owner and write down the missed-deadline decision.
Risk register
| Risk | Owner | Mitigation | Trigger |
|---|---|---|---|
| Quota shrinks unexpectedly | Dependency owner | Lower-rate contingency mode | Sustained throttling or forecast slippage |
| Duplicate logical results rise | Data engineering | Stricter idempotency checks and replay review | Duplicate count above tolerated threshold |
| Sink latency spikes | Platform ops or downstream team | Buffering and backpressure | Queue age exceeding the recovery window |
| Worker crash loop | On-call owner | Rollback or reduced concurrency | Repeated restarts in the canary slice |
The go/no-go gate
Stable throughput
Rehearsed crash recovery
An available contingency owner
Without all three, don't expand. It sounds conservative until the batch misses one deadline because nobody wanted to say no.
Complete the launch plan
- Canarying, rollback, migration, training, support and documentation.
- Canary: a slice of the nightly work runs on the new path; the old path stays as the fallback.
- Rollback: stop new work, preserve checkpoints, resume on the stable path.
Reusable value vs delivery work
| Category | What goes there |
|---|---|
| Configuration | Thresholds, deadlines, model choice, contingency policy |
| Adapters | Warehouse, queue and identity integrations |
| Common service | Retry, checkpoint and rate-limit wrappers |
| Core product | Partition orchestration, replay semantics, the push/degrade/stop policy engine |
Quick Recall: Lines to Say in the Interview
- "Throughput is not the hard part. The decision at 4 a.m. is."
- "Can the batch be partial? That one answer sets retry, checkpointing and the spend on the last ten percent."
- "4,630 records a second is the floor. 5,320 with headroom. Size from the tail, not the mean."
- "Tokens, not records, set the load: 270 a record, 27 billion a run."
- "Backpressure lives in the rate-limit coordinator. Quota tightening slows leases, it does not trigger a retry storm."
- "The checkpoint advances only after the sink write succeeds."
- "Upsert on job, record and model version. Duplicate work becomes harmless instead of dangerous."
- "Fail closed on the snapshot hash, the model version and the checkpoint. Degrade on everything else."
- "The contingency mode has a named owner before launch, not after the first miss."
Technical deep dives
The goal: the mechanisms behind the follow-ups: the job contract, the worker loop's commit order, the cost arithmetic, isolation, the bank variant and the two cost pivots.
30-Second Cheat Sheet
- Contract first: four decisions belong to the customer, not a queue. Store the policy with the job.
- Three durable records:
BatchJob,Partition,InferenceResult(keyedjob_id + record_id + model_version). - Four endpoints: create (idempotency key), status (not-found hides existence), pause (ETag), replay-failures (privileged).
- Worker loop order: lease → read once → batches of 64 → acquire tokens → classify → validate → upsert → checkpoint → complete.
- Two error branches:
TransientErrorretries with backoff;ValidationErrorretries once without backoff, then is a data-quality problem. - Cost: 27B tokens a run; at an illustrative $0.10 per million tokens, $2,700 a run, $27 per million records.
- Security sits outside the model: an immutable snapshot, opaque IDs in queues, per-tenant scope, versions recorded per run.
- Cost pivots share one root: reprocessing what didn't change. Measure, route, bound, cache safely.
1. The Job Contract, Durable Records and API
Get the output contract before the machinery
- Four decisions belong to the customer, not to a queue:
- Complete-only or partial publication.
- What happens to permanently bad records.
- Which fallback models are acceptable.
- Who approves changes.
- Store that policy with the job, so an operator under pressure can't improvise a new one.
- The job record pins the snapshot ID, the partition manifest, the model, prompt and schema versions, the deadline and the publication rule.
- Preserve enough lineage to reproduce one individual result and the whole run.
The three durable records
| Record | Key | Fields | Lifecycle |
|---|---|---|---|
| BatchJob | id |
input_snapshot, deadline, model, state |
queued, running, paused, completed, failed, replaying |
| Partition | job_id + partition_id |
range, lease, attempts, completed_count, checkpoint |
available → leased → completed; retryable on transient failure; abandoned/dead_lettered after too many attempts |
| InferenceResult | job_id + record_id + model_version |
output, status, confidence |
pending → validated → committed; quarantined if rejected, pending reconciliation if persistence is uncertain |
input_snapshotis an immutable pointer to the exact dataset version.- It's the ownership boundary that makes replay possible: a retry can name exactly what it is retrying.
- The result key follows business identity plus model version, for the reason in walkthrough step 6.
The job API
- Small surface: create, status, pause, replay-failures, each guarded by authorisation.
| Endpoint | Contract |
|---|---|
POST /v1/batch-jobs |
Authenticated; validates manifest and model reference. Idempotency key, so a client retry after a timeout doesn't create two jobs. Same key with a different payload is a conflict, not a merge |
GET /v1/batch-jobs/{id} |
Read model: progress, partition counts, failure counts, deadline, model version, state, compact error summary. Unknown id and no access both return not-found, so a caller can't tell whether a job it may not see exists |
POST /v1/batch-jobs/{id}/pause |
Stops new leases and preserves progress. Optimistic concurrency via ETag. Already terminal is a state conflict, not a pretend success. Retried pauses are harmless |
POST /v1/batch-jobs/{id}/replay-failures |
Privileged, because replay reconsumes capacity. Selector for all failed, a named subset, or after a checkpoint. A reused key returns the same replay outcome, never a second attempt |
Three details to defend
| Detail | Backed by |
|---|---|
| Reject a reused idempotency key with a different payload | IETF idempotency-key draft (section 2.7, now expired) and Stripe's idempotent requests |
| Return not-found for a job the caller may not see | Allowed by RFC 9110; the OWASP authorization regression testing cheat sheet notes distinct 403 and 404 answers leak existence |
| ETag on pause | Makes operator actions conditional: two operators pressing pause at once can't overwrite each other's view of the state |
ETag = an entity version tag. The request succeeds only if the version still matches.
2. Leases, Commit Order and the Worker Loop
Why leases make crashes boring
- Partition IDs are deterministic and bounded.
- Queue messages contain only identifiers; workers fetch the scoped records themselves.
- On a crash, lease expiration makes the partition visible again, so no supervisor has to notice the crash.
- The immutable snapshot means the replaying worker reads exactly the input the first one did.
The worker loop, in order
- The smallest implementation to validate is one worker loop. The source draws it as a flowchart, not code.
queue.lease(job_id)claims a partition;source.read(range)reads its records once.chunked(records, 64)splits them into batches of 64.limiter.acquire(tokens)asks for capacity before the call: admission control belongs before the quota breach, not after it.model.classify_batch(batch)makes the call;validate_output(raw)checks the result at a typed boundary.sink.upsert_many(key=record_id)writes idempotently.- The sketch shows the key as
record_idbecausejob_idandmodel_versionare fixed for the whole job. - The stored key is still the full triple.
- The sketch shows the key as
checkpoints.advance(partition, record_id)runs only after the sink write succeeds, which prevents false progress.queue.complete(partition)runs only after every batch in the partition succeeds.
The two error branches differ on purpose
| Error | Action | Why |
|---|---|---|
TransientError |
queue.retry(backoff=True) |
Throttling and network faults clear with time |
ValidationError |
Retry once without backoff (queue.retry(backoff=False)), then re-raise as a data-quality problem |
A second malformed answer suggests the input or prompt is wrong; waiting longer won't fix that |
Two required tests
Caveat: these are described here, not shipped as executable tests.
| Test | What it does | Pass condition |
|---|---|---|
| Contract test | Repeats POST /v1/batch-jobs with the same key |
One job and one id |
| Failure-injection test | Crashes the worker after upsert_many() but before complete() |
On retry, the sink still holds one logical result per record_id: the distinct record_id count equals the row count |
What the sketch omits on purpose
- Multi-worker contention, logging, metrics, tracing, cancellation, authentication, throttling and dead-letter routing.
- Acceptable in an interview only when you can name each omission and say where it would go.
3. Capacity, ETA and Cost Arithmetic
ETA
- ETA = remaining work ÷ observed effective throughput, adjusted for the straggler tail.
- An average-rate graph alone hides deadline failure: the fleet can average 5,320 records/s while one hot partition still holds the last 2% of records at 5:55.
- The MapReduce paper (Dean and Ghemawat, OSDI 2004) made the same observation: stragglers set the batch finish time, and backup tasks for slow work fix it.
Plan with distributions, not means
- p50 and p95 tokens per record, model latency, batch efficiency, provider throttling, sink throughput and hot partitions.
- A provider's tokens-per-second or tokens-per-minute quota may be the real ceiling even when CPU workers look idle.
- The Claude rate-limits documentation describes separate token quotas and 429 behaviour of this kind.
The supplementary cost formula
Provenance: the source chapter treats cost only qualitatively. The author of the source's "V2 tutorial" adds a live dollar formula, which the source labels supplementary perspective, not chapter content.
| Step | Calculation | Result |
|---|---|---|
| Sustained token rate | 5,320 records/s × 270 tokens | ≈ 1.43M tokens/s |
| Tokens per run | 100M records × 270 tokens | ≈ 27B tokens |
| Cost per run | 27,000 million tokens × the provider's price per million tokens | Depends on the price |
| Cost per million records | Cost per run ÷ 100, because the run is 100 million records | Depends on the price |
| Retry overhead | 5% of calls ran and were retried, re-spending 270 tokens each | ≈ 5% more spend |
- Worked example with an illustrative $0.10 per million tokens (not a quoted rate):
- Run: 27,000 × $0.10 = $2,700.
- Per million records: $27.
- A 5% retry rate adds about $135.
Which retries cost money
- A retried inference may re-spend input and output tokens under the provider contract.
- A 429 documents rate limiting, not a universal billing guarantee. Check usage records.
- Track rejected attempts, completed inference and ambiguous timeouts separately.
- A retry storm (failed calls retried fast enough to trigger more failures) can double the bill.
- Headroom vs spend:
- Headroom may cost reserved or idle capacity.
- Actual retry tokens and straggler compute are measured spend.
- Don't add 15% token cost merely because capacity was provisioned with that margin.
- So the cost ceiling belongs inside the rate-limit coordinator's backoff behaviour and the degraded-mode rules, not in a separate finance report.
Soundbite: "Track tokens per record, retry spend, cost per million records, queue age and the deadline forecast together, because a cost change usually shows up in one of the others first."
4. Security, Isolation and Operations
The key control sits outside the model
- Every worker processes a versioned snapshot that can't change beneath it.
- A retry against a mutable table can't prove what it retried.
Snapshot immutability does three jobs
- Removes ambiguity during retries.
- Makes evidence replayable after an incident.
- Limits blast radius: a malformed or malicious tenant dataset touches only that tenant's snapshot, not a global table.
Keep payloads out of the plumbing
- Messages carry only opaque identifiers, snapshot versions, partition keys and lease information.
- Caveat: identifiers, tenant tags and volume can still reveal business metadata, so queues, retries and dead-letter stores stay tenant-scoped and access-controlled.
- No full customer payloads in logs.
- Encrypt input and output; scope snapshots and credentials per tenant; least privilege on the result and checkpoint stores.
- Checkpoint state is sensitive too: it reveals the shape of business data and partial outputs.
Provenance per run
- Record the model version, code version, prompt or feature-schema version and deployment identity for every run.
- Log operator actions and model version changes.
- That's how the team proves which artifact produced which result when a customer asks why today's classification differs from yesterday's.
Two layers of rate control
| Layer | Protects |
|---|---|
| Per-tenant coordinator | Stops one customer from starving the others |
| Global controls | Protect the provider quota |
- Circuit breaking stops repeated failing calls while retaining durable pending work, so pausing a dependency never loses a partition.
Compliance: ask which framework applies first
Provenance: the source chapter names no external compliance framework. The V2 author treats that as a gap; their supplementary answer is to ask which framework applies before claiming compliance.
| Situation | What applies |
|---|---|
| Personal data | Purpose limitation and data minimisation apply to snapshot and result retention |
| Covered entities and business associates processing electronic protected health information | HIPAA's audit-control rule, 45 CFR 164.312(b), applies to the audit trail |
| Firms and records within their scope | Financial record-keeping rules such as SEC rule 17a-4 and FINRA 4511, or SOX |
| Any industry, on customer request | SOC 2: a voluntary audit report, not an industry rule |
HIPAA = the US health-data law (Health Insurance Portability and Accountability Act). SEC = US Securities and Exchange Commission. SOX = the Sarbanes-Oxley Act on financial-reporting controls.
- They also propose a per-run "processing basis" field on
BatchJob. - Without a named framework to test them against, the controls above are necessary but not sufficient.
5. The Bank Document Platform
The prompt
- An OpenAI-style practice prompt: "A bank processes millions of financial documents and wants to extract structured data using AI."
- Same spine, different payload: records become documents, and a label becomes a schema.
- The prompt's decomposition: ingestion, file validation, document classification, OCR or multimodal extraction, schema-constrained output and confidence scoring, validation against business rules, human review, correction feedback, audit storage, and reprocessing with model versioning.
- It asks you to discuss: batch vs online processing, idempotency, retry behaviour, data lineage, model versioning and document-format drift.
Map each stage onto the anchor, don't draw a new system
| Document-processing stage | Where it lives on the anchor | What is new |
|---|---|---|
| Ingestion, file validation | Job planner and snapshot | A document hash and file-type check before a document enters the manifest; corrupt files quarantined, never retried |
| Document classification | First worker pass | Routes each document to its extraction schema; low confidence goes to review, not to a guess |
| OCR or multimodal extraction | Inference workers | Page-level cost dominates, so partition by page count band, not document count |
| Schema-constrained output | validate_output() typed boundary |
The schema is the contract; a field that fails type or range is rejected, never stored |
| Confidence scoring, business-rule validation | After the typed boundary | Rules such as totals reconciling or dates in range catch plausible-but-wrong extraction |
| Human review, correction feedback | New lane off the sink | A review queue for low-confidence and rule-failed fields; corrections become labelled evaluation data |
| Audit storage, data lineage | InferenceResult plus snapshot pointer |
Every field traces to document hash, page, model version and reviewer |
| Reprocessing, model versioning | replay-failures and model_version in the key |
Reprocess a cohort under a new model without overwriting the old answers |
Why partition by page count
- Document extraction services such as Amazon Textract charge per page.
- A 300-page statement and a 1-page form are very different units of work.
- Lineage must point from each output field back to its source page.
Batch vs online is per workflow
| Workflow | Path | Why |
|---|---|---|
| Bulk backfills, nightly statements | Batch | Buys throughput and quota smoothing |
| A document a customer uploads while waiting | Online, with its own latency budget | The customer is waiting |
- The two paths can share the extraction schema and the typed boundary.
The likely follow-up: a new format appears without warning
- Detect: classification confidence drops; schema-validation and business-rule failure rates rise for one cohort.
- Contain: fail that cohort to the review queue rather than publishing low-confidence fields.
- Recover: add the format to the classifier and schema, then replay only the quarantined cohort through
replay-failures. - Prevent: monitor confidence and rejection rates by source and template.
Soundbite: "Format drift is a data-quality incident, not a model bug."
6. Cost Pivots: Nightly PDFs and Embeddings
- After a good design, the usual pivot: "the nightly bill is too high."
- Both cards share one root: reprocessing what didn't change.
- Guardrail: whatever shortcut you propose must not weaken correctness, hide permanent failures or erase provenance.
Nightly PDF summarisation is too expensive
- Setup: thousands of PDFs processed nightly; the cost is too high.
- Ask first:
- Are documents new or changed?
- Is full summarisation required every time?
- What is the SLA?
- Can work be batched off-peak?
- What quality checks are needed?
| Element | Answer |
|---|---|
| Dominant driver | Reprocessing unchanged documents on a premium model |
| Cheapest lever first | Content hash and change detection; dedupe; cheaper model in batch mode; sampled strong-model audit |
| Metric that proves it | Changed ratio; cost per document; queue depth; eval score on the sample |
| Do not | Run every PDF through the premium model every night |
| 60-second line | Never reprocess an unchanged document without a reason. Batch buys throughput not latency, so quality is proven by sampling |
- The source's strong answer adds incremental processing, queue budgets and sampled evaluation.
- The cheaper pipeline: ingest → hash and dedupe → unchanged: reuse last summary / changed: parse → queue only changed documents → summarise in batch with a cheaper model → audit a quality sample with a strong model → publish.
- Hash-and-dedupe is where the money is saved: an unchanged document never reaches a model.
- Trade-off: batch optimises throughput, not interactive latency, so quality is checked by sampling plus strong-model audits.
The batch embedding job became too expensive (scenario 13)
- Setup: the nightly embedding bill spikes after a document refresh.
- Ask: are all documents re-embedded, or only changed content?
- Usual causes: full re-indexing, duplicate documents, no content hash, or a larger embedding model.
| Element | Answer |
|---|---|
| Dominant driver | Re-embedding unchanged and duplicate documents on every refresh |
| Cheapest lever first | Pause the full job; switch to incremental indexing; deduplicate. Later, a content-hash embedding cache with change detection, and off-peak scheduling |
| Metric that proves it | Embeddings generated vs documents changed; duplicate rate; model version; job retries |
| Do not | Re-index the whole corpus because the refresh touched it |
| 60-second line | Embedding should be incremental. Re-embedding unchanged documents is usually a pipeline design issue |
- The debugging step is one comparison: changed document count vs embedded document count. If they differ, the pipeline is the bill.
- Prevention: an indexing budget with anomaly alerts.
- A silent embedding-model upgrade is also a full re-index, so the model version belongs in the cache key, exactly as it belongs in the anchor's result key.
Both cards connect back to the anchor
| Cost idea | Anchor idea |
|---|---|
| Content hash | Immutable snapshot: know exactly what this run is about, and skip what it isn't |
| Sampled audit | Tail-sized evaluation: prove quality on a sample instead of paying the premium model on everything |
The four verbs of a strong cost answer
- Measure: compare changed against processed; trace cost per document.
- Route: the bulk to a cheaper model, the audit sample to the strong one.
- Bound: queue budgets, an indexing budget and anomaly alerts.
- Cache safely: keyed on content hash and model version.
7. References
- The three facts the design leans on:
- SQS visibility timeouts don't guarantee single delivery.
- OpenAI Batch documents a 24-hour window.
- Claude limits distinguish requests, input and output quotas.
- Caveat: the worker tests are proposed tests, not executed code in this casebook.
- The source fact-checked these references on 27 September 2026.
| Reference | What it supports here |
|---|---|
| OpenAI API docs: Batch API | Batch jobs have their own semantics, so a naive retry loop can duplicate work |
| Dean and Ghemawat, MapReduce (OSDI 2004) | Stragglers set batch finish time; backup tasks fix it |
| OpenAI Help Center: Troubleshooting 429 errors | Rate-limited calls are rejected up front |
| Claude docs: Rate limits | Tokens-per-minute quotas can be the real ceiling; 429 behaviour |
| IETF draft-ietf-httpapi-idempotency-key-header-07 (expired), section 2.7 | The same key with a different payload is an error |
| Stripe API reference: Idempotent requests | The same key with different parameters is rejected |
| RFC 9110 HTTP Semantics, 403 and 404 | A server may return 404 to hide a forbidden resource |
| OWASP Authorization Regression Testing Cheat Sheet | Distinct 403 and 404 answers leak existence |
| AICPA and CIMA: SOC 2 | SOC 2 is a voluntary attestation, not an industry rule |
| 45 CFR 164.312(b) Audit controls | HIPAA's audit-control requirement |
| FINRA: Books and Records (SEA 17a-4, FINRA 4511) | Finance record-keeping rules |
| Amazon Textract pricing | Document extraction is priced per page |
Quick Recall: Lines to Say in the Interview
- "The customer decides publication, bad records, fallback models and approvals. The policy is stored with the job."
- "Same idempotency key with a different payload is a conflict, not a merge."
- "Unknown job and no access both return not-found, so existence doesn't leak."
- "Acquire tokens before the call: admission control belongs before the quota breach."
- "A validation error retries once, then it's a data-quality problem. Waiting won't fix a bad prompt."
- "The fleet can average 5,320 a second while one hot partition holds the last 2% at 5:55."
- "A retry storm can double the bill, so the cost ceiling lives in the coordinator's backoff."
- "Format drift is a data-quality incident, not a model bug."
- "Changed count against embedded count: if they differ, the pipeline is the bill."
Quick review
One sentence: design for safe replay and deadline recovery. An immutable manifest feeds leased workers behind shared rate limits, outputs are validated and upserted before checkpointing, and a live ETA plus a pre-agreed publish policy decide what happens when the window is at risk.
30-Second Cheat Sheet
- Ask first: is 6 a.m. hard, and can we publish partial results?
- Restate: a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule.
- Orchestration owns the workflow; the model only classifies or extracts.
- Checkpoint only after the sink write succeeds.
- Derive: 100M / 21,600 s ≈ 4,630/s; 5,320/s with 15% headroom; 270 tokens a record ≈ 27B a run.
- 4 a.m. at 45%: find the bottleneck, smallest lever, pre-approved fallback or labelled partial only if policy allows.
- Key: (
job_id,record_id,model_version) gives one logical result under retries.
1. Open With the Contract and Draw the Path
Ask first
- "Is 6 a.m. a hard deadline, and can we publish partial results?"
- Then the token distribution.
- Provider quotas.
- Permanent errors.
- Fallback approval.
- Replay or version requirements.
Restate the target
- A replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule.
The whiteboard path
job API → immutable snapshot + partition manifest → durable leases → workers → rate coordinator → classifier model or LLM → typed validation → idempotent sink → checkpoint + ack → reconcile + publish
Two rules
- The model classifies or extracts; deterministic orchestration owns the workflow.
- Checkpoint only after the sink write succeeds.
2. Numbers to Derive, Not Recite
| Item | Derivation | Value |
|---|---|---|
| Base rate | 100M / 21,600 s | ≈ 4,630 records/s |
| Planning rate | + 15% headroom | ≈ 5,320/s |
| At 10x | 1B records, with margin | ≈ 53,200/s |
| Tokens per record | 250 in, 20 out | 270 |
| Tokens per run | 100M × 270, before retries | ≈ 27B |
| Token rate | At the planning rate | ≈ 1.43M tokens/s |
| Retry spend | 5% retries | ≈ 5% more spend |
| Up-front 429 | Rejected before inference | Generally costs nothing |
- Confirm everything against measured token and latency distributions.
3. Failure Answer and Five Anchors
At 4 a.m. with 45% complete
- Forecast the remaining capacity needed.
- Inspect quota, hot shards, compute and the sink.
- Increase concurrency only with headroom.
- Use an approved fallback or explicitly labelled partial output only if policy allows.
- If the deadline is impossible: preserve checkpoints, stop leasing and page the owner.
The four failure policies
| Policy | Example |
|---|---|
| Fail closed | Snapshot hash, model version, checkpoint |
| Degrade | Transient downstream throttling |
| Queue | Quota reduction, noncritical backlog |
| Human intervention | 45% at 4 a.m. with no path to deadline |
Five anchors
- An immutable snapshot and pinned model, prompt and schema make replay meaningful.
- A unique (
job_id,record_id,model_version) key gives one logical result under retries. - Transient failures retry with backoff and jitter; permanent failures go to quarantine with lineage.
- Watch the ETA, the oldest partition, throttles, cost per million records and reconciliation counts.
- For document variants, add OCR, typed extraction, human review and versioned reprocessing.
Spoken answer (sixty-second close, from the source): "I design for safe replay and deadline recovery. The immutable manifest feeds leased workers behind shared rate limits; outputs are validated and upserted before checkpointing. A live ETA and a pre-agreed publish policy determine the response when the window is at risk."
4. Key Takeaways
| Topic | Takeaway |
|---|---|
| Framing | A throughput problem on the surface, a 4 a.m. recovery decision underneath. Restate it as a replayable, cost-controlled batch by deadline |
| Discovery | The partial-result question comes first: it sets retry, checkpointing and the spend on the last ten percent |
| Requirements | Split into features and constraints, prioritised must, should, could, each traced to a component |
| Sizing | Starts at 4,630 records/s, plans for 5,320 with headroom, driven by the tail and the 270 tokens a record |
| Architecture | One diagram separates the control plane (coordinates the run) from the data plane (moves records), with three trust boundaries |
| Duplicates | Made harmless by keying on job, record and model version and checkpointing only after the sink write |
| Security | Workers read immutable snapshots, queues carry opaque identifiers, every run records its model, code and schema versions |
| Failure policy | Decided before launch: fail closed, degrade, queue or human intervention, with five rehearsed drills |
| 4 a.m. | Find the bottleneck, pull the smallest lever, use a contingency mode that already had an owner |
| Trade-offs | Four defended with a verdict first; skew treated as the riskiest assumption |
| Scorecard | Completion forecast, duplicates, straggler age, retry rate and cost per million records, not "the job finished" |
| Rollout | Representative benchmark → 1% and 10% gates → deliberate failure drills |
| Bank variant | Same spine: a schema at the typed boundary, a review lane, format drift as a data-quality incident |
| Delivery | Open with the outcome, spend the middle on failure and trade-offs, close on the first rollout gate |
| Cost pivots | Both answered with change detection: never reprocess or re-embed what didn't change |
Flashcard Drill
Quick Recall: Lines to Say in the Interview
- "Is 6 a.m. hard, and can we publish partial results? I ask that first."
- "The model classifies; deterministic orchestration owns the workflow."
- "4,630 a second is the floor, 5,320 with headroom, 27 billion tokens a run."
- "A 429 rejected up front generally costs nothing; 5% retries cost about 5% more."
- "Checkpoint only after the sink write succeeds."
- "Job, record and model version: one logical result, however many retries."
- "If the deadline is impossible: preserve checkpoints, stop leasing, page the owner."
- "Never reprocess or re-embed what didn't change."
Where next
- Practise this as a worksheet
- High-Volume Batch Inference Pipeline
- Revise the concepts