Large Language ModelsInference & Performance Optimization
How do you size an LLM prefix cache from workload traces using KV-page stack distance?
Question 309 of 309 · Updated
On this page
- The capacity question
- 1. Define the unit you are sizing
- 2. Turn serving traffic into a page-reference stream
- 3. Understand LRU stack distance
- A small example
- 4. Derive the entire LRU capacity curve in one pass
- A toy numerical curve
- 5. How KVSET computes stack distances efficiently
- 6. Convert the curve into a working-set capacity
- 7. Use the curve to choose capacity and memory tiers
- 8. Example: a capacity decision for an agent-serving workload
- 9. The assumptions that determine whether the estimate is valid
- 10. Validate the model against the actual cache
- 11. Common mistakes
- 12. Production rollout checklist
- Interview-ready summary
The capacity question#
Prefix caching lets an LLM serving system reuse key/value (KV) tensors for a prompt prefix that has already been processed. This avoids repeating prefill computation, but only while the required KV pages remain available. Too little cache causes repeated misses and expensive prefill; too much cache ties up GPU, host-memory, or storage capacity that may deliver little additional reuse.
The practical question is not “How much KV history have we ever generated?” It is: What is the smallest cache capacity that preserves a chosen level of reuse for this workload?
That capacity depends on prompt lengths, shared-prefix patterns, agent turn histories, request ordering, concurrency, cache-page size, and eviction policy. A benchmark that reports one hit rate at one cache size cannot tell an operator how the whole capacity curve behaves.
KVSET, described in *The KV Cache Working Set: Online Capacity Planning for LLM Inference Systems*, applies the classical Mattson stack-distance algorithm to KV-page access traces. Its key idea is to derive cache hit rates for many candidate capacities from one pass over a reference stream, rather than independently simulating a different LRU cache for every size.
The method is useful as a capacity-planning instrument, but its predictions are exact only under the cache and trace assumptions discussed below.
1. Define the unit you are sizing#
A serving engine usually allocates KV memory in fixed-size pages or blocks. Each page stores keys and values for a range of tokens across model layers, according to the runtime's layout.
For a fixed model and KV format:
For example, if one KV page occupies 256 KiB, a cache of 4,096 pages represents 1 GiB. This is illustrative; actual bytes depend on model dimensions, layer count, KV heads, data type, block size, and whether the runtime stores full-attention, sliding-window, or other state types.
Keep these units distinct:
- Page capacity: number of cache pages the policy can retain.
- Byte capacity: physical memory consumed by those pages.
- Token capacity: token positions represented by the pages; partial blocks and mixed layouts complicate conversion.
- Request hit rate: fraction of requests meeting a defined cache-reuse condition.
- Page or token hit rate: fraction of page references or prompt tokens served from cache.
A request hit rate and a page hit rate are not interchangeable. A long prompt can contribute many page references while a short prompt contributes few. Always state the denominator.
2. Turn serving traffic into a page-reference stream#
The Mattson method works on a sequence of references to cache objects. For KVSET, the objects are KV pages and the sequence represents their accesses over time.
A simplified stream might look like:
A, B, C, A, B, D, A, C, E, A, BHere, A through E represent page identities, not tokens or requests.
This stream could arise from several requests that share a prefix. If one request accesses pages A, B, and C, and a later request reuses A and B before adding D, the access stream records those page references in the order the cache actually observes them.
The trace must preserve the order that matters to eviction. If requests are concurrent, interleaving can change reuse distances. Reconstructing a stream by grouping all pages from request 1, then request 2, then request 3 may not reproduce the order seen by the real cache.
Before analyzing a trace, document:
- Which event counts as a page access: prefix lookup, successful KV reuse, page promotion, or another runtime-defined event.
- How token prefixes map to page identities and page boundaries.
- Whether the trace records actual interleaved access order across requests and tenants.
- How duplicate, partial, pinned, in-flight, and invalidated pages are handled.
- Whether the cache has one global replacement order or separate pools and tiers.
- Whether the observed traffic is representative of the workload you plan to serve.
The stream is the foundation of the estimate. An exact algorithm over an inaccurate stream still produces an inaccurate deployment forecast.
3. Understand LRU stack distance#
For an LRU cache, the stack distance of a page access is the number of distinct pages referenced more recently than that page since its previous access.
Imagine a stack containing every previously seen page, ordered from most recently used to least recently used. Immediately before an access:
- The most recently used page has stack distance 1.
- The second most recently used page has distance 2.
- A page that has not appeared before is a cold miss at every finite capacity.
For a page with a previous reference, its stack distance tells us exactly which LRU cache capacities would retain it.
Under the usual one-based convention:
where d is the stack distance and C is the number of pages the cache can hold. Some implementations use zero-based distance, so the inequality changes by one. State the convention when comparing implementations.
A small example#
Consider this access sequence:
Access: A B C A B D A
Distance: ∞ ∞ ∞ 3 3 ∞ 3The first references to A, B, and C are cold misses. When A is referenced again, C and B have been used more recently, so A has distance 3. A cache of capacity 3 or larger would hit; a cache of capacity 2 would miss. When B is referenced, C and A are more recent, so B also has distance 3. D is new, and the final A access again has distance 3 because D and B are more recent than A.
The distances are properties of the access stream, not of one particular cache size.
4. Derive the entire LRU capacity curve in one pass#
A naive experiment might run the same trace repeatedly: simulate a 1,000-page LRU cache, then a 2,000-page cache, then a 4,000-page cache, and repeat for every candidate capacity. That approach is straightforward, but work grows with the number of candidate capacities.
The Mattson stack property gives a more efficient route. For each access, compute its stack distance once. Then count how many references have distance at most each candidate capacity.
For capacity C:
where cold misses have infinite distance.
This produces the hit-rate curve for all capacities from one distance stream. The curve is monotonic: increasing an LRU cache's capacity cannot turn a hit into a miss under the same reference stream and assumptions.
A toy numerical curve#
Suppose a trace contains 100 page references and its distance histogram is:
| Stack distance | References |
|---|---|
| Cold / unseen | 20 |
| 1–2 | 15 |
| 3–4 | 20 |
| 5–8 | 25 |
| 9–16 | 15 |
| Above 16 | 5 |
The cumulative hit-rate curve is:
| Capacity | Hits | Hit rate |
|---|---|---|
| 2 pages | 15 | 15% |
| 4 pages | 35 | 35% |
| 8 pages | 60 | 60% |
| 16 pages | 75 | 75% |
| 32 pages | 80 | 80% |
These numbers are hypothetical, not KVSET measurements. The important signal is the curve's shape. In this example, increasing capacity from 8 to 16 pages gains 15 percentage points, while increasing from 16 to 32 gains only 5. The latter increase may not justify its memory cost for the chosen workload and target.
5. How KVSET computes stack distances efficiently#
Maintaining a literal recency list and searching it for every page reference can be expensive. KVSET uses a Fenwick tree (binary indexed tree) to support efficient prefix-count operations over access positions.
Conceptually:
- Assign each page reference a time position in the trace.
- Track the most recent position of each page identity.
- Mark the previous position inactive when a page is referenced again.
- Mark the current position active.
- Count active positions more recent than the previous reference. That count yields the stack distance under the chosen convention.
- Update the page's latest position.
A Fenwick tree supports point updates and prefix sums in logarithmic time. The resulting computation supports online analysis and offline trace replay without replaying the workload independently for every cache capacity.
The tree is an implementation detail; the conceptual result remains the LRU stack property. The algorithm does not learn a hit-rate predictor from examples and does not need a fitted threshold to calculate the curve.
A deliberately simple conceptual implementation is:
PYTHONdef stack_distances(accesses): recency = [] distances = [] for page in accesses: if page in recency: distance = recency.index(page) + 1 recency.remove(page) else: distance = float("inf") distances.append(distance) recency.insert(0, page) return distances
This is not a production implementation: list search and removal are linear-time. KVSET uses a Fenwick-tree-based approach to avoid repeatedly scanning the entire recency structure.
6. Convert the curve into a working-set capacity#
A cache working set is not one universal number. It is the minimum capacity needed to achieve a chosen target.
For a page-reference hit-rate target h:
If a workload reaches 80% page hit rate at 32 pages but only 75% at 16 pages, then 32 pages is the minimum capacity for an 80% target in that trace.
KVSET also frames capacity around request coverage, which is a different aggregation:
- A request has a theoretical reuse ceiling based on the pages that could be reused if the relevant history were retained.
- For a chosen capacity, some requests preserve all or a target fraction of their possible reuse, while others do not.
- The operator chooses a target fraction of requests to cover, such as 95% or 99%.
- The analyzer estimates the capacity required to reach that request-coverage target.
Do not substitute a global page hit-rate target for a request-coverage target. They answer different questions and can produce very different capacity estimates.
The KVSET paper reports that, for its evaluated production coding-agent trace, approximately 1 TiB and 5 TiB of KV cache corresponded to its 95% and 99% request-coverage targets. Its 99.9% target did not converge within the observed trace. These are workload-specific observations, not sizing recommendations for another service.
7. Use the curve to choose capacity and memory tiers#
Once a capacity curve is available, capacity planning becomes an explicit trade-off rather than a guess.
A practical decision sequence:
- Choose the service objective. Decide whether the target is page hit rate, token hit rate, request coverage, TTFT, or prefill throughput. Do not treat them as equivalent.
- Replay representative traffic. Include realistic prompt lengths, repeated prefixes, tool outputs, multi-turn growth, concurrency, and tenant distribution.
- Build the capacity curve. Estimate hit rate or request coverage over a range of page capacities.
- Translate pages into bytes. Use the actual cache-page footprint for the model, attention layers, KV dtype, and runtime layout.
- Estimate marginal gain. Compare additional cache bytes with the extra reuse gained at each step.
- Choose the physical tier. Decide what belongs in GPU HBM, host DRAM, or storage based on latency, bandwidth, cost, and runtime support.
- Validate with a real deployment. Compare predicted hits with measured cache hits at multiple capacities before a fleet-wide commitment.
- Recompute as traffic changes. Agent histories, prompt templates, model versions, and request mixes can change the working set.
A two-tier design should not assume that a byte in CPU memory has the same performance value as a byte in GPU HBM. The working-set analysis estimates reuse demand under a model; tiering must additionally account for promotion, demotion, transfer latency, bandwidth, and miss cost in each tier.
8. Example: a capacity decision for an agent-serving workload#
Imagine a coding-agent endpoint whose requests repeatedly include a system prompt, tool definitions, conversation history, and new tool results.
A trace replay produces this hypothetical curve:
| KV capacity | Page hit rate | Estimated prefill tokens avoided per second |
|---|---|---|
| 256 GiB | 42% | 1.8 million |
| 512 GiB | 61% | 2.6 million |
| 1 TiB | 75% | 3.1 million |
| 2 TiB | 83% | 3.4 million |
| 4 TiB | 87% | 3.5 million |
These values are illustrative, and the avoided-token estimate is derived from the same hypothetical workload.
Moving from 256 to 512 GiB adds 19 percentage points of page hit rate. Moving from 2 to 4 TiB adds only 4 points. If the additional 2 TiB is expensive or competes with other workloads for host memory, the larger tier may not be justified.
But the page hit-rate curve alone is not a final deployment decision. Ask:
- Are misses concentrated in a few extremely long requests?
- Does extra capacity reduce p95 or p99 TTFT?
- Does prefill compute become the next bottleneck?
- Does a larger cache reduce GPU memory available for active decode KV?
- Are extra hits on the critical path or mostly on requests that are already fast?
- Does the tier increase transfer traffic or queueing?
- Does it improve SLO-compliant goodput and cost per successful request?
The correct capacity is the smallest one that meets the workload's actual service objective with adequate headroom—not necessarily the capacity with the highest hit rate.
9. The assumptions that determine whether the estimate is valid#
The one-pass stack-distance result is mathematically exact for the modeled page-reference stream under LRU. Applying it to a production inference engine requires more care.
LRU semantics. The stack-distance property applies to LRU. A cache using LFU, segmented LRU, priority eviction, session protection, or a custom hybrid policy can retain different pages. Current serving runtimes expose multiple eviction choices. SGLang, for example, documents LRU, LFU, SLRU, priority, and tail-optimized LRU policies. A stack-distance curve computed under pure LRU should not be presented as an exact prediction for a deployment using another policy.
Page-level versus prefix-tree eviction. A radix cache can reclaim eligible leaves or subtrees while preserving shared ancestors. This is not automatically equivalent to a single flat, page-granular LRU cache. The reference stream and simulator must represent the runtime's actual replacement unit and sharing behavior.
Concurrency and event ordering. If the trace reorders concurrent page references, stack distances can change. Capture or reconstruct the interleaving faithfully. A per-request sequence without a valid global ordering may be insufficient for predicting one shared cache.
Pinned and active pages. Pages locked by active requests may not be evictable. A simple LRU reference stream that treats every page as an ordinary candidate can overestimate effectiveness. Model pins, protected pages, in-flight requests, and admission behavior—or explicitly scope the estimate to an idealized cache.
Full-attention assumptions. A token-prefix cache for full causal attention has different reuse requirements from sliding-window attention or recurrent-state models. Some hybrid architectures retain only a recent window for one attention component and a checkpoint for another. Do not map all such state to one undifferentiated KV-page stream.
Workload representativeness. A trace is a sample, not a promise about the future. A launch, new agent tool, prompt-template change, traffic burst, or tenant shift can change locality. Re-run analysis over rolling windows and compare weekday, peak, and burst periods.
10. Validate the model against the actual cache#
A capacity estimator should be treated as a planning model until measured against the serving runtime.
A defensible validation process:
- Capture a production-like request trace with page identities and access ordering.
- Replay the same trace through the analyzer and a reference LRU simulator.
- Compare hit rates at several capacities, not just one point.
- Deploy or configure a test cache at those capacities and measure actual hit rates.
- Explain discrepancies through page granularity, concurrency, pins, cache namespaces, tiering, or eviction policy.
- Report absolute hit-rate error and variability across repeated traces.
- Keep a separate test window to evaluate whether the selected capacity generalizes to later traffic.
The KVSET paper reports that its estimates closely match measurements from Mooncake and SGLang deployments. However, the reported evaluation has limitations: it is based on a production coding-agent trace and selected capacity measurements, and the exact trace-capture protocol and numerical prediction errors are not fully reported. Its empirical results should therefore be read as promising evidence, not a universal guarantee.
The mathematical stack-distance calculation can be exact while the deployment prediction remains approximate because the real cache may not match the modeled assumptions.
11. Common mistakes#
- Sizing to total historical KV. Much historical state may never be reused. Capacity should be based on reuse demand and an explicit target.
- Reporting one hit-rate number. A curve shows diminishing returns and helps compare capacity choices.
- Confusing request and page hit rates. Always state the numerator and denominator.
- Assuming hit rate equals latency improvement. Prefill savings depend on token lengths, batching, attention cost, and the bottleneck at the time of a hit.
- Ignoring active decode memory. More retained prefix KV can compete with memory needed for active sequences.
- Using an LRU estimator for a non-LRU policy. Replacement semantics are part of the model.
- Replaying requests in the wrong order. Interleaving changes reuse distance.
- Treating a short trace as a stable forecast. Use rolling traces and sensitivity analysis.
- Provisioning to 100% reuse. Rare, one-off histories can make required capacity enormous for little incremental benefit.
- Ignoring cost by tier. GPU, CPU, and storage capacity have different costs and access latencies.
12. Production rollout checklist#
- [ ] Identify the actual cache replacement policy and eviction unit.
- [ ] Capture page-level references in the real observed order.
- [ ] Record prompt, prefix, request, tenant, and model-version metadata without exposing sensitive content.
- [ ] Separate cold misses from evictions and invalidations.
- [ ] Compute a capacity curve over a useful range.
- [ ] Choose explicit page-hit, token-hit, or request-coverage objectives.
- [ ] Translate page counts into actual bytes for each KV layout.
- [ ] Compare predicted and measured hits at multiple capacities.
- [ ] Track TTFT, prefill throughput, p95/p99 latency, GPU memory pressure, and SLO-compliant goodput.
- [ ] Re-run analysis after meaningful workload, model, or serving-policy changes.
- [ ] Keep capacity headroom for bursts, active requests, and failover.
- [ ] Record the trace window and assumptions alongside the capacity recommendation.
Interview-ready summary#
KVSET sizes an LLM prefix cache by converting a workload into a KV-page reference stream and computing each page's LRU stack distance. Under page-granular LRU, an access is a hit at capacity C exactly when its stack distance is at most C. The Mattson stack algorithm therefore derives hit rates for many capacities from one pass, and a Fenwick tree makes the distance calculation efficient. An operator can choose a target hit rate or request-coverage objective, read off the minimum capacity, and translate pages into bytes for GPU, CPU, or storage tiers. The result is exact for the modeled LRU stream, but production accuracy depends on faithful trace ordering, page mapping, eviction semantics, concurrency, and workload representativeness.
References
- 1.
- 2.Evaluation Techniques for Storage Hierarchiesdomino.research.ibm.com
- 3.SGLang Radix Cache Eviction Policiesgithub.com
- 4.Mooncake KV Cache Sharing and Isolationgithub.com
- 5.Pith review of KVSETpith.science
Related questions
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents