LLM Inference KV Cache: Memory Sizing and Cache Hit Optimization
Learn how KV caching reduces repeated computation during LLM inference, how to estimate its GPU memory footprint, and how prefix reuse affects latency and throughput. This article explains cache hit metrics, practical optimization steps, and capacity planning without relying on a specific model or pricing scheme.
Inference cost is often driven less by parameter count alone than by how much historical state must be recomputed or retained in GPU memory during autoregressive decoding. A key-value cache, or KV cache, stores previously computed attention keys and values so that subsequent steps only need to process the new token.
High cache reuse means many requests share or continue the same prefix, spreading computation across requests. Low reuse means repeatedly paying to process nearly identical context. Understanding the generation process, memory requirements, sources of cache hits, and capacity management makes it easier to plan inference infrastructure without tying the analysis to a particular model or billing scheme.
What Gets Recomputed Without a KV Cache?
Text generation is autoregressive: each step produces one token, appends it to the context, and then proceeds to the next step. Attention constructs a query (Q), key (K), and value (V) for each token.
Suppose a prompt produces a new token in the first step. In the second step, the input consists of the original prompt plus that token. Without caching, the model recomputes the keys and values for the earlier tokens, even though those values have not changed. The longer the sequence, the more work is repeated. At step t, attention must scan roughly t existing positions; even the cumulative attention work for incremental generation grows quadratically with sequence length.
With KV caching, each token’s keys and values are stored in GPU memory by layer and head as soon as they are computed. At the next step, the model computes Q, K, and V only for the new token. It then applies the new query to all historical keys and uses the resulting attention weights to combine the stored values.
Historical keys and values no longer need to be recomputed through the model. The main work at each step shifts from processing the entire sequence to processing the latest token, reading the cache, and computing attention over it. The initial prompt still requires a full prefill pass; the savings primarily apply to subsequent decoding steps.
How to Estimate KV Cache Memory
A standard approximation is:
KV cache bytes ≈ 2 × number of layers × number of KV heads× head dimension × sequence length × bytes per element
The factor of two accounts for separate K and V tensors. For grouped-query attention, use the number of key-value heads, not the number of query heads. Using query heads would overestimate the cache size.
Consider this illustrative configuration:
- 32 layers
- 32 key-value heads
- Head dimension of 128
- Sequence length of 4,096 tokens
- Half-precision storage at 2 bytes per element
The keys and values for one token in one layer require:
2 × 32 × 128 × 2 = 16,384 bytes = 16 KiB
Multiplying by the layer count and sequence length gives:
16 KiB × 32 × 4,096 = 2 GiB
That is the approximate cache footprint for one sequence. A batch of 10 sequences, all at the full length, requires about 20 GiB before accounting for model parameters, activations, and framework overhead.
With long contexts or high concurrency, the cache can become a memory bottleneck before model parameters do. Estimates also need to account for implementation details:
- Page- or block-aligned allocation can introduce fragmentation.
- Reserving the maximum length for every sequence wastes memory when sequence lengths differ.
- Sliding-window attention or caching only some layers can reduce the footprint below the full-cache estimate.
The formula is useful for order-of-magnitude planning, but it does not replace actual runtime allocation measurements.
What Does Cache Hit Rate Measure?
Within a single conversation, avoiding repeated computation of historical state is the basic benefit of KV caching. During decoding, a request normally reuses its own past keys and values.
When engineers discuss a high cache hit rate, however, they often mean cross-request prefix reuse. Multiple requests may share the same system prompt, tool definitions, document prefix, or conversation history. The prefix’s keys and values can be computed or loaded once, with subsequent requests continuing from a particular token position.
An intuitive measure is the share of historical tokens used by attention that come from an existing cache rather than being recomputed. For operational analysis, it is important to distinguish ordinary within-request reuse from cross-request prefix hits.
The level of reuse can vary substantially:
- No prefix reuse: The request benefits from incremental caching during decoding, but every long prompt still requires a complete prefill.
- Stable system prompt: Hundreds or thousands of initial tokens may be reusable. For short question-and-answer requests, this can represent a large share of the context.
- Shared long document or continued conversation: Hits may cover most of the context, allowing prefill work to be spread across many requests.
- Changed prefix: Insertions, edits, deletions, or inconsistent tokenization can invalidate the cache after the changed position and sharply reduce reuse.
A high hit rate is not an unexplained improvement in model efficiency. It depends on stable prefixes, consistent tokenization, and cached state remaining available. The engineering goal is to turn repeated prefill from a fixed cost for every request into a one-time cost shared across requests.
How Cache Hits Affect Speed and Cost
Prefill computation increases with prompt length. During decoding, each step reads an increasingly long cache.
When prefix reuse is high, much of the expensive prefill work can be skipped. Time to first token falls, and the same accelerator can support more concurrent decoding work. The underlying cost per request can decrease because:
- Repeated tokens no longer require the same amount of computation.
- One cached prefix in memory can serve multiple requests, improving memory utilization and throughput.
How those savings appear in token-based or time-based billing depends on the pricing scheme.
With low prefix reuse, each request must process the long prompt again. Prefix state may also be duplicated across requests, filling GPU memory sooner, limiting batch size, and increasing queueing.
Improving cache reuse is therefore both a computation problem and a traffic-management problem. Prompts need shareable prefixes, and requests should be routed to the device or memory tier that still holds the relevant cache.
Improving Hit Rate and Managing Capacity
The following steps do not depend on any vendor-specific API.
Keep reusable prefixes stable. Place system instructions, tool definitions, and unchanged retrieval results at the beginning of the prompt. Put request-specific content afterward. Changing a token near the beginning requires rebuilding the cache from that point onward.
Keep tokenization consistent. The same text must produce the same token sequence. Identical text does not guarantee reuse if it is tokenized differently.
Store prefixes in reusable cache blocks. Use a content hash to look up a prefix. On a hit, attach the new request to the existing prefix blocks and continue from there. On a miss, compute and store the prefix state.
Use paged or block-based memory management. Allocate and evict by block instead of reserving the maximum sequence length for every request. Eviction should favor retaining hot prefixes likely to be continued, rather than relying only on recency.
Balance precision, context length, and concurrency. Lower cache precision, fewer key-value heads, sliding windows, or caching only selected layers can reduce per-sequence memory use. This leaves room for more resident prefixes and can indirectly improve hit rates. These choices can alter numerical behavior or retained attention context, so validate quality on representative workloads rather than judging memory savings alone.
Track separate metrics. Monitor prefix hit rate, prefill token count, decode token count, cache bytes, eviction count, and queueing latency. Average latency alone can hide repeated processing of long prompts.
The following pseudocode illustrates the logic without relying on a specific framework:
key = hash(prefix_tokens)if cache.exists(key):kv = cache.attach(key) # Reuse historical K and Vstart = len(prefix_tokens)else:kv = model.prefill(prefix_tokens)cache.insert(key, kv)start = len(prefix_tokens)for token in decode_from(start):kv.append(model.step(token, kv))
Capacity Planning: What to Check First
Start by estimating the cache footprint of one sequence at its maximum intended length. Multiply that by the target concurrency, then leave headroom for model parameters and activations.
If the total exceeds available GPU memory, prioritize shortening non-reusable prompts, sharing identical prefixes, or considering configurations with fewer key-value heads or lower cache precision. Increasing batch size is not a remedy: cache memory grows approximately linearly with the number of active sequences.
In a multi-GPU deployment, also consider whether cached state must move with the request. Copying K and V across devices can offset the benefit of a cache hit. Scheduling should, where possible, send continuations back to the device holding the relevant prefix.
Host memory or object storage can hold evicted, cold prefixes. However, loading and deserialization must take less time than recomputing the prefill. Otherwise, a nominal cache hit merely replaces computation with slower I/O.
A practical hierarchy is:
- Hot prefixes: Keep them in accelerator memory.
- Warm prefixes: Keep them in host memory.
- Cold prefixes: Move them to external storage.
This tiered approach is more useful than maximizing the nominal hit rate without considering retrieval cost.
Conclusion
KV caching replaces repeated computation of unchanged keys and values with memory reads. Its size depends on layer count, key-value head count, head dimension, sequence length, and storage precision, and grows approximately linearly with batch size.
The most valuable cache hits often come from reusing stable prefixes across requests. This spreads prefill work across multiple requests and allows one copy of cached state to support more decoding.
Achieving that requires stable prompts, consistent tokenization, block-based storage, and observable eviction behavior—not merely enabling caching within a single generation. Combining memory estimates with separate measurements of prefix reuse and decoding reuse helps identify whether a long-context workload is limited by computation, GPU memory, or a lack of effective prefix sharing.
