Chapter 20
KV Cache, Paging, and Prefix Reuse
On this page
- Logical state and physical storage
- Fragmentation
- Block-size tradeoffs
- Allocation and reservation invariants
- Prefix cache identity
- Lookup structures and partial hits
- Eviction as value density
- Routing and cache locality
- Offload and migration
- Security and side channels
- Design Exercises
- Worked Solutions
KV state is the working set of autoregressive inference. Its lifetime follows requests, not batches, so allocation, sharing, eviction, placement, and security are first-class serving decisions.
At 131 kB per token on the running replica, a 500-token system prefix occupies about 65 MB. Storing it once for compatible requests can save substantial capacity. This chapter follows that state from allocation through sharing, eviction, and release.
Logical state and physical storage¶
Each cached token contributes a key and value vector at every attention layer. Logically, a sequence sees positions in order. Physically, those positions do not need to occupy one contiguous allocation. A serving engine can divide KV into fixed-size token blocks, allocate physical blocks on demand, and translate logical block numbers through a per-sequence table.
Paging avoids reserving the maximum possible output for every request and avoids copying the entire cache whenever a sequence grows. It also enables prefix sharing and copy-on-write branching. The attention implementation must accept block tables or an equivalent indirection, so memory management and kernel layout are designed together.
The term page may refer to a token block across selected layers, a per-layer allocation, or an engine-specific unit. Always state the unit, byte size, and placement. The important contract is stable logical order over movable or non-contiguous physical storage.
Fragmentation¶
Three forms matter:
- Internal fragmentation is unused space inside the last allocated block of a live sequence.
- External fragmentation is free memory that cannot satisfy an allocation because of size or placement constraints.
- Reserved slack is intentionally unallocated or pre-reserved capacity for growth and failure recovery.
With equal fixed-size blocks, external fragmentation in the KV pool is greatly reduced, but internal waste is bounded by at most one partially filled block per independent sequence or branch. Metadata, alignment, and separate pools can reintroduce constraints. Report effective usable KV capacity from the live allocator, not free bytes from a device-wide monitor.
Block-size tradeoffs¶
Smaller token blocks reduce tail waste, improve the granularity of prefix sharing, and make cancellation reclaim memory sooner. They increase block-table size, allocator operations, address translation, scatter in physical access, and scheduling metadata.
Larger blocks reduce metadata and can improve contiguous access, but waste more space on short or terminated sequences and require longer exact prefix matches before a whole block is reusable. The optimum depends on the sequence-length distribution, layer layout, attention kernel, and reuse pattern. Benchmark block sizes under memory pressure, not only with an empty cache.
Allocation and reservation invariants¶
A robust allocator maintains:
- no live sequence or in-flight kernel references a freed block;
- reference counts protect shared prefixes and speculative branches;
- copy-on-write occurs before a branch mutates shared state;
- reservation makes the next scheduled iteration memory-safe;
- cancellation and errors eventually release every owned reference;
- block tables are updated before kernels consume them, with explicit ordering;
- accounting attributes bytes to model, tenant, request, and cache class;
- migration or restore preserves token order, position state, dtype, and model identity.
Reserve before launch rather than discovering out-of-memory after some requests in a batch have advanced. For uncertain output length, reserve a bounded horizon and repeat admission checks. A reservation is a promise to the scheduler, not necessarily immediate physical zero-filling.
Output length is uncertain, so “reserve the declared maximum” and “reserve only the next token” are both poor universal policies. The first strands capacity; the second admits combinations that can fail together. Recent work on robust KV-cache management under output-length uncertainty makes this a joint decision across parallelism, reservation, routing, and prefix reuse. The durable lesson is to calibrate a length distribution by workload slice, reserve against an explicit tail-risk budget, and re-admit as evidence arrives. Treat paper-reported gains as workload-specific until replayed on the service's own arrival, prefix, and output correlations.
Prefix cache identity¶
Two compatible requests map their shared full prefix to the same physical pages and keep separate writable tails. Logical block order is independent of physical placement; reference counts protect shared pages from premature reuse.
KV for a prefix is reusable only when the computation that produced it is identical under the product contract. A key commonly includes:
- model weights and engine-compatible model version;
- tokenizer and exact token IDs;
- chat template and special-token policy;
- adapter or prompt-tuning state;
- positional encoding configuration and absolute offset;
- attention mode, relevant multimodal embeddings, and cache dtype;
- tenant or security namespace and cache salt;
- any hidden input that changes activations.
Text equality is insufficient because normalization or templates can change token IDs. Token equality can still be insufficient when adapter, image embedding, position, or model version differs. Cache identity should be a versioned schema with test vectors.
Lookup structures and partial hits¶
A trie or radix tree naturally represents shared token prefixes. A block-hash index maps full token blocks and their parent identity to cached blocks. Both can return the longest valid prefix rather than an all-or-nothing hit.
Insert only committed state. A cancelled or speculative branch may have computed tokens that were never part of the accepted sequence. Mark blocks immutable once published for reuse; append new private blocks and publish them only after the corresponding tokens and semantic state are committed.
Measure four distinct outcomes:
- request-level hit rate;
- reused-token fraction;
- prefill time or FLOPs avoided;
- net first-token improvement after lookup, routing, and transfer.
A full-prompt KV hit also needs an output contract. KV tensors alone do not ordinarily include the final hidden vector or vocabulary logits needed to sample the first new token. An engine can cache a compatible final hidden vector/logit result or recompute the final prompt token against the preceding KV prefix. In the latter case, remove or exclude that token's existing entry before appending its recomputed state; appending the same token a second time changes positions and history.
A high hit rate on tiny prefixes may save little. A lower hit rate on long system prompts can be far more valuable.
The running service makes the distinction concrete. Its shared 500-token system prefix costs about 65 MB to retain and can avoid up to 500 positions of prefill on compatible requests, subject to block alignment and any required logit recomputation. A per-user greeting of a few tokens may be common while saving almost nothing or failing to fill even one reusable block. Count actual reused positions and allocation overhead.
Eviction as value density¶
Least-recently-used eviction is a baseline, not a universal optimum. The value of an entry depends on expected reuse probability, recomputation cost, bytes, transfer locality, and the opportunity cost of displacing active KV.
A practical priority score may increase with saved prefill time and recent or known future reuse, and decrease with bytes and memory pressure. Pinning known system prompts can help, but permanent pins can crowd out active requests. Set budgets by cache class and expose why an entry survived or was evicted.
Prefix caching competes with decode capacity. Under pressure, retaining a reusable prefix may force rejection of a live request or reduce batch size. Admission and eviction need one memory objective, not separate local heuristics.
Routing and cache locality¶
In a replicated fleet, the router chooses between queue delay and cached state. Define an estimated completion score such as:
cost = queue_time + transfer_time + uncached_prefill_time + policy_penalty
Sticky routing maximizes locality but can create hot spots. Pure least-loaded routing destroys reuse. A cache-aware router considers both, places common prefixes on enough replicas, and falls back when a cache owner is unhealthy or overloaded.
Do not transfer a prefix merely because it exists elsewhere. Compare transfer time and network contention with recomputation. For a short prefix or a compute-rich prefill worker, recomputing may be cheaper and simpler.
Several maintained systems now make this design concrete. NVIDIA Dynamo consumes worker cache events for KV-aware routing and supports separate prefill and decode pools; LMCache extends reusable KV across GPU, CPU, local storage, and remote backends; llm-d exposes heuristic and event-driven prefix routing, a cache index, tiered offload, and disaggregated transfer; and Mooncake is a reference implementation of KV-centric disaggregation. These are implementation maps, not interchangeable libraries. Before adopting one, trace five contracts end to end: block identity, source-of-truth cache state, ownership and invalidation, transfer format and transport, and routing under stale events or worker failure.
Offload and migration¶
KV can be tiered across accelerator memory, host memory, local storage, or remote memory. Offload is useful when pause time is long enough to hide transfer and recomputation is more expensive. It is harmful when every decode step faults pages across a slow link.
For a state object of X bytes over sustainable bandwidth BW, a lower bound is X / BW, plus registration, serialization, queueing, and synchronization. Migration should transfer only live and required blocks, preserve reference ownership, and cancel cleanly if the destination can no longer admit the request.
A session cache and an active decode cache have different latency needs. Separate tiers and policies so inactive conversations cannot evict the working set of interactive generation.
Security and side channels¶
Cross-request reuse creates an information boundary. A tenant must not infer another tenant's prompt through timing, hit metadata, or shared identifiers. Namespace or salt cache keys, authorize sharing explicitly, avoid returning cache-hit details to untrusted callers, and consider padding or disabling cross-tenant reuse for sensitive workloads.
Deletion requirements propagate to cache copies, offloaded tiers, and replicas. Logging raw token keys or prefix hashes can itself leak information when prompts have low entropy. Treat cache metadata under the same retention policy as model inputs.
Design Exercises¶
- Why does paged KV reduce waste, and what costs does it introduce?
- How would you choose token-block size?
- State the allocator invariants required for prefix sharing and speculative branches.
- What must be included in a safe prefix-cache identity?
- Design a cache-aware routing and eviction policy.
- When should the system transfer, offload, recompute, or discard KV state?
Worked Solutions¶
1. Paging tradeoff¶
Paging allocates fixed-size blocks as sequences grow, so requests do not reserve maximum length and growth does not copy a contiguous cache. Tail waste is bounded by partially filled blocks, and blocks can be shared or released independently. Costs include block tables, allocation operations, address translation in attention, less contiguous physical access, metadata synchronization, and kernel complexity. The win must be measured with the actual block layout and memory pressure.
2. Block size¶
Sweep sizes against the production sequence and reuse distributions. Small blocks reduce internal fragmentation, reclaim sooner, and expose finer prefix hits; large blocks reduce metadata, allocation frequency, and translation overhead and may improve locality. Measure usable KV capacity, attention latency across context lengths, allocator CPU cost, block-table traffic, cache hit value, and cancellation reclamation. Choose by end-to-end goodput and SLOs, not fragmentation alone.
3. Sharing invariants¶
Published shared blocks are immutable and reference-counted. A branch increments references, performs copy-on-write before divergence, and publishes only accepted state. Scheduling reserves private growth blocks before launch. Freeing waits until no sequence or in-flight kernel can reference the block, with ordered block-table updates. Cancellation, rejection, and partial failure release every reference exactly once, and accounting remains attributable.
4. Cache identity¶
Use exact token IDs plus model and tokenizer versions, chat-template and special-token policy, adapter or prompt state, position configuration and offset, attention/cache mode and dtype, multimodal inputs that affect activations, and an authorization namespace or salt. Include any hidden feature that changes computed K/V. Version the identity schema so rollout cannot mix incompatible cache entries.
5. Routing and eviction¶
Estimate completion cost on candidate replicas from queue delay, reusable tokens, transfer or recompute time, memory pressure, and tenant policy. Replicate very hot prefixes enough to avoid affinity hot spots and use a no-cache fallback. Eviction should rank saved recompute time or known future value per byte while preserving active-request reserve and per-tenant limits. Continuously compare predicted savings with actual first-token improvement.
6. KV placement decision¶
Keep active working state on the accelerator. Transfer when another node can finish sooner after including network and admission cost. Offload when expected idle time can hide the round trip and recomputation is expensive. Recompute when the prefix is small, transfer links are contended, or local prefill is cheap. Discard when future reuse probability times saved work is below storage and displacement cost. Enforce deletion and tenant-isolation policy regardless of performance.