All posts
System Design Mastermind · Part 31
  • System design
  • Interview prep
  • AI/ML systems
  • LLM inference
  • Batch processing

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.

26 Oct 2026 · 34 min read · interactive

Share

The 1-minute answer

Offline batch inference runs a model over millions of rows where nobody is waiting: tag a catalogue overnight, score last month's tickets, grade 50,000 answers with a judge. The goal flips from latency to cost per row under a deadline. A team uploads a file of rows, each with a custom_id, and gets a job id at once. A validator checks every line, counts tokens and estimates cost before any GPU is booked. A scheduler splits the job into shards of ~20 minutes of work and asks for GPU-hours ÷ hours left GPUs, spot first. Each GPU worker loads the model once and leases shard after shard, running hundreds of rows at once (memory, not latency, is the cap) with the shared instructions cached as a prefix. Each attempt writes its own file and a conditional commit picks exactly one per shard, so retries after preemption never lose or duplicate rows; a row that always fails becomes an error record, not a dead shard. A finalizer writes a manifest and checks the counts add up. Every model or prompt change runs a golden set and a canary shard against the current version first, and results are published as a new version, never overwritten.

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.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

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

Three rules for this estimate
  1. GPU-hours are the bill: rows × (uncached prompt ÷ prefill rate + output ÷ decode rate) ÷ 3,600.
  2. The deadline sets the GPUs: GPU-hours ÷ (hours × 0.8), keeping 20% for retries and the slowest shard.
  3. The shared prefix is free after the first time if it's first in the prompt and cached.
They'll push on thisAnswer out loud, then open.

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.

EntityKey fieldsNote
Request
Response

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

They'll push on thisAnswer out loud, then open.

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.

They'll push on thisAnswer out loud, then open.

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.

On the wire

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.

    DataPickConsideredWhy 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 won

    Illustrative. 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

    1. At-least-once work is a given: a lost node's shard runs again somewhere else. ✅ Anyscale docs
    2. So output can't be appended as rows finish: the retry would write the first half again. 🧭
    3. Write one file per attempt, then commit once with a conditional update; a late duplicate gets 409. 🧭
    4. Readers still dedupe by custom_id: the hosted APIs key every result by it, because order isn't kept. ✅ OpenAI · Anthropic

    More database questions

    They'll push on thisAnswer out loud, then open.

    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

    1. 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. 🧭
    2. 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
    3. Short answers mean prefill dominates: caching an 800-token shared prefix takes the job from 527 to 209 GPU-hours. 🔶
    4. 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

    They'll push on thisAnswer out loud, then open.

    Deep dive: shards, preemption and poison rows

    Spot GPUs are cheap because they can vanish (with two minutes' notice on AWS). A shard that's cut short restarts from zero, so its size is a trade: too long and preemptions redo hours; too short and overhead eats the GPU. The curve is Daly's restart formula; the dot is your shard. Pick a preset, then change the switches and numbers.

    Useful work ÷ wall time = τ ÷ [M e^(R/M) (e^((τ+δ)/M) − 1)], with τ the shard length, δ its overhead, R the restart time and M the mean time between preemptions. Dashed teal: Young's √(2δM). Preemptions as a steady random rate is a teaching assumption. ✅ Daly 2006

    Three rules, in order

    1. Size shards by Young's rule: √(2 × overhead × mean time between preemptions); 20 s and 8 hours gives ~18 minutes. ✅ Young 1974 via Daly
    2. Make the commit the only thing that counts: per-attempt files, a conditional commit, dedupe by custom_id. 🧭
    3. Never let one row fail a shard: catch per row; bisect a crash; cap attempts and dead-letter. 🧭

    Numbers to quote

    AWS sends a spot interruption notice two minutes before it stops or terminates the instance, and suggests checking for it every 5 seconds. ✅ AWS docs

    Restart cost: downloading and loading Llama 3.1 70B took 127 s + 138 s with vLLM in AWS's test (Dec 2024): that's R in the formula, every time a node is replaced. ✅ AWS Dec 2024

    Ray Data retries failed tasks automatically, and smaller, well-partitioned blocks give finer-grained recovery. ✅ Anyscale docs

    They'll push on thisAnswer out loud, then open.

    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

      1. Hosted batch is half price: OpenAI's and Anthropic's batch APIs cost 50% of their synchronous ones, within 24 hours. ✅ docs 2026
      2. Cache the shared prefix; keep prompts and outputs short (max_tokens per row). ✅ vLLM docs
      3. Route to the cheapest model that passes; cascade the rest. ✅ FrugalGPT 2023
      4. Fill every GPU: big batches, spot, the online fleet's night trough. 🧭
      5. Count wasted attempts in cost per row; they're real GPU-hours. 🧭

      Guardrails, in layers

      1. In: PII redaction and data policy at validation; token limits; which data may go to which model. 🧭
      2. Out: JSON schema checks per row; refusals and empty answers counted as errors, not quiet defaults. 🧭
      3. Text shown to people: a safety classifier on generated text (Llama Guard-style). ✅ Inan et al. 2023
      4. Publish: versioned outputs, a canary diff, and a human-reviewed sample before customer-facing labels go live. 🧭

      Regression tests for prompts

      1. Golden set in CI: every prompt or model change runs it; a slice that drops fails the build. 🧭
      2. Pinned cases: every bad row found in production becomes a test row with its expected output. 🧭
      3. Diff against the current version, not just against labels: big label churn is a warning even when accuracy holds. 🧭
      4. Hands-on checks too: OpenAI's May 2025 rollback came after offline evals and A/B tests looked fine. ✅ OpenAI May 2025
      They'll push on thisAnswer out loud, then open.

      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.

      NormalSomething went wrongGreyed out: not possible from the current state.

      Edge cases interviewers love

      They'll push on thisAnswer out loud, then open.

      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)

      SignalTargetAlert

      Incident playbook

        The toolkit

        Name the technique, then say where it goes in this design.

        They'll push on thisAnswer out loud, then open.

        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.

        TeamOwnsPaged 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

        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 home

        All of AI / ML systems

        8 published · 1 comingLLM and ML systems, where interviews are heading.

        22

        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.

        34 min · interactive Preview
        25

        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.

        34 min · interactive Preview
        28

        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.

        35 min · interactive Preview
        31

        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.

        You're reading this Preview
        34

        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.

        34 min · interactive Preview
        35

        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.

        34 min · interactive Preview
        36

        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.

        33 min · interactive Preview
        37

        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.

        34 min · interactive Preview
        ··

        Feature store and training platform

        Coming next

        More posts