On this page
A coding assistant receives a repository question with system instructions, file excerpts, a failing test, and earlier tool results. Every generated token must attend back to that history. Recomputing every earlier attention projection on every step would turn a response into quadratic replay.
Instead, the engine retains each attention layer's Key () and Value () vectors in GPU HBM as the KV cache. Each decode step projects only the newest token, appends , and reads the cached history. Grouped-Query Attention (GQA) and Multi-Query Attention (MQA) shrink each token's footprint, yet placement remains the bottleneck: variable-length requests can strand 60% to 80% of VRAM inside oversized contiguous reservations. PagedAttention (introduced in vLLM) adapts operating-system paging to store KV state in fixed-size reusable blocks, unlocking near-zero fragmentation, copy-on-write branching, and cross-request prefix caching (RadixAttention and chained block hashes).[1][2]
Why the KV cache exists
In full causal self-attention, generating token attends over positions :[3]
Without a cache, generating tokens recomputes Key/Value projections. Caching writes and once per position ( projections total), though full causal decode still reads all cached positions at step , making long-context decode memory-bandwidth bound.[1]

KV cache memory analysis
Every cached token stores both and across every layer and KV head:
In MHA, . Under GQA, multiple query heads share one KV head: Llama 3 70B has 64 query heads and 8 KV heads, cutting FP16 KV storage from 2.5 MiB/token down to 320 KiB/token (1.25 GiB at 4K context, 10 GiB at 32K, 40 GiB at 128K).[4][5]
| Architecture | Layers | KV Heads | Cache/token (FP16) | 4K Context | 32K Context | |
|---|---|---|---|---|---|---|
| Llama 3 8B (GQA) | 32 | 8 | 128 | 128 KiB | 512 MiB | 4 GiB |
| Llama 3 70B (GQA) | 80 | 8 | 128 | 320 KiB | 1.25 GiB | 10 GiB |
| GPT-3 175B (MHA) | 96 | 96 | 128 | 4.5 MiB | 18 GiB | 144 GiB |

def cache_gib(layers: int, kv_heads: int, head_dim: int, bytes_per_value: int, tokens: int) -> float:
return (2 * layers * kv_heads * head_dim * bytes_per_value * tokens) / (1024 ** 3)
for label, heads in [("MHA-64", 64), ("GQA-8", 8), ("MQA-1", 1)]:
print(f"{label}: {cache_gib(80, heads, 128, 2, 4096):.2f} GiB at 4K tokens")MHA-64: 10.00 GiB at 4K tokens
GQA-8: 1.25 GiB at 4K tokens
MQA-1: 0.16 GiB at 4K tokensFor Llama 3 70B (80 layers, 8 KV heads, head dimension 128, FP16), how many bytes does one token add?
Answer
bytes = 320 KiB per token (1.25 GiB at 4K tokens).
Memory fragmentation and PagedAttention
Early serving engines avoided repeated reallocation by reserving one contiguous buffer sized for max_model_len (e.g., 8,192 tokens) when each request arrived. That static reservation created three distinct forms of waste totaling 60% to 80% of KV VRAM:[1][6]
- Internal fragmentation: A request reserves 8,192 slots and stops at token 600, locking 7,592 unused slots until exit.
- Reservation waste: Even slots that a sequence will eventually reach sit idle for hundreds of decode steps.
- External fragmentation: Variable-sized reservations free scattered holes that cannot satisfy a larger contiguous allocation.
PagedAttention borrows operating-system virtual memory paging:[1]
- Logical blocks divide each request's token positions into fixed-size pages of tokens (commonly ).
- Physical blocks form a uniform pool of fixed-size VRAM slots that need not be contiguous.
- A per-request block table translates logical position to .

