Skip to content
LearnAI

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.

⏱ 15 minAdvanced

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:

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.

ANALOGY· A restaurant with six tables

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.

INTERACTIVEBatching simulator
Output lengths
arrivalsStaticslot 1slot 2slot 3slot 4R1R2R3R4R5R6R7R8R9R10R11R12Continuousslot 1slot 2slot 3slot 4R1R2R3R4R5R6R7R8R9R10R11R120102030405060708090iteration

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 utilizationavg latencyavg time to first tokenall done at
Static50%35.7 it21.3 it92 it
Continuous70%23.8 it9.4 it66 it
Throughput gain
1.39×
same work, finished sooner
Latency reduction
33%
mean over requests
TTFT reduction
56%
less queueing behind long requests
Twelve requests with different output lengths arrive over time (triangles). The top timeline uses static batching, the bottom continuous batching, on the same number of slots. Red hatching is slot time wasted waiting for the longest member of a static batch.

Things to try:

  1. “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.
  2. “Similar” output lengths. The gap shrinks: when every request needs about the same number of steps, there is little idle time to reclaim.
  3. 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.

INTERACTIVEContiguous vs paged KV-cache memory
Allocator
Block size
Shared system prompt
S1S2S3
Each cell is one token's KV slot; solid = holds a token, faded = reserved but empty, gray = free.

S2 region: slots 104–191 (prompt 24 + max_tokens 64 reserved; 24 used)

Slots holding tokens
31%
120 of 384
Reserved but empty
50%
room for tokens not yet (or never) generated
Sequences
3 run · 2 wait
0 finished
Copies of system prompt
3
16 tokens each
A pool of 384 token slots serves five requests that each ask for up to 64 new tokens. Generate step by step and compare the allocators: contiguous reservation leaves requests waiting even when plenty of memory is free, while paging packs them in. Turn on prefix sharing to store a common 16-token system prompt only once.

Things to try:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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 MM bytes, the cache per token cc bytes, and suppose requests have a prompt of PP tokens and generate on average Gˉ\bar{G} tokens, with a limit of Gmax⁡G_{\max}.

Contiguous reservation must hold P+Gmax⁡P + G_{\max} tokens per request for its whole lifetime: Bcontig=Mc (P+Gmax⁡)B_{\text{contig}} = \dfrac{M}{c\,(P + G_{\max})}.

Paging holds what’s actually there. Averaged over a request’s life it holds about P+Gˉ/2P + \bar{G}/2 tokens plus half a block of slack, so on average Bpaged≈Mc (P+Gˉ/2+b/2)B_{\text{paged}} \approx \dfrac{M}{c\,(P + \bar{G}/2 + b/2)}, where bb is the block size.

Worked example. Llama-3-8B (c=128c = 128 KiB per token in BF16), M=40M = 40 GiB left for the cache after weights and activations on an 80 GB GPU, P=500P = 500, Gmax⁡=2000G_{\max} = 2000, Gˉ=300\bar{G} = 300, b=16b = 16.

allocatortokens held per requestconcurrent requests
contiguous500+2000=2500500 + 2000 = 250040 GiB/(2500×128 KiB)=13140\text{ GiB} / (2500 \times 128\text{ KiB}) = 131
paged500+150+8=658500 + 150 + 8 = 658 on average≈40 GiB/(658×128 KiB)≈498\approx 40\text{ GiB} / (658 \times 128\text{ KiB}) \approx 498

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 100+150+8=258100 + 150 + 8 = 258 tokens: ≈1,270\approx 1{,}270 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)
COMMON MISCONCEPTIONS
  • “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

0/5 answered
  1. 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?

  2. Q2.What is a block table in PagedAttention?

  3. Q3.Why can paging eliminate external fragmentation?

  4. 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?

  5. 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

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.