KV CACHE BATCHING
The batch waits for its longest request, and the memory waits for tokens that never come
An inference server batches statically. A batch starts with three requests that will generate 22, 3 and 18 tokens, one token each per iteration. When does the 3-token request's response go back to its caller?
Generating text runs the model once per output token. Each running request keeps a KV cache: the keys and values of every token so far, one slot per token, growing as it generates. The server batches requests so one pass over the weights serves many of them. Two things go wrong. A static batch is fixed until its longest member finishes. And because no one knows how long an answer will be, the server reserves KV memory for the maximum length up front, so most of the memory holds nothing.
The fixes are two separate ideas. Iteration-level scheduling re-forms the batch at every iteration. A paged KV cache stores each request’s cache in small blocks allocated as it grows, like pages of virtual memory.
# static batching, contiguous KV per request
while True:
batch = take_while(queue, lambda r: reserved + MAX_LEN <= KV_SLOTS)
reserve(batch, MAX_LEN) # 32 slots each, used or not
while any(not r.done for r in batch): # wait for the longest
step(batch)
respond(batch); free(batch)# iteration-level scheduling + paged KV cache
while True:
for r in running: # oldest first
while needs_block(r) and not alloc_block(r):
preempt(newest(running)) # free its blocks, recompute later
while queue and blocks_for(queue[0]) <= free_blocks():
admit(queue.pop(0)) # joins the batch this iteration
step(running) # one token each
for r in finished(running):
respond(r); free_blocks_of(r) # returns now, frees now The memory map has one character per KV slot: a letter is a token, a dot is reserved but empty, an underscore is free. In STATIC, RESERVE MAX the map is mostly dots, and B finishes at iteration 2 but returns at 21. STATIC, NO RESERVE fills memory with real tokens, then runs out as the batch grows and kills A. CONTINUOUS, RESERVE MAX returns B at once but the dots stay. In FIX: CONTINUOUS + PAGED the letters of different requests interleave across blocks, every invariant stays green, and the same ten requests finish in 22 iterations instead of 62.
Paging only wastes the unused tail of each request’s last block. Leave KV memory at 96 slots and find the smallest block size at which the paged server holds less than 60% real tokens in some iteration (the invariant).
GOAL: smallest block size that drops memory use below 60%
Write the scheduler. Every iteration the server calls plan(s), then gives each running request (plus each one you admit) the blocks it needs for one more token, then generates that token. Return { admit: [ids], preempt: [ids] }: admit takes ids from s.waiting, preempt takes ids from s.running (their blocks are freed and they go back to the front of the queue to be recomputed). A request needs Math.ceil((tokens + 1) / blockSize) blocks in total. The grader fails the run if the blocks needed ever exceed the free blocks (out of memory mid-batch), if any request takes longer than 300 iterations, or if the mean latency (arrival to return, in iterations) on either trace is over 32. Memory is 16 blocks of 4 tokens, enough for two requests at their 32-token maximum. Output lengths are unknown to you, as they are to a real server.
What the sim simplifies: memory is counted in token slots rather than bytes, every iteration takes the same time, prefill is one iteration however long the prompt, and recomputing a preempted request is free. In a real server, prefill of a long prompt is slower than a decode step, and recomputation costs a prefill. The block sizes and the 60% line are toy-scale. The vLLM paper uses 16 tokens as its default block and reports that blocks too small underuse the hardware and blocks too large waste memory.
The real numbers are bigger. For OPT-13B the paper puts the KV cache at 800 KB per token, so one request at OPT’s 2,048-token limit can need 1.6 GB. Orca (Yu et al., OSDI 2022) introduced iteration-level scheduling and reports 36.9x the throughput of NVIDIA FasterTransformer at the same latency on GPT-3 175B. vLLM adds paging on top and reports 2–4x the throughput of FasterTransformer and Orca at the same level of latency. Both comparisons are on the authors’ own workloads. When vLLM runs out of blocks it preempts and logs that a sequence group “is preempted by PreemptionMode.RECOMPUTE mode because there is not enough KV cache space”. When you see that warning, its tuning guide suggests giving the cache more memory or admitting fewer sequences at once. The caching, batching and latency chapter covers prefill and decode from the API caller’s side. Two lessons build on this memory: prompt cache prefix keeps a prompt’s KV cache for the next request that starts with the same bytes, and speculative decoding spends the compute a memory-bound decode step leaves idle.
Self-hosted inference with vLLM, TGI, SGLang or TensorRT-LLM, and capacity planning for GPU serving. Symptoms: GPU memory at the limit while batch sizes stay small, throughput that plateaus as the queue grows, short requests with long tails, out-of-memory errors under a burst of long prompts, and on paged servers a rising preemption count in the logs.
“Why is LLM serving throughput limited by memory and not compute?” or “Explain continuous batching and PagedAttention.” Explain that decode generates one token per request per iteration and that the KV cache grows with every token, then name both failures: static batches wait for the longest request, and max-length reservation wastes most of the memory. Give the fixes (iteration-level scheduling, block-based allocation on demand) and the trade-offs: block size against fragmentation, and preemption by swapping or recomputation when blocks run out.
USED IN
Chapters that build on this lesson.
- Cost, latency and choosing the modelAI Engineer