Paging eliminates external fragmentation inside the uniform pool and caps per-request waste to at most unfilled slots in the final block ( at exact multiples of , at 120 tokens with ). Choosing trades finer sharing and lower tail waste (smaller ) against smaller block tables and more regular vector loads (larger ; vLLM's sweet spot is typically 16 or 32).
Paged kernels vs. contiguous virtual memory (vAttention)
PagedAttention requires attention kernels that follow the block table per warp. In vLLM's original microbenchmark, block-table indirection added 20% to 26% attention-kernel latency over FasterTransformer's contiguous kernel, while recovered VRAM unlocked larger batches for higher end-to-end throughput.[1] vAttention takes the opposite trade-off: it reserves contiguous virtual address ranges and commits physical GPU pages on demand via CUDA virtual-memory APIs, letting unmodified contiguous attention kernels run while shifting complexity into driver page management.[7]
Also keep PagedAttention distinct from FlashAttention[8] and FlashInfer:[9] PagedAttention is a KV memory layout and allocator, whereas FlashAttention/FlashInfer are IO-aware GPU attention kernels that read tiled Q/K/V (including paged KV layouts) with minimal HBM round-trips.
Block manager implementation and read parity
The CPU-side manager below tracks free physical block IDs and per-request block tables, then verifies that gathering and through scattered blocks reproduces contiguous attention exactly while excluding invalid trailing slots:
class PagedKVCacheManager:
def __init__(self, num_blocks: int, block_size: int):
self.block_size = block_size
self.free_blocks: list[int] = list(range(num_blocks))
self.block_tables: dict[str, list[int]] = {}
self.seq_lens: dict[str, int] = {}
def allocate(self, request_id: str) -> None:
if request_id in self.block_tables:
raise ValueError(f"request already allocated: {request_id}")
if not self.free_blocks:
raise MemoryError("KV block pool exhausted")
self.block_tables[request_id] = [self.free_blocks.pop()]
self.seq_lens[request_id] = 0
def append_slot(self, request_id: str) -> tuple[int, int]:
blocks = self.block_tables[request_id]
idx = self.seq_lens[request_id]
if idx > 0 and idx % self.block_size == 0:
if not self.free_blocks:
raise MemoryError("KV block pool exhausted")
blocks.append(self.free_blocks.pop())
self.seq_lens[request_id] = idx + 1
return blocks[-1], idx % self.block_size
def free(self, request_id: str) -> None:
if request_id in self.block_tables:
self.free_blocks.extend(self.block_tables.pop(request_id))
del self.seq_lens[request_id]
manager = PagedKVCacheManager(num_blocks=20, block_size=4)
manager.allocate("A")
slots = [manager.append_slot("A") for _ in range(5)]
manager.allocate("B")
b_slot = manager.append_slot("B")
manager.free("A")
print("A slots:", slots, "| B slot:", b_slot, "| free after freeing A:", len(manager.free_blocks))A slots: [(19, 0), (19, 1), (19, 2), (19, 3), (18, 0)] | B slot: (17, 0) | free after freeing A: 19import numpy as np
pool = PagedKVCacheManager(num_blocks=4, block_size=2)
k_pool = np.full((4, 2, 2), 1000.0, dtype=np.float64)
v_pool = np.full((4, 2, 2), 999.0, dtype=np.float64)
k_seq = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=np.float64)
v_seq = np.array([[2.0, 1.0], [0.0, 3.0], [4.0, 2.0]], dtype=np.float64)
def write(req, kv_k, kv_v):
b, o = pool.append_slot(req)
k_pool[b, o], v_pool[b, o] = kv_k, kv_v
def read(req):
n = pool.seq_lens[req]
return k_pool[[pool.block_tables[req][i // 2] for i in range(n)], [i % 2 for i in range(n)]], \
v_pool[[pool.block_tables[req][i // 2] for i in range(n)], [i % 2 for i in range(n)]]
def attend(q, k, v):
s = (k @ q) / np.sqrt(k.shape[-1])
w = np.exp(s - np.max(s))
return (w / w.sum()) @ v
pool.allocate("A"); write("A", k_seq[0], v_seq[0])
pool.allocate("B"); write("B", np.array([-1.0, 0.0]), np.array([-5.0, -5.0]))
write("A", k_seq[1], v_seq[1]); write("A", k_seq[2], v_seq[2])
q = np.array([1.0, 0.5], dtype=np.float64)
expected = attend(q, k_seq, v_seq)
actual = attend(q, *read("A"))
assert pool.block_tables["A"] == [3, 1] and np.allclose(actual, expected, atol=1e-12)
assert not np.allclose(attend(q, k_pool[[3, 3, 1, 1], [0, 1, 0, 1]], v_pool[[3, 3, 1, 1], [0, 1, 0, 1]]), expected)
print("A table:", pool.block_tables["A"], "| output:", tuple(round(float(x), 6) for x in actual))A table: [3, 1] | output: (2.461842, 1.90474)![Spatial block-table mapping for paged KV read parity (block size 2). Left block tables show A table [3, 1] with valid_length = 3 and B table [2]. Arrows connect A logical block 0 to physical block #3 (valid positions p0 and p1) and A logical block 1 to physical block #1 (valid position p2 in slot 0; invalid sentinel K=(1000,1000), V=(999,999) in slot 1 excluded by valid_length). B maps to physical block #2. Bottom readout confirms q=(1, 0.5) gives identical paged and contiguous attention output (2.461842, 1.904740).](https://assets.leetllm.com/v1/618d658ce6be/fundamentals/kv-cache-paged-attention-llm-serving/illustrations/_generated/paged_read_parity_dark.png)
Copy-on-write branching and prefix caching
Block tables unlock two distinct kinds of KV sharing: intra-request branching (beam search, Best-of-N parallel sampling) via reference-counted Copy-on-Write (CoW), and cross-request reuse via prefix caching / RadixAttention.
Copy-on-write for shared partial blocks
When branches A and B fork from one prompt, both block tables point to the same physical blocks with ref_count = 2. Full shared blocks stay read-only while each branch appends into its own new block. The subtle bug sits in a shared partial block: if A and B share 3 slots of a 4-slot block, letting both write into slot 3 lets B overwrite A's token in place. Trigger CoW whenever ref_count > 1: copy the 3 valid slots into a private block for A, decrement the original block's count to 1, and let B write the original in place.[1]
storage = [[10, 20, 30, None], [None] * 4]
tail_blocks, refs, free = {"A": 0, "B": 0}, {0: 2, 1: 0}, [1]
def append_fourth(branch, val):
old = tail_blocks[branch]
if refs[old] > 1:
new = free.pop()
storage[new] = storage[old][:3] + [None]
tail_blocks[branch] = new
refs[old] -= 1
refs[new] = 1
storage[tail_blocks[branch]][3] = val
append_fourth("A", 90)
append_fourth("B", 80)
print("isolated branches:", {k: storage[b] for k, b in tail_blocks.items()}, "| refs:", refs)isolated branches: {'A': [10, 20, 30, 90], 'B': [10, 20, 30, 80]} | refs: {0: 1, 1: 1}
Prefix caching, RadixAttention, and cache-hit TTFT math
In causal self-attention, position depends only on positions . When separate requests share an identical prefix (system prompt, repository guide, tool schemas), prefix caching (called prompt caching on hosted APIs) keeps those completed KV blocks reusable across requests. Editing even one token near position 0 invalidates every downstream block!
Serving engines index reusable prefixes in two main ways:
| Engine | Indexing structure | Lookup and eviction |
|---|---|---|
| vLLM (Automatic Prefix Caching)[10] | Hash table over fixed-size PagedAttention blocks | Chains each block hash including LoRA ID and cache_salt; evicts unreferenced blocks via LRU |
| SGLang (RadixAttention)[2] | Compressed radix tree (token trie) | Traverses shared token edges, splits edges on divergence, and evicts unreferenced leaves via LRU |
Suppose 100 requests share a 1,000-token prompt with 16-token blocks: 62 complete blocks (992 tokens) are shared once while each request keeps 1 private tail block (8 tokens), dropping occupied prefix blocks from 6,300 to 162 (97.4% reduction). Even on an exact 1,008-token match, vLLM recomputes the final block so it can emit next-token logits.[11]

On prefill latency, consider three requests sharing a 6,000-token guide with question tails of 48, 37, and 51 tokens: fresh prefill drops from 18,136 tokens to 6,136 tokens (saving 12,000 prefill tokens). Warm prefill can drop from 1,220 ms to 170 ms (saving 1,050 ms on TTFT), while decode latency stays unchanged (880 ms) because decode still reads the cached prefix.
Four operational rules govern production prefix caching:
- Static-first prompt layout and hosted break-even economics: Put immutable instructions, guides, and tool schemas first, and dynamic timestamps, retrieved chunks, and user queries last. On hosted APIs with a cache write surcharge (e.g., for 5-min TTL or for 1-hour TTL) and discounted reads (),[12][13] full-prefix break-even reads equal:
That repays a write in 1 read and a write in 2 reads. Beware partial hits: paying writes on an initial 6,000-token call and then reusing only 1,024 of 6,000 tokens (with writes on the remaining 4,976 tokens) across three follow-up calls costs 10.3% more than uncached input! Always report volume-weighted token hit ratio () rather than binary request hits, and normalize provider schemas (OpenAI
input_tokensincludescached_tokens; Anthropicinput_tokensexcludescache_read_input_tokens). - Cached does not mean occupied: Completed requests leave blocks cached but unreferenced on the free queue. In a 1,000-block pool with 450 referenced, 400 cached-unreferenced, and 150 free blocks, 550 blocks are allocatable without preempting active requests.
- Prefix-affinity routing vs. queueing inversion: Sending repeat prefixes to one warm replica saves cold warmups, yet if queueing on a hot worker jumps from
20 msto1,200 mswhile prefill drops from1,220 msto170 ms, client TTFT actually gets 130 ms slower (1,370 msvs.1,240 ms). Pair prefix affinity with queue-depth caps or bounded-load consistent hashing.[14] - Server-derived tenant isolation: Because cache hits return faster, sharing prefixes across untrusted tenants opens a timing side-channel. Bind
cache_saltstrictly from server-verified authentication, never from raw client headers.[10]
from hashlib import sha256
from math import ceil
import json
def chain(salt: str, blocks: list[str]) -> list[str]:
parent, out = salt, []
for blk in blocks:
parent = sha256(json.dumps([parent, blk], separators=(",", ":")).encode()).hexdigest()
out.append(parent)
return out
v1 = chain("tenant-a", ["sys", "guide-v1", "tools"])
v2 = chain("tenant-a", ["sys", "guide-v2", "tools"])
tb = chain("tenant-b", ["sys", "guide-v1", "tools"])
print("v1 vs v2 hits:", [a == b for a, b in zip(v1, v2)], "| cross-tenant collision:", any(a == b for a, b in zip(v1, tb)))
# 3 requests sharing 6,000 prefix tokens + tails [48, 37, 51]
tails = [48, 37, 51]
print(f"Fresh prefill tokens: {sum(6000 + t for t in tails)} -> {6000 + sum(tails)} (saved {2 * 6000})")
print(f"Break-even reads (1.25x / 2.0x write, 0.10x read): {ceil(0.25 / 0.90)} / {ceil(1.0 / 0.90)}")
usage = [(0, 6000)] + [(1024, 4976)] * 3
uncached = sum(r + w for r, w in usage)
cached = sum(0.10 * r + 1.25 * w for r, w in usage)
print(f"Partial-hit trap: uncached={uncached} vs cached={cached:.1f} ({cached / uncached - 1:+.1%})")v1 vs v2 hits: [True, False, False] | cross-tenant collision: False
Fresh prefill tokens: 18136 -> 6136 (saved 12000)
Break-even reads (1.25x / 2.0x write, 0.10x read): 1 / 2
Partial-hit trap: uncached=24000 vs cached=26467.2 (+10.3%)Preemption, pool exhaustion, and continuous batching
PagedAttention pairs naturally with continuous batching (iteration-level scheduling from Orca[15]): as soon as a short request emits EOS, its blocks return to the pool and a waiting request enters on the next iteration instead of waiting for the longest sequence in a static batch.
When the block pool fills completely under heavy load, two invariants protect correctness and recovery:
- Failed allocation must preserve state: A rejected
append_slotleaves block tables, lengths, and ownership untouched, and duplicatefree()calls must never insert a physical block ID into the free list twice (which would alias two live customers onto the same KV memory). - Recompute vs. swap preemption: vLLM V1 defaults to recomputation (releasing preempted blocks and replaying tokens on resume, spending GPU FLOPs rather than PCIe bandwidth), whereas legacy V0 also supported CPU swapping (moving blocks over PCIe to host RAM and back).[1][16] Optional KV-offloading connectors also allow tiering reusable blocks to CPU/SSD (as in Mooncake[17]).
tiny = PagedKVCacheManager(num_blocks=2, block_size=4)
tiny.allocate("A"); tiny.allocate("B")
for _ in range(4):
tiny.append_slot("A")
before = (tuple(tiny.free_blocks), {k: tuple(v) for k, v in tiny.block_tables.items()}, dict(tiny.seq_lens))
try:
tiny.append_slot("A")
except MemoryError as err:
print("blocked:", err)
assert (tuple(tiny.free_blocks), {k: tuple(v) for k, v in tiny.block_tables.items()}, dict(tiny.seq_lens)) == before
tiny.free("B"); tiny.free("B") # Idempotent release prevents double-free aliasing.
assert tiny.free_blocks == [0]
print("retry after freeing B:", tiny.append_slot("A"), "| A table:", tiny.block_tables["A"])blocked: KV block pool exhausted
retry after freeing B: (0, 0) | A table: [1, 0]![A two-block, four-slot manager starts with A owning block 1 at length four and B owning empty block 0 at length zero. A fifth append raises MemoryError because the free list is empty and leaves both tables, lengths, and blocks unchanged. Freeing B twice returns block 0 once; retry writes slot (0, 0), giving A table [1, 0] and length five.](https://assets.leetllm.com/v1/7093c1241e0d/fundamentals/kv-cache-paged-attention-llm-serving/illustrations/_generated/pool_exhaustion_state_dark.png)
Capacity levers beyond paging
Paging eliminates fragmentation waste, not raw KV bytes per token. When every request fills its context window (e.g., Llama 3 70B at 128K = 40 GiB in FP16), shrink or relocate the state using complementary levers:
| Lever | What it changes | Primary trade-off |
|---|---|---|
| GQA / MQA / MLA[4][18] | Architectural KV heads or low-rank latent cache | Fixed at model architecture/training time |
| KV Quantization (FP8 / KIVI)[19] | Stored precision per value (FP8 halves raw bytes) | Requires kernel support, scale factors, and accuracy validation |
| Token Eviction (SnapKV / H2O)[20][21] | Drops low-attention KV positions from history | Lossy; can drop facts needed by later turns |
| Chunked Prefill & Disaggregation[22][23] | Bounds prefill interference with active decode steps | Disaggregation adds RDMA KV transfer and pool coordination |
| Tensor Parallelism (TP)[1] | Shards KV heads across ranks (only when n_kv_heads % TP == 0) | Always budget per rank; indivisible TP replicates KV heads |