KV CACHE BATCHING

The batch waits for its longest request, and the memory waits for tokens that never come

L218 MINAI SYSTEMS
PREDICT

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.

▶ SIMULATION
KV MEMORY · 96 slots · not started
iteration 0 · letter = a token's KV · · = allocated, empty · _ = free
________________________________ ________________________________ ________________________________
holding real tokens now: — · worst so far: 100%
tokens generated: 0 · preemptions: 0 · killed: 0 · returned late (held for the batch): 0
REQUESTS
A · prompt 8 · output 22 · arrives 0
arrives at 0
B · prompt 6 · output 3 · arrives 0
arrives at 0
C · prompt 10 · output 18 · arrives 0
arrives at 0
D · prompt 8 · output 4 · arrives 0
arrives at 0
E · prompt 6 · output 20 · arrives 0
arrives at 0
F · prompt 12 · output 5 · arrives 1
arrives at 1
G · prompt 8 · output 3 · arrives 3
arrives at 3
H · prompt 6 · output 16 · arrives 4
arrives at 4
I · prompt 10 · output 6 · arrives 6
arrives at 6
J · prompt 8 · output 4 · arrives 9
arrives at 9
✓ no request is killed because KV memory ran out✓ allocated KV memory holds real tokens ≥ 60% (worst iteration so far)✓ a finished request returns in the iteration it finishes
SCHEDULE
01[SERVER]static batching; reserve 32 slots per request
02[SERVER]run iterations 0–3
03[SERVER]run iterations 4–7
04[SERVER]run iterations 8–11
05[SERVER]run iterations 12–15
06[SERVER]run iterations 16–19
07[SERVER]run iterations 20–23
08[SERVER]run iterations 24–27
09[SERVER]run iterations 28–31
10[SERVER]run iterations 32–35
11[SERVER]run iterations 36–39
12[SERVER]run iterations 40–43
13[SERVER]run iterations 44–47
14[SERVER]run until every request has returned
Start of static, reserve max scenario. 14 steps.
# 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)

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.

BREAK IT NOT YET

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%

FIX IT NOT YET

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.

Mental model:

An LLM server’s batch size is set by KV-cache memory, not by compute. Do not reserve memory for tokens a request might generate. Allocate it in blocks as tokens arrive. Do not hold the batch for its slowest member. Re-form it every iteration, so a finished request leaves at once and a waiting one joins as soon as a block is free. When blocks run out, preempt a whole request and recompute it later; do not crash the batch.

IN PRODUCTION

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.

IN INTERVIEWS

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

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: SPECULATIVE DECODING →