Case brief
Understand the scenario, task, and constraints.
Finish 100 million records before 6 a.m., or know exactly what ships
A catalogue team must classify 100 million records overnight and publish the labels by 6 a.m., inside a six-hour window. The morning operations team reads those labels to plan the day's work and outreach, so a late or untrusted file costs them a morning.
Throughput is the visible part of the problem. Recovery is the hard part. Workers crash, the model provider throttles, some model output is malformed, and at 4 a.m. the job may be behind. Before the run starts, the customer has to decide whether a clearly labelled partial result may be published or whether everything is held.
A few terms carry the whole case, so we define them here and use them consistently:
- 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 together with the model, prompt and output-schema versions. Nothing in it changes during the run.
- Partition: a bounded slice of the snapshot. The 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: a key that 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 diagram is the whole case in five boxes. Freeze the job, process it in replayable pieces, and let a policy agreed in advance 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 extends to a bank that extracts structured data from millions of documents. That variant adds OCR (optical character recognition, turning scanned pages into text, often where document pipelines quietly lose accuracy), schema-constrained extraction, human review and reprocessing by model version.
Follow Tuesday's 6 a.m. catalogue job
Here is one night, end to end, as the source tells it. No chat agent picks the next task anywhere in it; every step is ordinary, deterministic orchestration around a model call.
- 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.
- The planner partitions the snapshot and queues the work. Workers pull partitions under leases.
- The model labels a record. Typed validation checks the shape of the output and accepts or rejects it.
- A provider 429 (HTTP "Too Many Requests") is retried later. Garbage JSON goes to quarantine instead of an infinite retry loop.
- Each success is written once under its idempotency key, and only then does the checkpoint advance.
- At 4 a.m. the job is behind. The named owner either publishes the 90% that is done or holds everything, exactly as agreed before the run.
The whole path is snapshot → partition → infer → validate → checkpoint → publish or hold. To make the state changes concrete, the table below follows one record through that night. The record ID and timings are illustrative; the steps and rules are the source's.
One illustrative record, r-1042, traced through the night's states.
| 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 |
Interactive question answering is out of scope. The human responsibility is narrow and deliberate: a named owner chooses among contingency options that were agreed before launch. They do not invent a new option at 4 a.m.
What you need to design
Design the pipeline starting from its dangerous constraint. The 6 a.m. deadline must be met or handled by policy, and retries and crashes must never produce duplicate results or a silently partial dataset. You should be able to explain the system end to end at interview depth, then take follow-up questions on capacity arithmetic, idempotency and replay, retry and quarantine policy, the 4 a.m. runbook, cost and rollout.
The case is written for engineers preparing for Forward Deployed Engineer (FDE: an engineer who sits with the customer, finds the real problem and ships a working system in their environment), solutions or applied-AI interviews, especially a round that asks for a batch inference or document-processing pipeline. It assumes you are comfortable with queues and worker pools, idempotent writes, rate limits and calling a model through an API.
The source consolidates four related interview prompts into one read. The nightly classification batch is the anchor, and every other prompt is a change on top of it.
The four prompts this case covers, and where each is taught.
| 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 |
| 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 |
Read the Design walkthrough in order; it is the answer you would talk through. Use the Technical deep dives for follow-up mechanics, Practice to test yourself before reopening the walkthrough, and the Quick review the night before the interview.
Next: build the answer in interview order.
Start the walkthroughDesign walkthrough
Follow the reasoning from discovery to delivery.
1. Restate the throughput prompt as a recovery problem
The prompt sounds simple: classify 100 million records every night before 6:00 a.m. In the room, three people want different things at once. The business owner says, "We just need classifications ready by morning." The data platform lead says, "Only if it doesn't break the warehouse." The on-call engineer says, "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.
So restate the target before drawing anything: "Complete a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule." Lead with that sentence as written. Interviewers use it as a checkpoint, because it tells them whether you are solving the business problem or only the throughput problem.
The source also gives a longer, technology-neutral opening that does the same work:
"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."
Compare a weak opening with a corrected one. The weak version names tools: "We should build a batch classifier with a fast inference service and a scheduler." The corrected version names value: "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."
In one sentence, the case is: classify 100 million records overnight, finish within a six-hour window, recover predictably from failures, and know what can be published if the deadline cannot be met. The first design choice is the customer's answer to one question: partial results, or all-or-nothing?
Next, map the stakeholders. Each one relies on the platform for a different job, and naming them settles who owns which decision.
Stakeholders, their pain, and the decision each one owns or does not own.
| 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 |
Read the last column carefully. The business does not decide batch retry semantics. The on-call engineer does not decide whether a stale classification is acceptable. The model owner does not own the downstream SLA (service level agreement: the promise to the customer, usually with penalties). 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 the volume and the deadline, then stop. The gap is the test.
Ask first about the constraint that changes the architecture most: 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 to the partial-result question sets the retry strategy, the checkpoint cadence and how much to spend on the last 10% of records.
The first table lists the questions to ask in the room, each with a concrete example of what it is really asking. RPM means requests per minute; providers often cap requests and tokens per minute separately.
Questions to ask the interviewer, with the concrete version and the decision each one drives.
| 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 second table is the fuller map of design axes. It adds the questions about downstream capacity, residency, pre-partitioned data, native batch APIs, ordering and a cost ceiling.
The full set of discovery questions and the design axis each one unlocks.
| 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.? | The 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 does not 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. The 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, and naming it shows you know where the design would break. If one record depends on another record's result, naive parallelism breaks correctness. If a tenant expects strict completion, a degraded mode that skips low-priority work breaks the contract. If the provider's batch API has different semantics from synchronous calls, a naive retry loop can duplicate output. Its turnaround must also fit the deadline. The OpenAI Batch API documented at this review offers a 24-hour completion window, so it cannot 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 it must do it, 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.
In plain terms, the functional requirements are: 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. The table states them as numbered requirements you can trace later.
Functional requirements.
| # | 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 say how well, and under what constraints. Each row below is phrased so a test can pass or fail it. The latency row uses a formula worth writing on the board: required rate = (N_records / T_window) × (1 + h), where h is the headroom fraction.
Non-functional requirements, each stated so it can be tested.
| Constraint | Stated so it can be tested |
|---|---|
| Deadline and latency | Six-hour completion window. Required rate = (N_records / T_window) × (1 + h): 100M records in 6 hours is about 4,630 records/s, or 5,320 with 15% headroom. The budget covers queueing, batching, writeback, validation and reconciliation, not only inference |
| Availability | The pipeline accepts and processes work throughout its window, sized against the tail of large or slow records rather than the mean, because the slowest few percent of records (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 per retried record (5% retries is about 5% more spend; a retry storm can double it), and stragglers keep workers warm, so both are watched as cost lines |
When the answers are partial, 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.
Then fence the MVP (minimum viable product: the smallest version that real users actually use) explicitly. It excludes cross-job optimisation across unrelated workloads, any per-record interactive feedback loop, a training pipeline in the batch path, arbitrary ad hoc queries, and optimal cost in every failure mode. Each extra responsibility makes deadline risk harder to reason about.
Finally, every component should trace to a named requirement. If a box on the whiteboard has no row here, ask why it exists.
Each requirement traced to the design element that satisfies it.
| 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 |
If the interviewer simply asks "What are the requirements?", the source's short answer is: "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 is a queue, a few workers and a model endpoint. That works at average load. It ignores the deadline, the retry rate and the hard last 5% of records, so derive the numbers live instead of reciting them.
The window is 6 × 3,600 = 21,600 seconds. With 100,000,000 records, the base rate is 100,000,000 / 21,600 ≈ 4,630 records per second. That is only the floor. Adding 15% headroom for retries, stragglers and reconciliation gives a planning rate of 4,630 × 1.15 ≈ 5,320 records per second.
Required record rates now and at ten times the volume.
| 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, while growth covers next quarter's larger batch. Mixing them hides both, so state average, peak, growth and headroom separately rather than one point estimate.
Tokens, not records, set the real load. At 250 input plus 20 output tokens, each record costs 270 tokens before retries. Over the run that is 100M × 270 = 27 billion tokens. Check it that way, as records times tokens per record, rather than multiplying a tokens-per-second rate by one hour. At the planning rate the fleet sustains about 5,320 × 270 ≈ 1.43 million tokens per second. Include retries, long-tail records and output variance in the estimate, and let the token figure, not the record count, drive partitioning and component choice.
This is why a provider's tokens-per-second (or tokens-per-minute) quota is often the real ceiling. At about 5,320 records/s packed 64 per request, the illustrative rate is about 83 requests/s, or 4,988 RPM, before retries. Input and output limits must also fit separately: roughly 79.8M input and 6.38M output tokens/minute under the 250-in/20-out assumption. Request packing does not remove token quota. CPU workers can look idle while the run is throttled at the provider. All of these figures are illustrative planning numbers: replace the token assumptions with the customer's measured distribution (p50 and p95 tokens per record), model latency, batch efficiency, provider throttling, sink throughput and hot partitions.
Say the uncertainty out loud. The source's version:
"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, and 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 does not establish that useful inference completed, and billing must follow the provider contract. The 15% headroom reserves capacity; it does not automatically add 15% billed tokens to a hosted run. That is why the cost ceiling belongs inside the rate-limit coordinator's backoff behaviour rather than in a separate finance conversation.
5. Draw the architecture end to end
Start with a 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. This workload does not need an autonomous agent to decide what to do next, because the next task is always "the next partition in the manifest".
Follow one partition through the diagram:
- 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 cannot 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 cannot 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. The planner owns what "this batch" means. The queue coordinates delivery, while a manifest lease epoch records current ownership. Visibility timeouts do not 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. The sink owns what has been published. When two components disagree after a crash, that ownership tells you which one to believe.
The source draws the same system again, split into two planes. The planner, manifest, forecaster and console are control-plane concerns: they coordinate the run. The workers and sink are data-plane concerns: they move records through the model into durable output. The two planes scale and change at different rates, which is why they are drawn apart.
The next two figures zoom into each plane and mark where trust changes. In the control plane, freeze the input snapshot before leasing any work, and send only opaque lease identifiers across the boundary into the queue.
In the data plane, the coordinator owns every grant-or-delay decision and therefore owns backpressure. The external model is untrusted in the operational sense: it can time out, return 429s, or return invalid output, and the worker is written to expect all three.
The component table states what each part owns and, more importantly, how it fails. "Closed" means the component stops the run rather than guess; "degrades" means it keeps working at reduced capacity.
Components, the state each owns, and how each fails.
| # | Component | Responsibility | State owned | Fails how |
|---|---|---|---|---|
| 01 | Job planner | Accepts the nightly run, freezes the input snapshot, and 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, and intervention controls | Human-facing incident and rollout state | Degrades: runbook and pager still work without it |
Now walk the happy path as seven steps, shown in the flow below.
- 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, because 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, and quarantine permanent ones with triage context.
- Reconcile the manifest and publish the completed dataset.
The 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 does not exist.
Three trust boundaries carry the security story. After the planner freezes the snapshot, the run cannot 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 cannot create duplicate classifications.
The MVP is the planner, manifest, queue, worker fleet, checkpointing, idempotent sink and a basic ETA panel. Smarter rebalancing, historical throughput prediction and tenant-aware scheduling come later, and a common mistake is to present 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 cannot prevent that, so the design 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, an idempotent sink and checkpoint-after-write together give an exactly-once effect: one logical result per key. Avoid claiming physical exactly-once execution, because the model may still be called twice for the same record.
The ordering rule is: commit the output, then advance the checkpoint, then acknowledge the queue lease. The table shows why. Each row is a crash at a different point, and in every case the replay is safe.
Where a worker can crash, and why replay stays safe at each point (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 | The record is 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 |
A crash at any point can replay safely, but it may still pay for another model call. Track replay cost as its own number.
The key is business identity plus model version: (job_id, record_id, model_version), never the worker or the attempt. Be ready for "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 applies at every write boundary, not only the sink:
- A duplicate create must not create a second job.
- A duplicate lease renewal must not invalidate the original lease.
- A duplicate result write overwrites the same logical record.
- A duplicate pause or replay request is harmless.
Versioning matters for the same reason. 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, and the worker-loop deep dive describes the required ordering and two tests an implementation must pass. 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.
Start with the basic split. Transient errors are throttling, network failure and a temporary sink outage; retry them with exponential backoff, jitter (a random delay so retries do not arrive in lockstep) and a cap on attempts. Permanent source errors, such as an invalid file under the frozen input contract, go to quarantine with reason and lineage. Malformed model output can be stochastic rather than permanent. Permit the source worker loop's single bounded validation retry, then quarantine or review; never loop until a lucky answer appears. A 429 is a retry; bad JSON goes to quarantine rather than looping forever.
Beyond individual records, every failure falls into one of four policies:
The four failure policies with example triggers.
| 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.
The source rehearses five drills, each as detection, containment, recovery and prevention. Read across a row to see the full response to one failure.
Five failure drills: how each is detected, contained, recovered and prevented.
| 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 |
Across all five drills the response has the same shape: never push harder against a failing dependency. Slow the arrival rate at the coordinator, preserve evidence before repair, and escalate when the deadline is no longer recoverable. A circuit breaker (a switch that stops calling a dependency after repeated failures) halts the failing calls while the pending work stays durable in the queue.
Reconciliation is the last line. It 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 must have exactly one selected validated result or an explicitly permitted terminal failure, with no unknown IDs or 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.
The ownership statement to say in the room: "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 is: 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.
First compute what is still required. Assume, for illustration, that the window opened at midnight. Four hours in, 45 million records are done, an observed rate of 45,000,000 / 14,400 ≈ 3,125 records per second. The remaining 55 million records must finish in 7,200 seconds, which needs about 7,640 records per second: roughly 2.4 times the observed rate and well above the 5,320 plan. That gap tells you whether adding workers can possibly be enough.
The console should answer three questions, not just turn 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 before choosing the lever. It is one of four: compute saturation, a hot partition, provider throttling (quota pressure), or downstream backpressure from the sink. Then choose the smallest intervention that restores schedule confidence:
- Raise concurrency, but 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 must be 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 storage key includes model_version, so two model versions can coexist; their presence alone does not identify which one downstream should use.
- Publish only the subset that meets the correctness and policy bar, if partial publication is allowed.
If throttling is temporary, the coordinator reduces concurrency and keeps the run stable. If it is persistent, or success is impossible, stop taking new leases, checkpoint everything, and page the customer with a recovery plan and the exact incomplete count. Never silently publish a partial dataset.
The figure shows that both branches preserve state. Even the "give up" branch is an orderly stop: no partition is lost, and when work resumes, the idempotent sink absorbs the replays.
The contingency modes are business decisions agreed before launch, each with a named owner. The product owner and operations lead agree them before the first run, not after the first miss:
- 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.
Partial results are publishable only under a partial-acceptance policy the customer defined. Some workloads can publish completed partitions when each unit is independently valid and clearly labelled. Others need all-or-nothing, because downstream cannot handle mixed vintages (records labelled by different runs or models side by side). State which regime applies; if partial, define the exact publish gate and the completeness metadata that travels with the file.
Two more probes arrive in this part of the round. To rebalance a hot partition, detect it early through lag, runtime histograms and queue age, then split it with a deterministic key so the work stays replayable. If it is in flight, move only the unprocessed remainder and record the new ownership in the manifest. To 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 cannot guarantee that 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 would, because they show you have not thought about when the slogan fails.
Four trade-offs and the verdict to lead with.
| 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, which is 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 cannot overload the provider.
The riskiest assumption in the whole design is that the backlog is evenly distributed and model runtime is stable. When the interviewer challenges it, agree rather than defend:
"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.
The scorecard: what each metric proves, how it is calculated, its threshold and its 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 | Does not 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 |
Around those headline metrics, also track predicted versus 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. The headline asks one question: will the batch complete by 6:00 a.m.? It shows the forecast, remaining partitions and the contingency mode. Below it sit the levers that explain the forecast: records per second, tokens per second, retry rate, straggler age, queue depth and sink lag. Below those sit the correctness signals: duplicates, rejected inputs, checkpoint freshness and replayed partitions. A business user sees whether the run is on track, an operator sees which subsystem is slowing it, and an engineer can trace a retry spike to a quota cut or a bad input cohort.
Keep four layers of evaluation distinct: technical health, model quality from sampled evaluation, adoption by downstream teams, and business outcome. A green pipeline says nothing about whether the labels are right.
Recovery needs its own evidence. Test on representative token sizes, and deliberately crash a worker after the sink write but before the acknowledgement. Inject provider quota exhaustion and a sink outage too, and show restart and reconciliation under each. A clean demo run does not prove recovery.
11. Roll out through a load-test ladder
The customer's real question is "when can this be trusted in production?", which is harder than "does it work?". Treat launch as a sequence of controlled reductions in uncertainty, each with a gate and an owner.
The rollout ladder: stage, gate and 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 because a wrong input distribution makes every later estimate wrong: throughput, queue pressure, quota burn and downstream lag. Before launch, also assign the contingency owner and write down the missed-deadline decision.
Carry a risk register with an owner, a mitigation and a trigger for each risk.
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 is blunt: without stable throughput, rehearsed crash recovery and an available contingency owner, do not expand. That sounds conservative until the batch misses one deadline because nobody wanted to say no.
Complete the launch plan with canarying, rollback, migration, training, support and documentation. A slice of the nightly work runs on the new path while the old path stays as the fallback. Rollback stops new work, preserves checkpoints and resumes on the stable path.
Finally, separate reusable value from delivery work. Thresholds, deadlines, model choice and contingency policy are configuration. Warehouse, queue and identity integrations are adapters. Retry, checkpoint and rate-limit wrappers become a common service. Partition orchestration, replay semantics and the push/degrade/stop policy engine are the core product.
Technical deep dives
Examine mechanisms, alternatives, and operational consequences.
The job contract, durable records and API
The question this system answers is recovery under a deadline, so 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; and who approves changes. Store that policy with the job, so an operator under pressure cannot 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. Three records carry all the durable state:
The three durable records, their keys and lifecycles.
| 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_snapshot is an immutable pointer to the exact dataset version. It is 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 given in step 6.
The API surface stays small: create, status, pause and replay-failures, each guarded by authorisation.
The job API and the contract each endpoint keeps.
| Endpoint | Contract |
|---|---|
POST /v1/batch-jobs | Authenticated; validates manifest and model reference. Idempotency key, so a client retry after a timeout does not 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 cannot 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. Reused key returns the same replay outcome, never a second attempt |
Three details in that table are worth being able to defend. Rejecting a reused idempotency key with a different payload follows the IETF idempotency-key draft (section 2.7, now expired) and Stripe's idempotent requests. Returning not-found for a job the caller may not see is allowed by RFC 9110, and the OWASP authorization regression testing cheat sheet notes that distinct 403 and 404 answers leak existence. An ETag (an entity version tag) on pause makes operator actions conditional: two operators pressing pause at once cannot overwrite each other's view of the state.
Leases, commit order and the worker loop
Partition IDs are deterministic and bounded. Queue messages contain only identifiers, and workers fetch the scoped records themselves. When a worker crashes, its 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 smallest implementation to validate is one worker loop. The source draws it as a flowchart rather than listing code.
Walk the loop in order:
queue.lease(job_id)claims a partition, andsource.read(range)reads its records once.chunked(records, 64)splits them into batches of 64.limiter.acquire(tokens)asks for capacity before the call, because admission control belongs before the quota breach, not after it.model.classify_batch(batch)makes the call, andvalidate_output(raw)checks the result at a typed boundary.sink.upsert_many(key=record_id)writes idempotently. In the sketch the key is shown asrecord_idbecausejob_idandmodel_versionare fixed for the whole job; the stored key is still the full triple.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 behave differently on purpose. A TransientError calls queue.retry(backoff=True). A ValidationError retries once without backoff (queue.retry(backoff=False)) and is then re-raised as a data-quality problem, because a second malformed answer suggests the input or prompt is wrong, and waiting longer will not fix that.
Two required tests exercise parts of the loop; they are described here, not shipped as executable tests. The contract test repeats POST /v1/batch-jobs with the same key and confirms one job and one id. The 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 source's assertion is that the distinct record_id count equals the row count.
The sketch deliberately omits multi-worker contention, logging, metrics, tracing, cancellation, authentication, throttling and dead-letter routing. That is acceptable in an interview only when you can name each omission and say where it would go.
Capacity, ETA and cost arithmetic
ETA is remaining work divided by observed effective throughput, adjusted for the straggler tail. An average-rate graph alone hides deadline failure: the fleet can average 5,320 records per second 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 measured 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 source chapter treats cost only qualitatively. The author of the source's "V2 tutorial" closes the gap with a live dollar formula, which the source labels as supplementary perspective rather than chapter content. Here it is worked through:
The supplementary cost formula, step by step.
| 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 |
With an illustrative price of $0.10 per million tokens (not a quoted rate), the run costs 27,000 × $0.10 = $2,700, or $27 per million records, and a 5% retry rate adds about $135.
Which retries cost money matters. 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 and track rejected attempts, completed inference and ambiguous timeouts separately. A retry storm, where failed calls are retried fast enough to trigger more failures, can double the bill. Headroom may cost reserved or idle capacity, while actual retry tokens and straggler compute are measured spend. Do not add 15% token cost merely because capacity was provisioned with that margin. All of this is why the cost ceiling belongs inside the rate-limit coordinator's backoff behaviour, and in the degraded-mode rules, rather than in a separate finance report.
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.
Security, isolation and operations
The most important security control sits outside the model: every worker processes a versioned snapshot that cannot change beneath it. A retry against a mutable table cannot prove what it retried.
Snapshot immutability does three jobs at once. It removes ambiguity during retries. It makes evidence replayable after an incident. And it limits blast radius: a malformed or malicious tenant dataset touches only that tenant's snapshot, not a global table.
Keep raw payloads out of queue metadata. Messages carry only opaque identifiers, snapshot versions, partition keys and lease information, to reduce payload exposure. Identifiers, tenant tags and volume can still reveal business metadata, so queues, retries and dead-letter stores remain tenant-scoped and access-controlled. Avoid full customer payloads in logs for the same reason. Keep input and output encrypted, scope snapshots and credentials per tenant, and restrict the result and checkpoint stores to least privilege. Checkpoint state reveals the shape of business data and partial outputs, so treat it as sensitive too.
Record the model version, code version, prompt or feature-schema version and deployment identity for every run, and log operator actions and model version changes. That is how the team proves which artifact produced which result when a customer asks why today's classification differs from yesterday's.
Rate control has two layers. A per-tenant coordinator prevents one customer from starving the others, while 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.
The source chapter names no external compliance framework, and the V2 author treats that as a gap. Their supplementary answer is to ask which framework applies before claiming compliance:
- With personal data, purpose limitation and data minimisation apply to snapshot and result retention.
- For covered entities and business associates processing electronic protected health information, the audit-control rule of HIPAA (the Health Insurance Portability and Accountability Act, the US health-data law), 45 CFR 164.312(b), applies to the audit trail.
- For the firms and records within their scope, financial record-keeping rules such as SEC (US Securities and Exchange Commission) rule 17a-4 and FINRA 4511, or SOX (the Sarbanes-Oxley Act on financial-reporting controls), apply.
- SOC 2 is a voluntary audit report that customers in any industry may ask for, not an industry rule.
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.
The bank document platform
The document-processing member of this group is an OpenAI-style practice prompt: "A bank processes millions of financial documents and wants to extract structured data using AI." It is the same spine with a different payload. Records become documents, and a label becomes a schema.
The prompt lists the decomposition: ingestion, file validation, document classification, OCR or multimodal extraction, schema-constrained output and confidence scoring, then validation against business rules, human review, correction feedback, audit storage, and reprocessing with model versioning. It asks you to discuss batch versus online processing, idempotency, retry behaviour, data lineage, model versioning and document-format drift.
Map each stage onto the anchor rather than drawing a new system:
Each document-processing stage mapped onto the batch anchor, and what is new.
| 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 |
Partitioning by page count follows from pricing: document extraction services such as Amazon Textract charge per page, so 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 versus online is a per-workflow decision. Bulk backfills and nightly statements are batch, which buys throughput and quota smoothing. A document a customer uploads while waiting needs an online path with its own latency budget. The two paths can share the extraction schema and the typed boundary.
The likely follow-up is "How would you handle a new document format appearing without warning?" Answer in four parts. Detect it: classification confidence drops, and schema-validation and business-rule failure rates rise for one cohort. Contain it: 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, because format drift is a data-quality incident, not a model bug.
Cost pivots: nightly PDFs and embeddings
After a good design, the interviewer's usual pivot is "the nightly bill is too high." Two members of the group are that pivot, and both have the same root: reprocessing what did not change. Whatever shortcut you propose must not weaken correctness, hide permanent failures or erase provenance.
Nightly PDF summarisation is too expensive. Thousands of PDFs are processed nightly and 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?
The nightly PDF summarisation card.
| 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. Its pipeline is shown below.
The hash-and-dedupe step is where the money is saved: an unchanged document takes the "reuse last summary" branch and never reaches a model. The trade-off is that batch optimises throughput rather than interactive latency, so quality is checked by sampling plus strong-model audits instead of running the premium model on everything.
The batch embedding job became too expensive (scenario 13). The nightly embedding bill spikes after a document refresh. Ask whether all documents are re-embedded or only changed content. The usual causes are full re-indexing, duplicate documents, no content hash, or a larger embedding model.
The batch embedding card.
| 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 a single comparison: changed document count against embedded document count. If the two differ, the pipeline is the bill. Prevention is 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. The content hash is the same idea as the immutable snapshot: know exactly what this run is about, and skip what it is not. The sampled audit is the same idea as tail-sized evaluation: prove quality on a sample instead of paying the premium model on everything.
Every strong cost answer follows four verbs in order. Measure, by comparing changed against processed and tracing cost per document. Route, sending the bulk to a cheaper model and the audit sample to the strong one. Bound, with queue budgets, an indexing budget and anomaly alerts. Cache safely, keyed on content hash and model version.
References
SQS visibility timeouts do not guarantee single delivery. OpenAI Batch documents a 24-hour window; Claude limits distinguish requests, input and output quotas. The worker tests below are proposed tests, not executed code in this casebook.
The source fact-checked these references on 27 September 2026. Each line says what it supports in this case.
- 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.
Practice
Attempt the case before revealing the worked reasoning.
Attempt the design on a blank page
Close the walkthrough and design the pipeline for 100 million records before 6 a.m. from nothing. Open with the restatement and the partial-result question, derive the planning rate and token load, draw both planes, explain why a crashed worker cannot create a duplicate, classify the 4 a.m. incident and give a rollout gate. The source offered a separate worksheet for this exercise; it is not imported here. The local worksheet fields below are a prototype addition, and the questions after them are the source's own self-checks and follow-ups, with two authored drills marked as such.
Work through your answer
This local worksheet is a prototype addition. Notes save in this browser. Nothing is submitted or scored.
Check your reasoning
Reveal the self-assessment rubric
This checklist is an authored addition. Assess what you can explain without reopening the walkthrough.
0 of 8 reasoning checks covered.
Check yourself
These are the source's self-check questions. Answer each aloud before opening it.
What is the one-sentence restatement of the prompt?
Complete a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule.
It names the business problem (a usable, trusted batch by morning) rather than the throughput problem, which is why interviewers use it as a checkpoint.
Which clarifying question is protected first when time is short, and why?
Whether partial results have value. It decides the retry strategy, the checkpoint cadence and how much to spend on the last 10% of records.
Derive the planning rate.
100,000,000 / 21,600 s ≈ 4,630 records per second; × 1.15 headroom ≈ 5,320 records per second.
The 21,600 s is the six-hour window, 6 × 3,600.
Why is headroom kept separate from growth factor?
Headroom covers noise inside one batch; growth covers next quarter's larger batch. Mixing them hides both.
That is why the 10x row (1B records, about 53,200 records per second with headroom) is stated separately as a design test.
Where does backpressure live, and what does it do when quota tightens?
In the rate-limit coordinator. It slows leases or per-worker concurrency instead of letting retries stampede the provider.
Why is InferenceResult keyed on job_id + record_id + model_version, not record_id?
So replay is idempotent within a run, and a rerun under a new model cannot silently overwrite the old answer.
When does the checkpoint advance?
Only after the sink write succeeds, which prevents false progress. The lease is acknowledged after that.
Name one trigger for each failure policy.
Fail closed: broken snapshot hash. Degrade: transient sink throttling. Queue: quota reduction. Human intervention: 45% at 4 a.m. with no path to the deadline.
What three questions should the console answer at 4 a.m.?
Can we still finish? Which lever first? What is the blast radius if we keep going?
What changes when the payload is a bank's financial documents?
A schema at the typed boundary, confidence and business-rule checks, a human-review lane, and lineage down to document hash and page.
Partitioning also moves to page-count bands, because extraction is priced per page.
What is the sixty-second line for the nightly PDF bill?
Never reprocess an unchanged document without a reason. Batch buys throughput not latency, so quality is proven by sampling.
What single comparison diagnoses the embedding bill spike?
Changed document count against embedded document count. If the two differ, the pipeline is the bill.
Follow-ups in the order they arrive
The source lists these follow-ups in the order interviewers usually ask them. The last two are authored drills that apply the same mechanisms.
What do you do at 4 a.m. with 45% done?
Identify the bottleneck, then pull the smallest lever: concurrency if there is headroom, split hot partitions, fallback model, or publish the subset that meets the bar. Make the decision explicit; never leave the batch in limbo.
If the deadline is impossible, stop new leases, preserve checkpoints, page the owner and report the exact incomplete count.
How do you rebalance a hot partition?
Detect it through lag, runtime histograms and queue age; split with a deterministic key; move only the unprocessed remainder and record the new ownership in the manifest.
How do you avoid paying twice after a timeout?
Treat the timeout as ambiguous. Use idempotency keys, durable checkpoints and write-side deduplication to protect results, and reconcile provider request or batch status before resubmitting. Sink deduplication does not prevent paying for a second inference call.
When are partial results publishable?
Only under a partial-acceptance policy the customer defined. Label completeness. Use all-or-nothing when downstream cannot handle mixed vintages.
Why is the result keyed by model version too?
So a rerun under a new model does not silently overwrite yesterday's answer, and replay stays meaningful across model changes.
Where does the cost ceiling live?
In the rate-limit coordinator's backoff and the degraded-mode rules, not in a separate finance report.
What if the provider's batch API behaves differently from synchronous calls?
Retries can duplicate output. The idempotent sink absorbs it, and a submission scheduler replaces the naive worker pool.
How does a new document format get handled?
Detect it by confidence and rejection rates per cohort; route that cohort to review; add the format to the classifier and schema; replay only that cohort.
Authored drill: a worker dies after writing 40 of 64 results in a batch, before the checkpoint moves. What does the sink hold after recovery?
The lease expires and another worker replays the batch from the last checkpoint. The 40 records are reprocessed and upserted under the same (job_id, record_id, model_version) keys, so they stay single rows; the other 24 are written for the first time.
The sink holds 64 logical results. Forty records already have committed results. If replay skips them, only the remaining 24 need new inference. If it regenerates the whole batch, up to 64 record outputs are regenerated. The number of API calls depends on packing; it is not necessarily 40. Record both regenerated tokens and repeated requests as replay spend.
Authored drill: at 2 a.m. the provider halves your quota. Which failure policy applies, and what does the system do?
It is the "Queue" policy and drill 2. The coordinator backs off immediately and the circuit breaker stops repeated failing calls, while pending partitions stay durable.
Recovery is smaller batches, rebalancing across the remaining capacity and deferring low-priority partitions. The forecaster recalculates the ETA; if the deadline is no longer reachable, the pre-agreed contingency mode and its owner take over.
Deliver it in fifty minutes
Open with the outcome, then ask the judgement question: if everything cannot be perfect, what matters most: deadline, accuracy, cost or safe replay? That one question prevents you from overbuilding the wrong axis. The source's opening:
"I'll first pin down the batch deadline, correctness tolerance, and failure recovery expectations. Then I'll estimate throughput and identify the bottlenecks that actually threaten the schedule. After that I'll propose a partitioned ingestion and inference pipeline with idempotent writes, monitoring, and a deliberate fallback path if we're behind at 4 a.m."
A fifty-minute plan, with the walkthrough step that supplies each phase.
| Minutes | Phase | Walkthrough step |
|---|---|---|
| 0–5 | Discovery: size, deadline, freshness, quality bar, retry policy, whether partial output is useful | Steps 1 and 2 |
| 5–10 | Estimation: 4,630 and 5,320 rps, tokens per record, where margin is thin | Step 4 |
| 10–18 | Architecture: control plane, manifest, workers, checkpoints, sink | Step 5 |
| 18–25 | Normal run, then a degraded run: worker failure, hot partition, throttling, falling behind | Steps 6 and 7 |
| 25–32 | Trade-offs | Step 9 |
| 32–38 | Security and operations, each control tied to a failure mode | Security deep dive |
| 38–45 | Follow-up drill: 4 a.m., rebalancing, paying twice, partial publish | Step 8 |
| 45–50 | Close in ninety seconds, name the riskiest trade-off, specify the first rollout gate | Step 11 |
A technically strong answer that runs out of time before the trade-offs or the failure drill still scores as a weak interview. Watch the clock at minute 25.
The source grades answers in three tiers. The weak answer builds a batch classifier with an inference service and a scheduler and runs it nightly; it names tools instead of value and says nothing about snapshots, 4 a.m. or replay. The average answer partitions, runs workers with retries, checkpoints and alerts when late; it treats "alert when late" as a recovery plan and never shapes calls against quota. The strong answer freezes a snapshot and balances partitions by processing cost, leases durably, holds backpressure in a coordinator, checkpoints for bounded replay, upserts by record key, and agrees contingency modes before the run is ever late.
The lines that carry the round, as the source gives them:
- "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."
- "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."
Rehearse the spoken answers
The source gives three timed answers. They are written in the first person because they are scripts to speak; read them aloud and time yourself.
Two-minute answer, from the interview guide
"I would first establish whether the six-hour deadline requires a complete dataset or permits an explicitly labelled partial one. I freeze the input and model configuration, partition 100 million records, and process them from durable leases with autoscaled workers behind global and tenant rate limits. Each worker validates the model output and idempotently upserts it before checkpointing or acknowledging. That makes retries safe. At roughly 4,630 records per second baseline, I plan for about 5,320 with headroom and forecast ETA continuously. If we fall behind, I diagnose quota, skew, compute and sink capacity, then apply only a pre-approved fallback. Reconciliation controls publication, and the operations dashboard shows deadline risk, failures and cost."
Two-minute answer, from the answer key
"The prompt sounds like a throughput problem — classify 100 million records every night before 6 a.m. — but the room splits three ways immediately: the business owner wants classifications by morning, the platform lead wants the warehouse intact, and the on-call engineer wants to rerun safely when something fails. That disagreement is the real problem, so I would restate the target as completing a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule. The first question I need answered is whether partial results have value, because that one answer determines retry strategy, checkpointing cadence, and how much money to spend on the last ten percent. On sizing, 100 million records across a six-hour window is about 4,630 records per second, and with fifteen percent headroom for retries and stragglers, roughly 5,320 — and I would size from the tail of large records, not the mean. Architecturally, a planner freezes an immutable snapshot, a manifest splits it into partitions balanced for processing cost rather than row count, a durable queue hands out leases, and a rate-limit coordinator holds backpressure so tightening quota slows leases instead of triggering a retry storm. Checkpoints make recovery bounded and the sink upserts on the record key so replay cannot duplicate. The failure I would rehearse out loud is being 45% complete at 4 a.m., and the answer is that the contingency mode — narrow scope, cheaper model, or partial output with explicit status — was agreed with a named owner before launch."
Ninety-second architecture summary, from the V2 tutorial
"We have a nightly batch that must classify all records before the business deadline, so I would prioritise replayability, clear ownership, and deadline-aware recovery over exotic optimisation. I'd partition the input into deterministic shards, track each shard in a durable manifest, and run workers that call either a provider API or a self-hosted model depending on the cost, latency, and control constraints. Every write would be idempotent, every shard would checkpoint progress, and every retry would be safe to rerun. I'd monitor shard lag, provider throttling, queue age, and downstream sink health so we can detect whether we're on track by the middle of the window. If we're behind at 4 a.m., I'd first identify the bottleneck, then decide whether to split hot partitions, raise concurrency, or switch the remaining work to a fallback model if the quality policy allows it. The main trade-off is between throughput and flexibility: larger batches improve efficiency, but smaller, deterministic units make recovery safer. I'd start rollout with a small representative slice, verify stable throughput and idempotent replay, and only then expand to the full nightly workload."
Calibrate your level
On this design the levels separate on who owns the 4 a.m. decision and how far replay safety reaches, not on raw throughput. Use the "Missing" column to find what your answer would need next.
Level calibration: what each level sounds like and what it is missing.
| Level | Sounds like | Missing |
|---|---|---|
| Senior | Derives 4,630 records a second, plans for 5,320 with 15% headroom and sizes from the tail, not the mean. Freezes the snapshot, leases partitions, upserts on job, record and model version, and advances the checkpoint only after the sink write, so a worker crash is harmless | The 4 a.m. policy and its owner: which contingency mode applies, whether partial output is publishable, and how a quota cut is kept from turning into a retry storm |
| Staff | Asks the partial-result question first and gets the contingency modes agreed with a named owner before launch. Holds backpressure in the rate-limit coordinator with global and per-tenant quotas, and gates rollout on 1% and 10% load tests plus a rehearsed crash after the sink write | What happens as workloads and models change: which parts become shared, how a rerun under a new model stays meaningful, and what stops the nightly bill growing through reprocessing |
| Principal | Makes retry, checkpoint and rate-limit wrappers a common service, and keeps partition orchestration, replay semantics and the push, degrade or stop policy engine as core product. Treats a model upgrade or format drift as a versioned cohort replay, not an overwrite, and makes change detection the first cost lever | Provider versus self-hosting, the cost ceiling and whether downstream can take mixed vintages depend on the customer's quotas, budget and consumers, so they wait for discovery |
Return to the decisions you could not explain.
Review the essentialsQuick review
Recall the decisions, failure responses, and closing answer.
Open with the contract and draw the path
Ask first: "Is 6 a.m. a hard deadline, and can we publish partial results?" Then ask about the token distribution, provider quotas, permanent errors, fallback approval and replay or version requirements. Restate the target as a replayable, cost-controlled batch by deadline with clear recovery decisions when behind schedule.
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. The model classifies or extracts; deterministic orchestration owns the workflow. Checkpoint only after the sink write succeeds.
Numbers to derive, not recite
100M / 21,600 s ≈ 4,630 records/s; +15% headroom ≈ 5,320/s. At 10x (1B records), ≈ 53,200/s with margin. At 270 tokens a record (250 in, 20 out), ≈ 27B tokens per run before retries (100M × 270), and ≈ 1.43M tokens/s at the planning rate. 5% retries ≈ 5% more spend; a 429 rejected up front generally costs nothing. Confirm everything against measured token and latency distributions.
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. Failure policies: fail closed (snapshot hash, model version, checkpoint), degrade, queue, human intervention.
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.
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."
Key takeaways
- The prompt is a throughput problem on the surface and a 4 a.m. recovery decision underneath, so restate it as a replayable, cost-controlled batch by deadline.
- The partial-result question comes first, because it sets retry, checkpointing and the spend on the last ten percent.
- Requirements are split into features and constraints, prioritised must, should, could, and each is traced to a component.
- Sizing starts at 4,630 records per second, plans for 5,320 with headroom, and is driven by the tail and the 270 tokens a record.
- One diagram separates the control plane that coordinates the run from the data plane that moves records, with three trust boundaries.
- Duplicate work is made harmless by keying results on job, record and model version and advancing the checkpoint only after the sink write.
- Workers read immutable snapshots, queues carry opaque identifiers, and every run records its model, code and schema versions.
- The failure policy is decided before launch: fail closed, degrade, queue or human intervention, with five rehearsed drills.
- The 4 a.m. answer finds the bottleneck, pulls the smallest lever, and uses a contingency mode that already had an owner.
- Four trade-offs are defended with a verdict first, and skew is treated as the riskiest assumption.
- The scorecard tracks completion forecast, duplicates, straggler age, retry rate and cost per million records, not "the job finished".
- Rollout climbs from a representative benchmark through 1% and 10% gates to deliberate failure drills.
- The bank document platform is the same spine, with a schema at the typed boundary, a review lane, and format drift treated as a data-quality incident.
- The hour opens with the outcome, spends its middle on failure and trade-offs, and closes on the first rollout gate.
- Both cost pivots are answered with change detection: never reprocess or re-embed what did not change.