How KV Cache Affects LLM Inference Cost and Cache Hit Rate

    KV caching is central to LLM inference efficiency and cost. This article explains why autoregressive generation needs KV cache, how to estimate its GPU memory footprint, why memory becomes a bottleneck with long contexts and high concurrency, and how prefix caching improves cache hit rates and reduces costs. It also covers common engineering optimizations such as GQA, KV cache quantization, paged memory management, and sliding-window attention, plus practical guidance for evaluating pricing changes and planning deployments.

    1. Why Generation Needs KV Cache

    Large language models generate text autoregressively: they produce one token at a time, append it to the end of the input sequence, and then generate the next token.

    Suppose the input is “The weather today” and the model first outputs “is”. The input then becomes “The weather today is”, and the model outputs “nice”. If every step reprocessed the entire sequence from scratch, the Key (K) and Value (V) vectors of historical tokens like “The” and “weather” would be recomputed over and over. These vectors depend only on the historical tokens themselves, so the results would be identical to what was already computed in the previous step.

    The idea behind KV cache is straightforward. Once a token produces its K and V at a given layer, those vectors are stored in GPU memory. At the next generation step, the cached K and V of historical tokens are read directly; only the new token’s Query (Q), K, and V need to be computed. The new Q then computes attention scores against all cached K, and those scores weight the cached V.

    In this way, the projection computation per step drops from “processing the entire sequence” to “processing a single new token”. The attention computation itself still has to read the full history cache, so per-step cost still grows with sequence length, but a large amount of redundant matrix computation is avoided.

    2. How to Estimate KV Cache Memory Usage

    The GPU memory occupied by KV cache can be estimated with the following formula:

    KV cache size = 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element

    The factor of 2 accounts for storing one copy each of K and V. With FP16, each element takes 2 bytes.

    Take a hypothetical model as an example: 32 layers, 32 attention heads, head dimension of 128, sequence length of 4096, using FP16.

    • The KV size of a single token at one layer: 2 × 32 × 128 × 2 = 16,384 bytes, or 16 KB.
    • The KV size of a single token across all 32 layers: 16 KB × 32 = 512 KB.
    • A sequence of length 4096 occupies: 512 KB × 4096 = 2 GB.
    • If 10 such sequences are processed concurrently (batch size of 10), the total is roughly 20 GB.

    This figure does not include the model parameters themselves. Model weights have a fixed size once loaded, whereas KV cache grows linearly with batch size and sequence length.

    3. Why GPU Memory Becomes the Bottleneck

    The example above shows that even a short sequence already requires nearly 2 GB of cache. If the sequence length is raised to 131,072 (about 128K) tokens, a single sequence under the same configuration needs 512 KB × 131,072 = 64 GB of cache — a magnitude that can exceed the model weights themselves.

    The bottleneck mainly comes from three sources.

    First, long context. The longer the input document, the larger the cache, and it keeps growing as generation continues.
    Second, high concurrency. The more requests a server processes simultaneously, the larger the total cache.
    Third, memory fragmentation. Different requests have different generation lengths and finish at different times. With contiguous memory allocation, this easily produces large amounts of unusable fragmented memory.

    As a result, the design goals of an inference system often go beyond raw compute speed: they include fitting as many concurrent requests as possible and minimizing wasted memory.

    4. From Memory Optimization to Cache Hits

    When multiple requests share the same prefix, the server can compute that prefix’s KV once, keep it, and let subsequent requests reuse it directly. Such prefixes include system prompts, long documents, few-shot examples, tool definitions, and the history of multi-turn conversations.

    Cache hits bring three benefits.

    1. Computation in the prefill phase drops, shortening time to first token.
    2. Only one copy of the shared prefix is kept in memory, increasing concurrency capacity.
    3. A common industry practice is to price cached input tokens lower, so invocation cost decreases.

    The cache hit rate can be defined as:

    Hit rate = number of cached input tokens ÷ total number of input tokens

    The following sample function estimates input cost with cache pricing; the price units are set by the caller:

    1. def estimate_input_cost(total_tokens, cached_tokens,
    2. price_full, price_cached,
    3. unit_tokens=1_000_000):
    4. """
    5. total_tokens: total number of input tokens
    6. cached_tokens: number of tokens that hit the cache
    7. price_full: unit price for uncached tokens (per unit_tokens tokens)
    8. price_cached: unit price for cached tokens (per unit_tokens tokens)
    9. """
    10. if total_tokens == 0:
    11. return 0.0, 0.0
    12. hit_rate = cached_tokens / total_tokens
    13. uncached = total_tokens - cached_tokens
    14. cost = (cached_tokens * price_cached + uncached * price_full) / unit_tokens
    15. return hit_rate, cost
    16. rate, cost = estimate_input_cost(
    17. total_tokens=2_000_000,
    18. cached_tokens=1_200_000,
    19. price_full=1.0,
    20. price_cached=0.2,
    21. )
    22. print(f"Hit rate: {rate:.0%}, input cost: {cost:.2f}")

    The key to improving the hit rate lies in prompt structure.

    1. Put stable content first — system instructions, tool definitions, and a fixed knowledge base — and place the user input that changes every time at the end.
    2. Avoid inserting timestamps, random IDs, or differently ordered results into the prefix. Changing even a single character in the prefix invalidates all cache after that point.
    3. In multi-turn conversations, keep the order and formatting of historical messages consistent; do not reorder or rewrite old messages arbitrarily.
    4. Use the same prefix template for requests from the same business scenario so the server can recognize and reuse it.

    5. How to Rationally Evaluate a Price Change

    Price change announcements usually only state unit prices, but actual cost depends on other factors as well. When evaluating, check at least the following dimensions.

    1. Base unit prices: the prices for input and output respectively, and the ratio between them.
    2. Cache pricing rules: hit conditions, cache validity period, minimum prefix length, and the discount applied to the cached portion.
    3. Effective unit price: total spend divided by useful output, counting retries, overlong responses, and invalid generations.
    4. Context length limits and rate limits: if usable context or concurrency quotas tighten after a price drop, the actual benefit is discounted.
    5. Stability and latency: no matter how low the cost, if instability increases retries, total cost may still rise.

    Here is a hypothetical scenario to illustrate the calculation. Let the original input unit price be P, the cache hit rate be h, and the discount on the cached portion relative to the original price be d. The effective input cost is approximately:

    Effective input cost = P × (1 − h × d)

    If h is 0.4 and d is 0.8, the effective input cost is P × 0.68, equivalent to 32% below the original price. These numbers are for demonstration only and do not represent the pricing of any specific service. The key point is that the hit rate of your workload often determines the final benefit, not the list price itself.

    6. Common Engineering Techniques to Reduce Memory and Cost

    Beyond improving the hit rate, you can start from model architecture and deployment strategy.

    1. Reduce the number of KV heads. Grouped-query attention (GQA) lets multiple query heads share fewer K and V heads. Cutting KV heads from 32 to 8 reduces the cache to a quarter of its original size. Multi-query attention (MQA) is the extreme form of this approach.
    2. Quantize the KV cache. Quantizing the cache from FP16 to INT8 halves memory usage, at the cost of possibly slight accuracy loss, which should be validated on an evaluation set.
    3. Paged cache management. Split the cache into fixed-size blocks allocated on demand, reducing fragmentation caused by varying sequence lengths and improving memory utilization.
    4. Sliding-window attention. Keep only the KV of the most recent window; history beyond the window is no longer cached. This caps memory usage but loses long-range information, making it suitable for scenarios with low long-range dependency requirements.
    5. Set a reasonable maximum generation length. The generation length cap directly determines the worst-case memory usage of a single request and also affects concurrency planning.

    7. Practical Recommendations

    In real projects, you can proceed in the following order. First, use the formula above to estimate the memory requirement of your target model at your target context length and concurrency. Next, analyze prefix duplication across your business requests to estimate the potential hit rate. Then adjust your prompt templates to move stable content to the front, and record hit data for every call. Finally, use the effective unit price rather than the list price as the comparison baseline when deciding whether to migrate or adjust your service plan.