Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Continuous batching | The engine re-forms its batch at every step: finished requests leave, waiting ones join (12.j). |
| Step | One forward pass of the model over the current batch. Each running request gets one new token per decode step. |
| Token budget | The most tokens (prompt pieces plus one per decoding request) the engine will process in one step. |
| Concurrency cap | The most requests allowed in the running batch at once. |
| ITL | Inter-token latency: the time between two streamed tokens. Roughly one step. |
| Preemption | Throwing a running request out of the batch because the KV cache is full; it is recomputed later (17.c). |
| Capacity problem | The fleet is simply too small for the traffic. No setting fixes it. |
1. What is it?#
Module 12 explained what continuous batching is. Inside one engine it happens on its own. The serving system’s job is to set its limits, so that each replica runs batches as large as the latency targets allow, and to know when the limits are not the problem.
Every continuous-batching engine has the same four limits, under different names:
| Limit | vLLM | SGLang | TensorRT-LLM |
|---|---|---|---|
| Concurrency cap | --max-num-seqs | --max-running-requests | max_batch_size |
| Token budget per step | --max-num-batched-tokens | --chunked-prefill-size | max_num_tokens |
| Longest request | --max-model-len | --context-length | max_seq_len |
| Memory for weights + KV cache | --gpu-memory-utilization | --mem-fraction-static | free_gpu_memory_fraction |
This lesson is engine-neutral. For vLLM, the mechanics of the token budget are in 17.b, the memory arithmetic in 17.h, and the full flag-by-flag tuning procedure in 19.d.
2. Why does it matter?#
The four limits decide the two numbers users feel. A bigger batch means more tokens per GPU per second (cheaper), but each step takes longer (slower streaming). A bigger token budget means faster prefill (better time to first token), but any step that carries a big prefill chunk is slow for every streaming user.
And the most common finding when a team “tunes the batch” is that the settings were fine and the fleet was too small. The arithmetic that shows this takes ten minutes. Doing it first saves days of flag-twiddling.
3. Simple analogy#
A bus that never stops moving. Passengers step on and off at every stop (continuous batching).
- The number of seats is the concurrency cap.
- The width of the door is the token budget: how many people can board in one stop. A wide door gets a big group on quickly, but the stop takes longer for everyone already sitting.
- The longest ticket is the maximum request length.
- The size of the bus is the GPU memory you give it.
If the queue at the stop is longer than any bus can carry, adjusting seats and doors does nothing. You need more buses.
4. Tiny example: tuning problem or capacity problem?#
A chat service on Llama-3.1-8B, one H100 per replica. Peak 40 requests per second; prompts average 1,500 tokens (p95 3,000); answers average 400 tokens (p95 600). Target: p95 ITL under 50 ms.
// sizing.go — is it a tuning problem or a capacity problem? One replica, rough physics.
package main
import (
"fmt"
"math"
)
func main() {
// Model: Llama-3.1-8B in BF16 on one H100 (80 GB, 3.35 TB/s).
const (
weightsGB = 16.1
kvPerTokKB = 128.0 // 2 (K,V) × 32 layers × 8 KV heads × 128 dims × 2 bytes = 128 KiB
gpuGB = 80.0
memFraction = 0.92 // vLLM's default gpu_memory_utilization
otherGB = 4.0 // activations, CUDA graphs, workspace (read yours from the log)
bwTBs = 3.35
bwEff = 0.6 // decode reaches ~60% of peak bandwidth in practice
prefillTPS = 30000.0 // prefill tokens/s once compute-bound (measure yours)
)
// Workload: chat.
const (
meanPrompt, p95Prompt = 1500.0, 3000.0
meanOutput, p95Output = 400.0, 600.0
peakRPS = 40.0
itlSLOms = 50.0
)
kvGB := gpuGB*memFraction - weightsGB - otherGB
capTokens := kvGB * 1e9 / (kvPerTokKB * 1024)
memSeqs := math.Floor(capTokens / (p95Prompt + p95Output))
fmt.Printf("KV cache: %.1f GB = %.0fk tokens → %0.f sequences at p95 length\n", kvGB, capTokens/1000, memSeqs)
// Decode step time: read the weights once, plus each sequence's KV cache.
meanCtx := meanPrompt + meanOutput/2
step := func(b float64) float64 {
bytes := weightsGB*1e9 + b*meanCtx*kvPerTokKB*1024
return bytes / (bwTBs * 1e12 * bwEff) * 1000 // ms
}
batch := math.Floor(memSeqs * 0.75) // leave 25% headroom against preemption
fmt.Printf("max_num_seqs %0.f: decode step ≈ %.1f ms (ITL SLO %.0f ms)\n", batch, step(batch), itlSLOms)
// Per-replica request rate r: prefill takes r×meanPrompt/prefillTPS of the GPU's time,
// decode uses the rest at batch/step tokens/s, and must produce r×meanOutput tokens/s.
decodeTPS := batch / (step(batch) / 1000)
r := decodeTPS / (meanOutput + decodeTPS*meanPrompt/prefillTPS)
fmt.Printf("one replica: %.0f decode tok/s → about %.1f requests/s\n", decodeTPS, r)
fmt.Printf("peak %.0f req/s at 70%% target utilization → %.0f replicas\n", peakRPS, math.Ceil(peakRPS/(r*0.7)))
}Output:
KV cache: 53.5 GB = 408k tokens → 113 sequences at p95 length
max_num_seqs 84: decode step ≈ 17.3 ms (ITL SLO 50 ms)
one replica: 4849 decode tok/s → about 7.5 requests/s
peak 40 req/s at 70% target utilization → 8 replicasHow to read it:
- Memory allows 113 worst-case sequences. We cap at 84 to leave room for unlucky mixes of long requests; running at the memory maximum causes preemption storms.
- Latency is comfortable: a 17 ms decode step against a 50 ms target. Real steps are longer (prefill chunks join them, and attention costs grow), but there is room.
- Capacity is the problem. One replica handles about 7.5 requests per second. At 40 per second you need 8 replicas at a 70% target utilization (20.c section 7). No flag changes that.
The program is a first estimate, not a benchmark. Replace bwEff, prefillTPS and otherGB
with numbers from your own startup log and a load test (19.d, 22.g).
5. Technical explanation#
Concurrency cap#
The most sequences in the running batch.
Too low: the GPU runs smaller batches than memory allows; throughput is left behind.
Too high: KV memory runs out mid-flight → preemption; and ITL grows past the SLO.
Set it to: min(memory-allowed concurrency at your p95 request length × ~0.75,
latency-allowed concurrency at your ITL SLO)Compute the first from the startup log (section 6). Find the second by load testing: raise concurrency until p95 ITL reaches the target.
vLLM’s default is high (1,024 on H100- and B200-class GPUs, 17.b), so in practice the cache, not
this cap, decides concurrency unless you set it. Recent vLLM also has --max-num-active-seqs,
which limits only how many requests run at once without shrinking the buffers and CUDA graphs
sized by --max-num-seqs.
Token budget#
The total tokens processed in one step: prefill chunks plus one token per decoding request. This is the main prefill/decode balance knob.
Small (512–2,048):
✓ every step stays short → smooth ITL
✗ a long prompt takes many steps → worse time to first token
Large (8,192–32,768):
✓ fast prefill → good time to first token, high throughput
✗ a step that carries a big chunk is slow → ITL spikes for everyone streamingA starting point: the budget whose prefill fits inside your ITL target.
budget ≈ ITL_target_ms / prefill_ms_per_1k_tokens × 1,000
prefill 30,000 tok/s = 33 ms per 1,000 tokens; ITL target 50 ms → about 1,500 tokensThen measure. vLLM picks 8,192 on an H100 and 16,384 on a B200 by default (17.b), which favours throughput; an interactive service often wants less. Chunked prefill is what makes a small budget possible at all: without it a long prompt could not be split (12.k).
Longest request#
The context ceiling for one request. Set it from your traffic (p99 prompt + p99 output, plus margin), not from the model card.
In a paged engine (12.l) this limit does not shrink the cache: capacity in tokens is the same whatever you set (17.h). What it changes:
- whether the server starts: one full-length request must fit in the cache;
- the worst-case concurrency the startup log prints;
- how long a single request may hold memory, and how big its prefill can be;
- in engines that pre-allocate per-sequence buffers (some TensorRT-LLM configurations), memory is reserved for it. Check your engine.
Memory fraction#
The share of GPU memory the engine may use for weights, activations, CUDA graphs and KV cache. vLLM defaults to 0.92 of total memory (17.h). Raising it adds cache; lowering it leaves room for another process or for a spike. Test with your longest real prompt before raising it: the activation peak during a long prefill is far bigger than during decode.
How they interact#
concurrency cap ↑ → more KV needed at once → more preemption risk
→ longer decode steps (each step reads more KV)
token budget ↑ → faster prefill, more throughput
→ slower steps when a big chunk rides along → worse ITL
→ bigger activation peak → less memory left for KV
longest request ↑ → bigger single prefills and longer slot holds
→ may fail to start if one full request no longer fits
memory fraction ↑ → more KV cache → more concurrency
→ less margin for activation spikesPresets#
Engines now offer presets that move several knobs together. vLLM’s --performance-mode
(balanced by default, interactivity, throughput) changes budgets, CUDA graph sizes and
kernel choices in one flag (19.d). Start from the preset that matches the workload, then adjust.
Batching outside the engine#
Two other kinds of batching belong to the serving system:
- Small non-generative models (embedders, rerankers, classifiers) run one forward pass per request, with nothing to continue. A server-side dynamic batcher waits up to a few milliseconds to collect requests into one batch (12.i). Triton’s dynamic batcher is the classic example; its key setting is the maximum queue delay. vLLM serves embedding models with its usual scheduler.
- Offline batch jobs: evaluation runs, document backfills, synthetic data. Run them through a
batch interface (vLLM’s
vllm run-batchreads and writes OpenAI-format JSONL files) or a low-priority class (20.k), on a pool tuned for throughput, so they never share a token budget with interactive users.
6. Under the hood: what the engine tells you at startup#
vLLM prints its capacity once memory is profiled (16.b reads the whole log):
GPU KV cache size: 688,304 tokens, Maximum concurrency for 32,768 tokens per request: 21.01x
Chunked prefill is enabled with max_num_batched_tokens=8192.- KV cache size in tokens is the real capacity: the total tokens all running requests can hold at once.
- Maximum concurrency is that number divided by
--max-model-len: the worst case, if every request used the whole context. Real requests are shorter, so real concurrency is higher. max_num_batched_tokensis the token budget actually in force, after defaults and presets.
Read these lines on every deploy. Divide the KV cache size by your p95 request length: that is the concurrency memory allows. If it is far below what you expected, check the memory fraction, the KV cache dtype (an FP8 cache doubles it, 13.h) and what else is on the GPU.
Each step, the scheduler fills the budget: first one token for every running request, then prefill chunks for waiting ones, until the budget or the cache runs out (17.a, 17.b).
7. Performance implications#
The direction each change moves the three numbers you care about:
| Change | Throughput | p95 time to first token | p95 ITL | Watch for |
|---|---|---|---|---|
| Concurrency cap ↑ (within memory) | ↑ | ↓ (less queueing) | ↑ | Preemptions |
| Concurrency cap at the memory maximum | ≈ | ↑↑ under long-request bursts | ↑ | Preemption storms |
| Token budget ↑ | ↑ | ↓ | ↑, spiky | p99 ITL during long prompts |
| Token budget ↓ | ↓ | ↑ for long prompts | ↓, smooth | Short prompts stuck behind long ones |
| FP8 KV cache | ↑ (more concurrency) | ↓ | ≈ | Quality on long context (13.h) |
| Separate pools for long and short prompts | ↑ | ↓ for short | ↓ for short | Utilization of the long pool (20.f) |
Your numbers depend on model, GPU and traffic. Sweep the cap and the budget on your own hardware and plot throughput against p95 ITL: the useful settings lie on the frontier.
8. Production implications#
- Do the capacity arithmetic first. If one replica cannot carry its share, no setting helps.
- Tune per workload. A retrieval service with long prompts and a chat service want different budgets for the same model. Give them different pools if both are large.
- Re-check when traffic changes. Prompt lengths drift as products evolve.
- Watch running batch size and preemptions as the main tuning signals.
- Write down the settings and why. Six months later nobody remembers why the budget is 2,048.
- Set the longest request from traffic, not from the model card.
- Keep batch jobs off interactive replicas, or behind a low priority.
9. Common mistakes#
- Concurrency cap at the memory maximum. Preemption storms when long requests cluster.
- Believing
max_model_lenshrinks capacity in a paged engine. It changes the worst case and startup, not the token capacity. - Memory fraction at 0.97. Out of memory on the first long prefill.
- A huge token budget on an interactive service. Great throughput, broken ITL.
- Tuning to fix a capacity problem.
- Copying someone else’s configuration for a different workload.
- Benchmarking with the offline API and deploying the server. vLLM’s offline
LLMclass uses larger default budgets thanvllm serve(17.b).
10. Hands-on exercise#
A. Run the arithmetic. Run sizing.go. Change the workload to retrieval: prompts average
8,000 tokens (p95 16,000), answers average 200. How many replicas now? Which term dominates?
B. Sweep the knobs. On a real server, sweep --max-num-seqs (16, 64, 256) and
--max-num-batched-tokens (1,024, 4,096, 16,384) separately. Measure throughput, p95 time to
first token and p95 ITL. Plot throughput against p95 ITL.
C. Induce preemption. Set the concurrency cap far above the memory-allowed value and send
long-context requests. Watch vllm:num_preemptions and the latency.
D. Test max_model_len. Start the server with --max-model-len 4096, then 32768. Compare
“GPU KV cache size” and “Maximum concurrency”. Which changed, and why?
E. Long prompts and ITL. Mix short streaming requests with an occasional 32,000-token prompt. Measure p99 ITL with a budget of 1,024 and of 16,384.
11. Interview questions#
- Name the four batching limits every continuous-batching engine has, and what each controls.
- How would you choose the token budget for a service with a 50 ms ITL target?
- Why should the concurrency cap not be the memory maximum?
- Does lowering
max_model_lengive a paged engine more KV cache? What does it change? - How do you tell a tuning problem from a capacity problem?
- What do the “KV cache size” and “maximum concurrency” lines in vLLM’s startup log tell you?
- Where does batching happen for an embedding model, and how is it different?
12. Further reading#
Checked on 12 November 2026.
- [REFERENCE] vLLM optimization and tuning — chunked prefill, the token budget and preemption
- [REFERENCE] vLLM engine arguments
- [REFERENCE] SGLang server arguments
- [REFERENCE] TensorRT-LLM: tuning max batch size and max num tokens
- [ESTABLISHED] Agrawal et al., “Sarathi-Serve” (OSDI 2024) — the chunked-prefill trade-off, analysed
- [REFERENCE] Triton dynamic batcher