Batching, simulated
The system design question candidates most often report from Anthropic: callers send one request at a time and wait for its answer, while the model would much rather take them a hundred at a time. Here the givens are fixed — up to 100 requests per batch, 100 ms per batch however many it holds, about 300 characters per request — and everything else is a knob. Pick a batching policy, add GPUs, push the load past capacity, crash a GPU mid-batch, slip in a request that breaks every batch it joins, and watch latency, batch fill and GPU time respond.
For the algorithm rounds there are graphs, dynamic programming and P vs NP.
The question
one model · 100 ms per batch · callers that waitDesign a service that serves inference requests for a model. Each caller sends one request and waits for the answer to that request. The service groups pending requests into batches and runs each batch through the model, which finishes a batch in 100 ms. Cover the path from caller to model and back, what closes a batch, scaling, overload and failures.
As candidates report it (Exponent, PracHub). The 100 ms is often the only number given; the cap of 100 per batch and the ~300-character requests are this page's assumptions. In the room, ask for them or state your own.
The lab
discrete-event simulation · 100 per batch · 100 ms per batch · slowed down so you can watchEach square is a request. Requests queue in the middle, leave together when the policy says so, ride a GPU for 100 ms and fly back to their callers. Time is simulated exactly and only shown slowed down, so the numbers under the picture are what the design really does. Start with a scenario, then change anything.
- next batch
- behind it
- will miss the target
- caller gave up
- retried
- poison
- on a GPU
latency of each batch · last 20 s
queued requests · last 20 s
batch sizes · last 200 batches
batching
traffic
GPUs & queues
overload
failures
Each request gets 3 attempts. Use poison and crash a GPU under the picture.
the givens
Latency against load
5 policies · 16 loads · 12 s simulated eachA run of the lab is one point. This runs every policy at 16 loads, from a trickle to 120% of capacity (GPUs × 100 per 100 ms), with the GPUs, queues, limits and failures set above, and plots what each one buys. It takes a second or two.
The design
what to say, in roughly the order to say itbefore you draw anything
- Is 100 ms model compute only, or end to end? (Time to first token, or the full answer?)
- Is there a cap on batch size, and does 100 ms hold up to the cap — for long prompts too?
- One model, or several that cannot share a batch?
- Requests per second at peak, not on average, and the latency target: p50 or p99?
- Do callers hold a connection and wait (synchronous), and with what timeout? Is the answer streamed?
- Does order matter? Tenants who must not starve each other? Requests that are safe to retry?
the numbers
- per GPU
- 100 per 100 ms = 1,000 /s — only with every batch full. A batch of 10 costs the same 100 ms, so it caps you at 100 /s.
- fleet
- GPUs = peak ÷ (1,000 × target utilization).
- bytes
- 300 B × 1,000 /s = 300 KB/s per GPU: the network is never the problem. Queue memory is tiny too — 100,000 waiting requests is 30 MB.
- tokens
- ~4 characters per token: ~75 per request, ~7,500 per full batch — the number to ask about if prompts vary.
- Little's law
- requests in the system = arrival rate × time each spends. At 1,000 /s and 150 ms, 150 are in flight or waiting at any moment.
the latency budget
Split the target before choosing anything. With a p99 of 300 ms:
- network, each way ~10
- queueing for a GPU
- batch forming, ≤ W
- model 100
- margin
The model's 100 ms is fixed. Network both ways is ~10–20 ms in one region. What is left is for waiting: for a batch to form (at most W) and for a free GPU (queueing). That is where W comes from — and why the target must be p99, not average, under bursts.
what closes a batch
| policy | low load | high load |
|---|---|---|
| no batching | 100 ms | collapses past 10 /s per GPU |
| wait for 100 | waits 99 ÷ rate — at 3 /s, half a minute | full batches, best GPU time |
| 100 or W ms | waits ≤ W | fills before W fires; the standard answer |
| when a GPU frees | lowest latency | part-full batches hold GPUs for the full 100 ms; tails grow on several GPUs |
| every T ms | waits ≤ T | ignores full batches and idle GPUs; T = 30 ms caps a GPU at 833 /s |
Launch at 100 or when the oldest has waited W — what TensorFlow Serving calls max_batch_size and batch_timeout_micros, and Triton max_queue_delay_microseconds. Pick W from the budget. On a fleet you own, W near 0 is free latency at low load; where GPU time is billed, or at high load on several GPUs, a W of tens of ms fills batches and lowers both cost and tail latency (lab scenarios 4 and 5).
form the batch when a GPU is free
Don't seal a batch and then queue it behind a busy GPU: everything that arrives while it waits should ride along. Let GPUs pull — a free GPU asks for work, and the batcher hands it up to 100 of the oldest requests right then. Under load this makes batches fill themselves: the queue that builds during one 100 ms batch is the next batch. The C++ below does exactly this: each GPU thread calls next_batch() when it is free.
more out of each GPU
- Prepare batch n + 1 while batch n runs — tokenize, copy to pinned memory, start the transfer — so the GPU never waits on the CPU. The 100 ms is only all GPU if this overlaps.
- Variable lengths mean padding to the longest request in the batch: bucket by length, or cap a batch by tokens instead of by count.
what to watch
Queue depth and the age of the oldest request; time spent forming batches; the batch fill histogram; GPU busy time; p50 and p99, end to end and per stage; 429s, sheds, timeouts and model errors; answers per second; GPU-seconds per 1,000 answers. The lab shows most of them live.
one queue, or one per GPU
One queue the GPUs pull from sees all the traffic, so batches fill K times faster, no GPU sits idle while another has a backlog, and limits live in one place. The price is a component in the path: a batcher service in front of the GPUs, which needs its own redundancy and gets partitioned (by model, then by shard) as it grows.
A queue inside each model server behind a load balancer is simpler — no extra hop, it is what a dynamic batcher in a model server gives you — but each queue sees 1/K of the traffic. At low load batches leave emptier and cost more GPU time; near capacity the unlucky queues back up. Balance on outstanding work (least loaded, or best of two random choices), not round robin, and expect a crash to take that GPU's queue with it. In the lab, 4 GPUs at 90% load: p99 ~130 ms with one queue, ~200 ms with four.
getting each answer home
- Give every request an id. The front end that holds the caller's connection keeps a promise per id; the batch carries (id, input) pairs, the model returns outputs in input order, and result i completes promise i.
- Across machines the batch also carries a reply address — the front end that owns the connection — or the batcher sits in the request path and answers on the same RPC.
- Release the caller on every path: success, model error, timeout, disconnect. A caller that disconnects is cancelled: taken out of the queue if it hasn't launched, its result dropped if it has.
- Propagate the deadline with the request, and never launch a request that cannot finish before it (now + 100 ms > deadline).
overload
- Capacity is fixed at GPUs × 1,000 /s at best. Above it the queue grows by the excess every second, forever, and every caller's wait with it (scenario 7).
- Bound the queue — by length or by the age of its oldest request — and refuse at the door with 429 or 503 and
Retry-After. A refusal in a millisecond beats a timeout after seconds. Size the limit as what drains within the budget: (budget − 100 ms) × capacity. - Shed what nobody waits for. Without it the GPUs spend overload answering callers who already left, and useful throughput falls to zero (scenario 9).
- Autoscale on queue wait and batch fill, not CPU, and keep headroom for the peak: bursts that average 60% load still overrun (scenario 10).
- Priorities and tenants get separate queues and a fair share of each batch; drop the lowest priority first. Clients retry with exponential backoff, jitter and a retry budget, or retries become the overload.
failures
- A GPU dies mid-batch. The worker holds a lease on its batch; when the connection drops or the lease runs out (a few × 100 ms), the batch goes back to the front of the queue. Inference is side-effect free, so retrying is safe; keep request ids to drop a duplicate answer from a worker that was only slow (scenario 11).
- A request that fails every batch it joins. Retrying the whole batch fails all its neighbours with it. Split the failed batch in half and retry the halves: the bad request is alone after ~log₂ 100 ≈ 7 rounds and only its caller gets the error (scenario 12; the C++ needs 13 model calls).
- Transient errors. A small retry budget, then fail fast; take a GPU that keeps failing out of rotation.
follow-ups to expect
- Batch time depends on what's in it. Schedule by a token budget, group similar lengths, estimate each request's cost.
- One long answer holds the whole batch. Continuous batching: requests join and leave the running batch between decoding steps (Orca, vLLM), so short ones return early. Or separate queues by expected length, and a max_tokens.
- Several models. They cannot share a batch: a queue and batcher per model, GPUs placed by demand, cold models sharing GPUs.
- The 100 ms is end to end. Then nothing is left for waiting: W = 0, in-region callers, and a talk about whether the target is real.
A batcher in C++
one queue · GPU threads pull · 100 or W · bisect on failureAbout a hundred lines of the core: submit() never blocks and returns a future; each GPU thread asks for a batch when it is free; a full queue refuses at once; expired requests are answered without spending GPU time; a failed batch is split until the request that breaks it is alone. The model is a stand-in that sleeps 100 ms. The output is real, from g++ 13.
which knob when
| you see | it means | turn |
|---|---|---|
| p99 far above p50 at low load | the policy waits for full batches | add a max wait W |
| batches mostly empty, GPU time high | launching too eagerly | raise W, or use fewer GPUs |
| queue grows steadily, never drains | arrivals above capacity | more GPUs; until then, a queue limit |
| GPUs busy, answers ≈ 0 | serving callers who left | shed expired requests, propagate deadlines |
| one GPU backed up, others idle | per-GPU queues, poor routing | least loaded / best of two, or one shared queue |
| p99 spikes while the average is fine | bursts above capacity | headroom for the peak, autoscale on queue wait |
| bursts of errors around one request | a poison input failing its neighbours | bisect failed batches, cap attempts |
words
- batch fill
- Requests per batch ÷ the cap. With a fixed 100 ms per batch, it is the share of GPU time that does useful work.
- max wait (W)
- How long the oldest request may wait for a batch to fill before it launches anyway.
- late binding
- Choosing a batch's contents when a GPU is ready for it, not before, so late arrivals ride along.
- backpressure
- Telling callers to slow down — a fast refusal, a 429 — instead of queueing without limit.
- load shedding
- Dropping work that can no longer be useful: expired requests, low priorities first.
- goodput
- Answers that reach a caller in time, per second. Under overload it can fall while the GPUs stay busy.
- p99
- The latency 99% of requests beat. The target to design for, because bursts live in the tail.
- continuous batching
- For text generation: changing a running batch between decoding steps so requests join and leave independently.