Continuous batching
Re-form the batch at every decode step: finished sequences leave and queued requests take their slots at once, instead of everyone waiting for the longest member. It's the main reason engines get several-fold more throughput.
Analogy: A static batch is a tour bus that leaves only when full and doesn't return until the last tourist is done; continuous batching is a subway, where people board and leave at every stop.
How it works
- With static batching, the batch runs until its longest member finishes, so short answers leave slots idle.
- New arrivals also wait for the batch to drain, so their TTFT includes someone else's generation.
- Every step, the scheduler drops finished sequences, frees their KV cache and admits waiting requests that fit.
- Decode is bandwidth-bound, so an extra sequence costs little; KV memory is the real limit.
- vLLM, SGLang and TGI do it by default; you only tune max sequences and tokens per step.
Check yourself
Answer to mark it learned; your answers aren't scored.
An internal chat API wraps Hugging Face generate() in FastAPI with fixed batches of 16. Answers range from 20 to 1,500 tokens. nvidia-smi shows the GPU busy, throughput is poor and p95 TTFT is ~6 s. A teammate wants more GPUs. What do you do first?
Go deeper
Full explanation
Continuous batching (also iteration-level or in-flight batching) decides who is in the batch at every forward pass, not once per batch.
With static batching, 8 requests start together and the batch runs until its longest member finishes. LLM output lengths vary wildly: if one answer needs 1,000 tokens and the rest 50, seven slots idle for ~950 steps, and new arrivals wait for the whole batch to drain, so their TTFT includes someone else's generation.
Orca (OSDI 2022) moved scheduling to the granularity of one iteration. Every step, the scheduler:
- removes sequences that hit EOS or
max_tokensand frees their KV cache; - admits waiting requests if there is KV memory for them (their prefill joins this step, often chunked: Prefill vs decode);
- runs one forward pass that emits one token for every running sequence.
Decode is bandwidth-bound, so an extra sequence in a step costs little until compute or memory runs out: a full batch is where throughput comes from. KV memory is the real limit. PagedAttention & vLLM allocates it in small blocks so more sequences fit; when it fills, the scheduler preempts a sequence and recomputes or swaps it back later.
It's the default in vLLM, SGLang, TGI, TensorRT-LLM ("in-flight batching") and LMDeploy. You don't choose it; you tune its caps: max sequences and max tokens per step.
Code Toy simulation: static vs continuous batching
import random
from collections import deque
def static_steps(lengths, batch):
# each batch runs until its LONGEST member finishes; the rest emit padding
return sum(max(lengths[i:i + batch]) for i in range(0, len(lengths), batch))
def continuous_steps(lengths, batch):
queue, running, steps = deque(lengths), [], 0
while queue or running:
while queue and len(running) < batch: # refill free slots every step
running.append(queue.popleft())
running = [r - 1 for r in running if r > 1] # one token each; drop finished
steps += 1
return steps
# Toy model: decode steps only (no prefill, unlimited KV), 32 slots
rng = random.Random(0)
lengths = [rng.choice([30, 80, 150, 300, 600, 1500]) for _ in range(1024)]
s, c, useful = static_steps(lengths, 32), continuous_steps(lengths, 32), sum(lengths)
print(f"static: {s} steps, slot utilization {useful / (s * 32):.0%}") # 48000, 29%
print(f"continuous: {c} steps, slot utilization {useful / (c * 32):.0%}") # 14920, 94%
print(f"speedup: {s / c:.1f}x") # 3.2x
# In vLLM it's built in; you tune the caps, not the algorithm:
# vllm serve $MODEL --max-num-seqs 128 --max-num-batched-tokens 8192Real example
An internal chat API served Llama-3-8B with Hugging Face generate() behind FastAPI, in fixed batches of 16. Answers ranged from 20 to 1,500 tokens, so each batch ran as long as its longest answer while finished rows generated padding. nvidia-smi showed the GPU busy, yet most slots did no useful work, and p95 TTFT hit ~6 s because new requests waited for the batch to drain. Moving the same GPU to vLLM raised throughput several-fold and cut p95 TTFT below 1 s, with no client changes.
Trade-offs +3 · −4
+ You gain
- Several-fold more throughput on the same GPUs: no slot idles waiting for the longest sequence.
- Lower TTFT under load: new requests join at the next step instead of waiting for a batch to drain.
- Server-side only: no client changes, and every major engine ships it on by default.
− You pay
- Per-user TPOT grows with batch size; you must cap concurrency to hold the latency SLO.
- New prefills interfere with running decodes, causing inter-token latency spikes unless prefill is chunked.
- Needs dynamic KV management; under memory pressure, preemption causes sudden latency spikes.
- Batch composition changes every step, so outputs can vary slightly even at temperature 0 unless kernels are batch-invariant.
Use it when
Any online LLM serving with concurrent users. Use an engine that has it (vLLM, SGLang, TensorRT-LLM) instead of wrapping model.generate() in a web server, and tune its caps against your TPOT SLO.
Avoid it when
It buys nothing at batch 1 (single-user local or on-device). If you need bitwise-reproducible outputs, varying batch composition breaks that unless the engine offers a batch-invariant mode.
Numbers to know 4
- Orca: 36.9× throughput over NVIDIA FasterTransformer at the same latency (GPT-3 175B).
- Anyscale benchmark: up to ~23× throughput vs naive static batching (with vLLM), while also lowering p50 latency.
- vLLM (PagedAttention + continuous batching): 2–4× throughput over FasterTransformer and Orca at the same latency.
- Static batch cost = longest sequence × batch size: a 50-token answer next to a 1,000-token one wastes ~95% of its slot.
Common pitfalls 4
- Serving
model.generate()behind a web server with a lock or fixed batches: the GPU looks busy but delivers a fraction of its capacity. - Setting max batch size for peak throughput and blowing the TPOT SLO; derive it from a goodput sweep instead.
- Benchmarking with identical output lengths, which hides the static-batching penalty; use a real length distribution.
- Ignoring KV usage and preemption counters: when they climb, latency spikes before throughput drops.
Interview questions 2
Answer out loud first, then reveal.
Explain continuous batching and why it improves throughput so much.Show answer
Static batching fixes the batch for its whole lifetime, so it runs as long as its longest output while finished slots generate padding and new requests queue outside. Continuous batching re-decides membership every iteration: done sequences leave, waiting ones join. Since decode is bandwidth-bound, extra sequences in a step are nearly free, so keeping slots full turns into throughput, often several times more. The catches are memory and latency: admission is limited by KV cache, so it pairs with paged attention, and bigger batches raise TPOT, so I cap concurrency at the SLO.
p99 inter-token latency spikes whenever someone sends a long document. Why, and what do you do?Show answer
With continuous batching, the new request's prefill runs in the same iteration as everyone's decode, so a 30k-token prefill turns a ~30 ms step into about a second and every stream freezes. First fix: chunked prefill with a tokens-per-step budget, so the document is processed over many steps alongside the decodes. If long prompts are frequent, I'd route them to a separate pool, or disaggregate prefill and decode at larger scale. I'd also watch preemptions: long contexts eat KV and can evict running sequences.