Sub topic 8
Continuous batching for LLM-style workloads
This chapter assumes you know the dynamic batching from the earlier chapters: a queue, a maximum batch size, and a maximum queue delay. It also assumes you know what a Kubernetes replica is and what p50 and p99 latency mean. You don't need to know transformer internals. You do need to know that a language model produces its output one token at a time.
Why request-level batching breaks down for LLMs
Dynamic batching, as built earlier in this tutorial, treats a request as one unit of work. The batch goes in, the model runs once, and all outputs come back together. That fits a classifier or an image model, where every input costs about the same.
An autoregressive model works differently. To produce a reply, the server runs the model in a loop. Each pass of the loop is a decode step, and each step emits one new token for every sequence it is working on. A reply of 5 tokens needs 5 steps. A reply of 500 tokens needs 500.
If you batch whole requests together, the batch lasts as long as its longest reply. Short replies finish early, but their slots in the batch sit idle until the longest reply is done. New requests also cannot join until the whole batch ends. Two costs follow:
- Wasted accelerator capacity. Finished sequences hold slots that do no useful work.
- Added queueing delay. A request that arrives one step after a batch starts waits for the entire batch, which can take hundreds of steps.
Iteration-level scheduling
Continuous batching (also called in-flight batching or iteration-level scheduling) moves the batching decision from the request to the decode step. Before every step, the scheduler does three things:
- It removes sequences that just emitted an end-of-sequence token or hit their length limit.
- It admits waiting requests into the freed slots, if resources allow.
- It runs one decode step for everything currently in the batch.
The batch is therefore a rolling set of sequences. Each sequence can be at a different position in its reply. A new request waits at most one step for a free slot instead of waiting for a whole batch to drain.
A small simulation
The script below compares the two policies by counting decode steps. It ignores prefill cost and per-step time differences, so treat the result as an illustration of the idle-slot effect and not as a benchmark.
from collections import deque
def static_steps(lengths, batch_size):
"""Request-level batching: each batch runs until its longest reply ends."""
total = 0
for i in range(0, len(lengths), batch_size):
total += max(lengths[i:i + batch_size])
return total
def continuous_steps(lengths, batch_size):
"""Iteration-level batching: freed slots are refilled before every step."""
waiting = deque(lengths)
running = []
steps = 0
while waiting or running:
while waiting and len(running) < batch_size:
running.append(waiting.popleft())
steps += 1
running = [r - 1 for r in running if r - 1 > 0]
return steps
lengths = [5, 40, 8, 100, 12, 6, 90, 10] # tokens to generate per request
print("static: ", static_steps(lengths, 4)) # 190
print("continuous:", continuous_steps(lengths, 4)) # 104The same eight requests need 190 steps with fixed batches and 104 with continuous batching. The remaining 104 is close to the length of the longest request (100), plus a small tail. That is the best any policy can do here, because one sequence cannot finish faster than its own token count.
What limits the batch: the KV cache
In the simulation, the batch size is a number you choose. In a real server, memory sets the limit. During decoding, the model keeps a key-value cache (KV cache) for every active sequence. It stores the attention state for all earlier tokens, so the model does not recompute them at each step. The cache grows by one token's worth of state per step per sequence. Its total size is roughly:
active sequences × tokens per sequence × bytes of state per token
Two consequences matter for operations:
- The effective batch size depends on sequence length. The same GPU can hold many short conversations or a few long ones. A fixed
max_batch_sizefrom the earlier chapters is not enough to express this limit. - Memory fragmentation wastes capacity. If the server reserves a maximum-length block for every sequence, most of that memory goes unused. Servers such as vLLM store the cache in small fixed-size blocks (the technique is called PagedAttention) and allocate blocks as sequences grow. That lets many more sequences fit.
When the cache fills up and a running sequence needs another block, the scheduler must act. It can pause a sequence, evict its cache and recompute it later (preemption), or refuse new admissions. Preemption keeps the server alive but raises latency for the affected requests.
Prefill and decode
A request has two phases with different costs:
- Prefill processes the whole prompt in one pass. It is compute-heavy and its time grows with prompt length.
- Decode produces one token per step. It is dominated by memory reads, which is why batching many sequences into a step is efficient.
Because the two phases share the same GPU, a long prompt that arrives mid-stream can stall every running sequence for the length of its prefill. Users see this as a pause in token streaming. Chunked prefill splits a long prompt into pieces and mixes each piece with decode work, so streaming continues. The trade-off is that the new request's first token arrives a little later.
Parameters you tune
The knobs differ from the two you used in earlier chapters. The names below are from vLLM. Other engines such as TensorRT-LLM and Hugging Face TGI expose equivalents under different names.
| Setting | What it limits | Effect of raising it |
|---|---|---|
| `--max-num-seqs` | Sequences running in one step | More throughput, higher time per token, more KV cache needed |
| `--max-num-batched-tokens` | Tokens processed per step (prompt chunks plus decode tokens) | Faster prefill and higher throughput, longer stalls for running sequences |
| `--gpu-memory-utilization` | Share of GPU memory the server may claim | More room for the KV cache, less headroom for other processes |
| `--enable-chunked-prefill` | Whether prompts are split across steps | Smoother streaming, slightly slower first token |
A launch command combining them looks like this:
vllm serve my-model \
--max-num-seqs 64 \
--max-num-batched-tokens 8192 \
--gpu-memory-utilization 0.90 \
--enable-chunked-prefillFlag defaults change between releases, so check the documentation for the version you deploy.
Latency metrics change too
A single "request latency" number hides what users feel. For LLM serving, track two:
- Time to first token (TTFT): from request arrival to the first streamed token. It includes queueing and prefill.
- Time per output token (TPOT), also called inter-token latency: the gap between consecutive tokens. It rises as the running batch grows.
Total latency is approximately TTFT plus TPOT times the number of output tokens. Set separate objectives for TTFT and TPOT, and look at their p99 values. A chat product needs a low TTFT and a TPOT that keeps up with reading speed. A batch summarization job may care about neither.
Scaling on the right signals
The max_queue_delay from earlier chapters no longer describes the queue well, because a request can wait for a slot or for cache space. Signals that work for LLM replicas:
- Waiting requests per replica. If requests queue for admission, the replica is saturated. This is the closest analogue of the queue depth metric from the autoscaling chapter.
- KV cache usage. A replica at 95% cache usage is about to preempt or reject. Scale out before it gets there.
- Running sequences compared with
max-num-seqs. This is a concurrency signal in the same sense as Little's law.
Plain GPU utilization is a poor signal here. A GPU can report high utilization while the server still has headroom, and it can sit at the cache limit while compute looks moderate. Servers export the useful counts as Prometheus metrics, for example vllm:num_requests_waiting, vllm:num_requests_running and a KV cache usage gauge. Exact names vary by version.
Scale-out is also slower than for small models. A replica must load tens of gigabytes of weights before it can serve, so cold start can take minutes. Use a longer scale-up lead (a lower target such as 2 waiting requests per pod, not 4), keep a higher minReplicas, and keep the scale-down stabilization window from the earlier chapter.
Decision criteria
Use continuous batching whenever the model generates variable-length output token by token. Chat, code completion, and summarization all qualify. Keep ordinary dynamic batching for fixed-cost models such as embedding encoders, rerankers, and classifiers, because they have no per-token loop to schedule around. Many embedding services run well with the simpler max_queue_delay approach.
Common errors
- Raising
max-num-seqswithout checking cache. The server admits more sequences than memory supports, then preempts constantly. Watch the preemption count. - Tuning only for throughput. Tokens per second rises with batch size, but so does TPOT. Check p99 TPOT after every change.
- Ignoring prompt length. A few very long prompts can dominate prefill time. Cap the maximum context length at the gateway.
- Scaling on CPU or GPU utilization. It lags the real saturation signal, so replicas arrive late.
Exercise
A server has 2 slots (batch size 2) and receives four requests that need 2, 10, 3 and 3 output tokens, in that order. Count the decode steps needed with request-level batching and with continuous batching. Why can continuous batching not finish in fewer than 10 steps here?
Show answer
Request-level batching runs two batches: (2, 10) takes 10 steps and (3, 3) takes 3 steps, so 13 steps in total. Continuous batching starts with the 2 and the 10. After step 2 the short request leaves and a 3 enters. After step 5 that one leaves and the second 3 enters. It finishes at step 8. The 10-token request finishes at step 10, so the total is 10 steps. It cannot go below 10 because the longest request needs 10 sequential decode steps no matter how the others are scheduled.