Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish
How to design an offline batch inference pipeline (a nightly job that runs an LLM over 10 million rows) in real interview order: GPU-hours, the deadline and the shared prompt prefix as the numbers that matter, an API of files, jobs, custom_ids and results in any order, an explainer on what prefix caching saves, a validator, scheduler, shard queue, GPU workers on spot capacity, per-attempt files and a finalizer built in passes, one job walked through a lost spot node, a row that crashes the engine and a prompt change, a lab on rows in flight, KV memory, cost and the deadline, a lab on shard size, preemption, duplicates and poison rows, evals with golden sets, judges and canary shards, cascades, prompt vs fine-tune, guardrails, and what happens when each part fails.
The 1-minute answer
How this page follows the interview
Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.
New to KV cache, batching and prefill vs decode? Foundations F18 explains them, and Part 22 designs the online version (LLM serving). Batch and stream pipelines in general are F17. Designed from public material only.
Requirements and numbers
Agree the rows, the tokens and the deadline, then size GPU-hours, GPUs for the deadline and cost. Requests per second barely matters here. Change any input: each number comes with the decision it forces.
Functional
- Submit a file (or a table) of rows with a model, a prompt version and a deadline
- See progress, cost so far and whether it's on track
- Get an output file and an error file, matched to rows by custom_id
- Cancel; resubmit only the rows that failed
- Many teams share one GPU budget
Non-functional
- Done by the deadline (hours), not fast per row
- No row lost, none written twice, every failure with a reason
- Lowest cost per row: spot GPUs, big batches
- Survives losing GPUs at any moment
- A new model or prompt is measured before it touches a full job
Out of scope (say it)
Training and fine-tuning runs, online serving (Part 22), streaming inference on events, the internals of the inference engine.
Capacity calculator
Every input is an assumption 🔶: say it out loud. The two tokens/s numbers are the throughput lab's 70B run with the prefix cached; GPU and API prices are round teaching numbers, not quotes ❓. Spot at 50–80% off is Anyscale's range ✅ Anyscale docs; batch APIs at half price is OpenAI's and Anthropic's ✅ docs 2026
- GPU-hours are the bill: rows × (uncached prompt ÷ prefill rate + output ÷ decode rate) ÷ 3,600.
- The deadline sets the GPUs: GPU-hours ÷ (hours × 0.8), keeping 20% for retries and the slowest shard.
- The shared prefix is free after the first time if it's first in the prompt and cached.
Core entities and the API
A job is the unit of work; a shard is the unit of retry; an attempt is what a worker actually did. What they listen for: a file in, 202 and a job id, custom_id on every row, and results in any order.
| Entity | Key fields | Note |
|---|
What a shared prefix saves
Most batch prompts are the same instructions and examples with one row's data at the end. The engine can compute the prefix's KV cache once and reuse it, but only in full blocks and only if the prefix is identical and first. Change the numbers.
How it works
- Block hashes: vLLM hashes each KV block from its own tokens and every token before it, so a block is reused only when the whole prefix up to it matches. ✅ vLLM docs
- Full blocks only: a partly matching block isn't reused; the lab uses 16-token blocks. ✅ vLLM docs
- Same output: caching skips repeated prompt work without changing what the model produces. ✅ vLLM docs
- Hosted batches: Anthropic says cache hits in batches are best-effort, since requests run in any order; a 1-hour cache helps. ✅ Anthropic docs
Anyscale reported its batch costs falling furthest on shared-prefix workloads (80% shared prefix in its Oct 2024 benchmark). A date or row id at the top of the prompt breaks every hit. ✅ Anyscale 2024
High-level design
Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.
Walk one job, box by box
A marketplace tags 10 million product listings with a category and attributes, due by 6 am. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes, including a lost spot node, a row that crashes the engine, and a prompt change.
Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.
What keeps the GPUs full
A demo is a for-loop over rows. These six details are what turns it into a pipeline that's cheap per row.
Data and database choices
Decisions in a database, bytes in a bucket. Jobs, shards, attempts and leases are small and transactional; inputs and outputs are big files written once. Published results get a new version every run.
| Data | Pick | Considered | Why not those |
|---|
The one thing to know: the worker loop
# One GPU worker. Illustrative; names are made up.
engine = load_model(version) # once per node
while not spot_notice():
shard = queue.lease(version) # 60 s lease
if not shard: break
rows = read(shard.input) # prefetched
prompts = [PREFIX + render(r) for r in rows]
out, errs = [], []
for r, o in zip(rows, engine.generate(prompts)):
ok, val = check_schema(o) # retry once
(out if ok else errs).append(row_result(r, val))
path = shard.attempt_path # attempt-k.jsonl
write(path, out + errs) # whole file
queue.commit(shard, path) # conditional;
# 409 = someone wonIllustrative. In Ray Data or Spark the framework runs the loop as tasks; the per-attempt file and the conditional commit are what you add. 🧭
Why per-attempt files
- At-least-once work is a given: a lost node's shard runs again somewhere else. ✅ Anyscale docs
- So output can't be appended as rows finish: the retry would write the first half again. 🧭
- Write one file per attempt, then commit once with a conditional update; a late duplicate gets 409. 🧭
- Readers still dedupe by custom_id: the hosted APIs key every result by it, because order isn't kept. ✅ OpenAI · Anthropic
More database questions
Deep dive: throughput per GPU-dollar and the deadline
Each decode step reads every weight once, whether it serves 8 rows or 358. With no user waiting, you batch until KV memory says stop. The top chart shows output tokens per GPU against rows in flight; the bars show the job's finish time against the deadline. Pick a preset, then change the switches and numbers.
Teal: throughput while rows fit in memory; grey dashed: past the KV limit. Bars: the plan (80% of the deadline, apricot = the 20% kept spare) and the job on the GPUs you can get. Roofline model on H100s, not a benchmark. 🔶
The rules this lab teaches
- Decode is memory-bound: 8 rows in flight share each 70 GB weight read among 8 tokens. Raising it to 358 cuts the job from $4,773 to $1,581 here. 🧭
- KV memory is the cap: each 1,260-token row holds ~0.2 GB on the 70B; a 60K-token row holds ~10 GB, so only 7 fit. ✅ Llama 3 shapes
- Short answers mean prefill dominates: caching an 800-token shared prefix takes the job from 527 to 209 GPU-hours. 🔶
- The smallest model that passes wins: the 8B is ~7× cheaper per row than the 70B. Prove it on the golden set first. 🧭
Real numbers to quote
Anyscale (vendor benchmark, Oct 2024): self-hosted Llama 3.1 8B batch was 2.9× cheaper than Bedrock and 2.2× cheaper than GPT-4o mini's batch price; with an 80% shared prefix, 6.1× and 4.8×. ✅ Anyscale 2024
Their sizing method: measure one GPU's tokens/s on a sample, divide total tokens by the time you have, add 10–20% buffer. ✅ Anyscale docs
Scale people run: Scribd processed over 400 billion tokens with batch inference on Databricks; First American extracts data from a million+ files a day. ✅ Databricks Oct 2024
Deep dive: evals, rollouts, cost and guardrails
A batch job fails quietly: ten million wrong labels look exactly like ten million right ones, and they land all at once. Ship a new model or prompt like a data migration, measure it before the full run, and keep the cost per row honest.
The release ladder
A cascade: small model first
The small model answers every row; rows it's unsure about (low confidence, failed schema, a scorer's flag) go to the big one. FrugalGPT reported matching GPT-4 at up to 98% lower cost this way on its benchmarks. Prices are the throughput lab's on-demand 8B and 70B runs, rounded; accuracies are made up ✅ FrugalGPT 2023
Judges for batch outputs: useful, with limits
Prompt, fine-tune or a bigger model?
Tick what's true for the job.
Cost and latency per row
- Hosted batch is half price: OpenAI's and Anthropic's batch APIs cost 50% of their synchronous ones, within 24 hours. ✅ docs 2026
- Cache the shared prefix; keep prompts and outputs short (max_tokens per row). ✅ vLLM docs
- Route to the cheapest model that passes; cascade the rest. ✅ FrugalGPT 2023
- Fill every GPU: big batches, spot, the online fleet's night trough. 🧭
- Count wasted attempts in cost per row; they're real GPU-hours. 🧭
Guardrails, in layers
- In: PII redaction and data policy at validation; token limits; which data may go to which model. 🧭
- Out: JSON schema checks per row; refusals and empty answers counted as errors, not quiet defaults. 🧭
- Text shown to people: a safety classifier on generated text (Llama Guard-style). ✅ Inan et al. 2023
- Publish: versioned outputs, a canary diff, and a human-reviewed sample before customer-facing labels go live. 🧭
Regression tests for prompts
- Golden set in CI: every prompt or model change runs it; a slice that drops fails the build. 🧭
- Pinned cases: every bad row found in production becomes a test row with its expected output. 🧭
- Diff against the current version, not just against labels: big label churn is a warning even when accuracy holds. 🧭
- Hands-on checks too: OpenAI's May 2025 rollback came after offline evals and A/B tests looked fine. ✅ OpenAI May 2025
A job's lifecycle
Every job moves through a small state machine, close to the hosted batch APIs' own statuses. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.
Edge cases interviewers love
Failure, monitoring and recovery
A batch pipeline fails loudly (the job misses its deadline) and quietly (rows lost, written twice, or wrong). The quiet ones matter more. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.
Tracing it back: a healthy shard vs a poisoned one
Every span carries job, shard, attempt, worker and model version. Times are seconds from the lease. In the bad trace one huge row crashes the engine twice before the shard is split and the row cornered.
How one failure becomes three
What you'd alert on (SLOs)
| Signal | Target | Alert |
|---|
Incident playbook
The toolkit
Name the technique, then say where it goes in this design.
Making it fast, and who owns what
A job's time is GPU-hours ÷ GPUs; the fixed costs around it (validation, getting nodes, loading weights) matter only when they repeat. Bars are sizing estimates, not measured figures.
| Team | Owns | Paged when… |
|---|
Senior follow-ups beyond the happy path
Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.
Practice ladder
Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.
Sources
- Batch API, OpenAI API docs (checked Oct 2026)
- Batch processing (Message Batches API), Anthropic docs (checked Oct 2026)
- Automatic prefix caching, vLLM design docs (checked Oct 2026)
- Batch LLM inference with Ray Data, vLLM examples (v0.32.0, checked Oct 2026)
- Cost and performance for Ray Data LLM batch inference, Anyscale docs (checked Oct 2026)
- Anyscale batch LLM inference announcement, Anyscale (1 Oct 2024; vendor benchmark)
- Introducing simple, fast and scalable batch LLM inference on Mosaic AI Model Serving, Databricks (22 Oct 2024)
- Spot Instance interruption notices, AWS EC2 docs (checked Oct 2026)
- Introducing Fast Model Loader in SageMaker Inference, part 1, AWS Machine Learning blog (2 Dec 2024)
- A higher order estimate of the optimum checkpoint interval for restart dumps, J. T. Daly, Future Generation Computer Systems 22 (2006)
- A first order approximation to the optimum checkpoint interval, J. W. Young, Communications of the ACM (Sep 1974)
- Efficient Memory Management for Large Language Model Serving with PagedAttention, Kwon et al., SOSP (2023)
- The Llama 3 Herd of Models, Meta (Jul 2024)
- NVIDIA H100 Tensor Core GPU specifications (checked Oct 2026)
- Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena, Zheng et al., NeurIPS (2023)
- FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance, Chen, Zaharia and Zou (May 2023)
- Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations, Inan et al. (Dec 2023)
- Expanding on what we missed with sycophancy, OpenAI (2 May 2025)
- Design an LLM inference API, techinterview.org (third party, used to cross-check interview expectations)
Checked October 2026. Batch API behaviour comes from OpenAI's batch guide (24-hour window, 50% off, 50,000 requests and 200 MB per file, statuses, expiry, 30-day output retention) and Anthropic's batch processing docs (100,000 requests or 256 MB, most batches under an hour, results for 29 days, best-effort cache hits). Engine behaviour comes from vLLM's prefix-caching design doc and its Ray Data batch example. Cost and sizing come from Anyscale's docs (spot 50–80% cheaper, a sizing method) and its Oct 2024 benchmark post, which is a vendor's own comparison. Databricks' Oct 2024 post gives customer scale (Scribd, First American). Spot behaviour is AWS's interruption-notice doc; model load time is AWS's Dec 2024 Fast Model Loader post. Shard sizing uses Young's 1974 rule as stated in Daly's 2006 paper, whose restart formula drives the shards lab. Judge limits are from Zheng et al. (2023); cascades from FrugalGPT (2023). The throughput lab is a roofline on NVIDIA's H100 datasheet and Llama 3's shapes: real runs are usually slower, so measure. No third-party prep page covered this exact question; techinterview.org's LLM inference API page (third party) was used only to cross-check what interviewers press on. Nothing here comes from any employer's internal systems.
System Design Mastermind · AI / ML systems
Series homeAll of AI / ML systems
8 published · 1 comingLLM and ML systems, where interviews are heading.
LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes
Chat API (auth, token limits, history, safety, SSE with resumable event ids) → router picks model (easy turns to a small one), version (registry canary split) and a replica with the prefix cached → vLLM-style engines batch continuously up to the time-per-token target. Admit by priority because GPUs take minutes to add; ship every model change through evals, shadow and canary, with rollback by one number.
RAG assistant over company docs system design: retrieval, permissions and answers you can trust
Ingestion (change events + full sync → parse → chunk with a context line → embed only changed chunks) fills a versioned index of keywords, vectors and allowed principals. Serving rewrites the question, runs hybrid search with the permission filter inside it, reranks 150 → 8, answers only from numbered sources, checks grounding and re-checks cited docs. A golden set gates every change.
AI agent platform system design: tools, durable runs, approvals and agents you can trust
A durable orchestrator runs each agent as workflow code: pin the version, call the model through a caching gateway, record every step so crashes resume. The model only proposes tool calls; a tool gateway validates, authorizes with the user's own token, adds idempotency keys and parks irreversible steps for approval. Budgets stop runaways; end-state evals with k tries gate every release.
Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish
Validate the file, split it into ~20-minute shards, lease them to GPU workers on spot that load the model once and run hundreds of rows at a time with the shared prompt cached. Each attempt writes its own file; one conditional commit per shard makes output exactly-once. Golden set and canary shard gate every new version.
Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a day
Hash at upload against known-bad lists, score every policy with small classifiers in ~50 ms, two lines per policy: remove above, allow below, and the band between goes to an LLM that reads the policy, then a review queue ordered by severity × reach × likelihood. Every decision logged with a reason, appealable, and gated by golden set → shadow → canary.
Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests
Several sources (two-tower ANN search, like-your-likes, trending, a fresh pool) retrieve a few thousand items; a light ranker keeps a few hundred; a heavy multi-task ranker predicts finish, like, share and skip; a value model and re-rank add diversity, in ~200 ms. Events stream back to features in seconds and to incremental training in minutes; models ship via interleaving and A/B tests.
LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rollouts
Every product calls an AI gateway: versioned config, input guards (PII mask, a small injection classifier, an LLM judge only when unsure), output guards on streamed chunks, a trace per request. Off the path: sampled traces judged online, people calibrating the judges, failures turned into regression tests, and every change gated by a paired eval with error bars, then shadow, canary and A/B.
AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals
Three shapes, one backend: a small self-served Tab model per keystroke; an agent loop with a context engine (grep plus an optional index), a cached prompt to a frontier model, text-anchored edits or a fast apply model, permissions and an OS sandbox; and background agents in a container per task that open a PR. An eval harness gates every change on pass^k.