4.7Serving: batching & PagedAttention
How inference servers keep GPUs busy for thousands of users at once with continuous batching, paged KV-cache memory and prefix sharing.
Two numbers that pull against each other
Running a model for one person is easy. Running it for ten thousand people at once, on a fixed number of GPUs, is a systems problem. Two kinds of metric matter, and they conflict:
- Latency, what one user feels. The two standard measures are time to first tokenTime to first token (TTFT)Latency from sending a request until the first output token arrives. It is dominated by queueing and prefill. Its companion metric TPOT (time per output token) measures decode speed. (TTFT), which covers queueing plus prefillPrefillThe first phase of generation: the whole prompt is processed in one parallel forward pass, filling the KV cache and producing the first output token. It is usually compute-bound., and time per output token (TPOT), the pace of the streaming text during the decode phaseDecode phaseThe token-by-token phase of generation after prefill. Each step processes one new token per sequence and reads the whole KV cache and all weights, so it is usually memory-bandwidth-bound..
- Throughput, what the operator pays for: total tokens generated per second across all users, and therefore cost per million tokens.
The lever connecting them is the batch. Decoding is memory-bound: each step reads every weight once, whether it computes one sequence or sixty-four. Batch 64 sequences and you get roughly 64 times the tokens for not much more time per step, so throughput soars. But each step gets a bit slower, and every request now competes for memory, so latency suffers if you push too far. A serving engine’s job is to stay near the sweet spot under a constantly changing, unpredictable stream of requests.
A restaurant has six tables (batch slots), and the kitchen cooks for every occupied table at once. A static restaurant seats a party of six groups together and won’t seat anyone new until the slowest group has finished dessert, even though five tables sit empty for most of the evening. A smart restaurant reseats a table the moment it frees up: that’s continuous batching.
Then there’s the floor space (KV-cache memory). The old way reserves a long banquet table for every party, sized for the biggest group it might become, with seats empty all night. The new way is modular two-seat tables (blocks) pushed together as a party grows, placed wherever there’s room (paging), with a block table at the front desk recording which tables belong to whom. And when several parties share the same starter platter (a common system prompt), it goes on the table once.
Static vs continuous batching
The simplest server collects a batch of requests, runs them together until all have finished, and then starts the next batch. Requests produce wildly different numbers of tokens: one user asks for a yes/no answer, another for an essay. With static batching, the short requests finish early and their slots sit idle until the longest one is done, while new arrivals wait in the queue.
Continuous batching, introduced by the Orca system (Yu et al., OSDI 2022) as iteration-level scheduling, makes the scheduling decision at every decoding step instead of once per batch. When a sequence emits its end-of-sequence token, it leaves the batch immediately, and a waiting request takes its slot on the very next iteration. Different sequences in the batch are at different positions, with different lengths, but that’s fine: the big matrix multiplies treat each token independently, and only attention needs per-sequence handling. Continuous batchingContinuous batchingAdding and removing requests from a running batch at every generation step, instead of waiting for the whole batch to finish. is now standard in every major serving engine.
Each bar is one request (dark first cell = prefill, then one decode iteration per output token). Red hatching = a slot held by a finished request or left empty while the static batch waits for its longest member.
| GPU slot utilization | avg latency | avg time to first token | all done at | |
|---|---|---|---|---|
| Static | 50% | 35.7 it | 21.3 it | 92 it |
| Continuous | 70% | 23.8 it | 9.4 it | 66 it |
Things to try:
- “Very different” output lengths. Static batching shows large hatched areas: one long request holds the whole batch hostage. Continuous batching packs the timeline tightly, finishes sooner and slashes average latency.
- “Similar” output lengths. The gap shrinks: when every request needs about the same number of steps, there is little idle time to reclaim.
- More batch slots. Both improve, but static batching still wastes a fraction of every batch. In a real server, slots are limited by KV-cache memory, which is the next section’s topic.
The memory problem behind the batch
How many sequences can share a batch? Usually the limit isn’t compute but KV-cache memory: every running sequence keeps keys and values for all its tokens. And you don’t know in advance how long a sequence will become; the model decides when to stop.
Early serving systems handled this the way a naive program handles a growing array: they reserved one contiguous chunk per request, sized for the maximum possible length (prompt plus max_tokens). That wastes memory three ways:
- Reserved but unused: space for tokens the request may never generate.
- Internal fragmentation: even a request that runs to its limit leaves its reservation half-empty for most of its life.
- External fragmentation: after requests of different sizes finish, free memory is scattered in gaps too small for the next large request.
The vLLM paper measured that in existing systems only 20.4% to 38.2% of KV-cache memory actually held token states. Most of the precious GPU memory was empty reservations and gaps.
PagedAttention: virtual memory for the KV cache
PagedAttentionPagedAttentionvLLM's technique of storing the KV cache in fixed-size blocks, like virtual-memory pages, to avoid fragmentation and enable sharing. (Kwon et al., 2023), the core of vLLM, borrows the oldest trick in operating systems: paging. The KV-cache pool is divided into fixed-size blocks, each holding the keys and values of a small number of tokens (16 by default in vLLM). A sequence’s cache is a list of blocks that can live anywhere in memory. A per-sequence block table maps logical block 0, 1, 2… to physical block numbers, just as a page table maps virtual to physical pages.
- Blocks are allocated on demand: a new one only when the last block fills up. The only waste is the unfilled tail of each sequence’s last block, under one block per sequence.
- Any free block will do, so there is no external fragmentation.
- The attention kernel is modified to follow the block table, gathering keys and values from scattered blocks as it computes.
Paging also enables sharing. If several requests start with the same system prompt, or if one prompt is sampled several times, their block tables can point to the same physical blocks for the common part, with a reference count. Only when a shared block must be modified is it copied (copy-on-write). The paper reports 2–4× higher throughput than FasterTransformer and Orca at the same latency.
S2 region: slots 104–191 (prompt 24 + max_tokens 64 reserved; 24 used)
Things to try:
- Contiguous, step 0. Three requests run, and most of their reservations are faded (empty). S4 and S5 wait even though a large share of the pool holds no tokens at all.
- Drag the step slider to about 25. S1 and S3 have finished. S5 still can’t start: it needs 112 contiguous slots, and the free memory is split into gaps. Click S5 to see the largest gap. That’s external fragmentation.
- Switch to Paged. All five requests run from the start, and the “reserved but empty” share drops to a few percent. Click a sequence to read its block table: its blocks are scattered across the pool.
- Change the block size. Bigger blocks waste more in each last block; smaller blocks mean longer block tables and less efficient kernels. vLLM’s default of 16 is a compromise.
- Share prefix. The 16-token system prompt is stored once instead of once per request.
Beyond the basics
Prefix caching across requests. Prefix cachingPrefix cachingReusing the KV cache of a shared prompt prefix (like a system prompt) across requests, so the shared part is stored once and never recomputed. keeps the KV blocks of common prefixes (system prompts, few-shot examples, a long document several questions refer to) alive after a request finishes, so the next request with the same prefix skips that part of prefill. SGLang’s RadixAttention organizes cached prefixes in a radix tree and finds the longest match automatically. vLLM’s automatic prefix caching does something similar by hashing blocks. This is also why some API providers charge less for cached input tokens.
Chunked prefill. A 50,000-token prompt arriving mid-stream would stall everyone else’s decoding while its prefill runs. Sarathi-style chunked prefill splits long prefills into chunks and mixes them with ongoing decode steps in the same batch, smoothing out TPOT spikes and keeping the GPU busy with a mix of compute-heavy and memory-heavy work.
Prefill/decode disaggregation. Prefill is compute-bound; decode is memory-bound. Systems such as DistServe and Splitwise run them on different GPU pools, transferring the KV cache from prefill workers to decode workers, so each pool can be sized and tuned for its own bottleneck. Reports suggest large production deployments use variants of this idea, though details are rarely published.
MATH CORNER · optionalHow memory waste caps the batch, with numbers
Let the KV-cache budget be bytes, the cache per token bytes, and suppose requests have a prompt of tokens and generate on average tokens, with a limit of .
Contiguous reservation must hold tokens per request for its whole lifetime: .
Paging holds what’s actually there. Averaged over a request’s life it holds about tokens plus half a block of slack, so on average , where is the block size.
Worked example. Llama-3-8B ( KiB per token in BF16), GiB left for the cache after weights and activations on an 80 GB GPU, , , , .
| allocator | tokens held per request | concurrent requests |
|---|---|---|
| contiguous | ||
| paged | on average |
About 3.8× more concurrent sequences from the same memory, and because decoding is memory-bound, nearly that much more throughput, until compute becomes the limit. (The “on average” matters: a paged server must be ready to pause or swap out requests if many grow long at once. vLLM preempts sequences when blocks run out.)
Shared prefixes. If all requests share a 400-token system prompt inside that 500-token prompt, paging stores it once, so each request only adds tokens: requests in the same budget.
In code
Serving engines hide all this behind a simple interface. With vLLM, continuous batching, paged attention and (optionally) prefix caching are on by default:
from vllm import LLM, SamplingParams
llm = LLM(
model="meta-llama/Meta-Llama-3-8B-Instruct",
gpu_memory_utilization=0.90, # share of GPU memory for weights + KV blocks
enable_prefix_caching=True, # reuse KV blocks of shared prefixes
)
system = "You are a concise assistant. Answer in one sentence.\n\n"
prompts = [system + q for q in ["What is a KV cache?", "Why batch requests?",
"What does PagedAttention page?"]]
params = SamplingParams(temperature=0.7, max_tokens=128)
# All prompts are scheduled together; finished ones free their blocks immediately.
for out in llm.generate(prompts, params):
print(out.outputs[0].text)
- “Batching makes each user’s response faster.” It mainly raises total throughput. Each step gets somewhat slower as the batch grows; continuous batching reduces latency compared with static batching mostly by cutting queueing time.
- “PagedAttention is a new kind of attention that changes the model’s outputs.” The math is ordinary attention. Only the memory layout and the kernel that reads keys and values from scattered blocks change.
- “The KV cache is allocated once per request at its maximum length.” That was the old approach and wasted most memory. Paged systems allocate small blocks on demand as tokens are generated.
- “More GPU memory only helps fit bigger models.” For serving, extra memory mostly buys more concurrent sequences (a bigger batch), which directly raises throughput for memory-bound decoding.
Check your understanding
Q1.In static batching, a batch has requests needing 5, 8 and 40 decoding steps. What happens to the slots of the two short requests?
Q2.What is a block table in PagedAttention?
Q3.Why can paging eliminate external fragmentation?
Q4.Twenty requests share the same 1,000-token system prompt. With prefix sharing in a paged KV cache, how many copies of that prompt's KV cache are stored?
Q5.Which metric is most directly hurt when a very long prompt's prefill runs without chunking in the middle of other users' decoding?
Further reading
- paperEfficient Memory Management for LLM Serving with PagedAttention — Kwon et al., 2023: the vLLM paper.
- paperOrca: A Distributed Serving System for Transformer-Based Generative Models — Yu et al., OSDI 2022: iteration-level scheduling (continuous batching).
- paperSGLang: Efficient Execution of Structured Language Model Programs — Introduces RadixAttention for automatic KV-cache reuse.
- paperTaming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve — Chunked prefills and stall-free batching.
- paperDistServe: Disaggregating Prefill and Decoding — Running prefill and decode on separate GPUs.
- docsvLLM documentation — The open-source engine built around PagedAttention.