KV Cache Optimization: How Prefix Cache Hits Reduce LLM Inference Costs

    KV caching reduces repeated computation during large language model inference, while prefix caching extends those savings across requests. This article explains how cache hits can lower inference costs, what KV caches consume in GPU memory, and how developers can structure prompts and evaluate pricing to benefit from caching.

    Recent announcements of permanent price cuts for large language model inference services—including reductions to a quarter of previous prices—have prompted discussions about another cloud pricing war. But competition is not the only possible explanation. Improvements in inference efficiency can also create room for lower prices.

    An important factor is cache reuse. After a service has handled substantial production traffic, operators can identify workloads with highly repetitive inputs. For some request patterns, cache hit rates may approach 99%, substantially reducing the marginal cost of processing repeated input.

    That does not mean every price cut can be attributed to caching. It does explain how mature inference infrastructure can translate technical efficiency into lower prices. To understand the connection, we need to distinguish ordinary KV caching during generation from prefix reuse across requests.

    1. Autoregressive Generation Without Caching

    Language models generate text autoregressively: they predict one token, append it to the existing sequence, and then predict the next token.

    For example, using simplified text fragments rather than an exact tokenizer output:

    • First, the model receives “The weather” and predicts “is.”
    • Next, it receives “The weather is” and predicts “nice.”
    • Then it receives “The weather is nice” and predicts another token.

    In a transformer, attention uses three vectors for each token at each layer: Q, or query; K, or key; and V, or value.

    Without caching, each generation step processes the growing sequence again. That repeats calculations for earlier tokens even though their key and value states remain unchanged under causal attention.

    For example, when processing “The weather is,” the model would recompute the K and V states for the existing prefix, “The weather.” Those states were already calculated in the previous step. As the sequence grows, the amount of repeated work grows with it.

    2. KV Cache: Trading GPU Memory for Computation

    KV caching avoids this repetition by storing the key and value states of processed tokens in GPU memory.

    During subsequent generation steps, the model reads historical K and V states from the cache instead of recomputing them. It calculates Q, K, and V for the newly processed token, adds the new K and V states to the cache, and uses the new query to attend over the cached keys and values.

    1. # Simplified pseudocode
    2. new_q, new_k, new_v = proj(token) # Compute only the new token
    3. kv_cache.append(new_k, new_v) # Append its key and value
    4. attn_out = softmax(new_q @ cache.K.T) @ cache.V

    The model no longer needs to run the full sequence through every layer at each generation step. However, the new token’s attention still reads the historical keys and values, so the cost of attending to the context does not disappear.

    The core trade-off is straightforward: KV caching uses GPU memory to save computation time.

    3. Why Cache Hits Can Translate into Lower Prices

    Ordinary KV caching reuses states within a generation sequence. Prefix caching extends that idea across requests.

    Long conversations and document-processing workloads often contain large, repeated prefixes, such as:

    • A fixed system prompt
    • Reusable document context
    • Historical messages from a multi-turn conversation

    If an inference platform retains the KV states for an identical prefix, later requests can reuse them rather than process those input tokens again. This greatly reduces the repeated prefix-processing cost, although cache storage, lookup, and reading still carry overhead. Generating the response also continues to require computation.

    Many inference services therefore charge cached input tokens at a lower rate than uncached input tokens. Depending on the service, the cached-input rate can be much lower.

    When workloads are highly repetitive—for example, many requests use the same system prompt and document prefix—the average input-processing cost can fall substantially. Similar documents alone are not enough: prefix reuse depends on matching prefixes, not merely related content.

    This helps explain why efficiency-driven price reductions may follow a period of real-world usage. Production traffic reveals how much input can actually be reused and whether the resulting savings are sustained.

    From an engineering perspective, effective cache reuse usually depends on several capabilities:

    1. Prefix caching: Identify identical prefixes and retain their KV states for subsequent requests.
    2. Cache eviction: Manage limited GPU memory with policies such as least recently used, or LRU, eviction.
    3. Request routing: Send requests to nodes that hold the relevant cache; otherwise, a reusable prefix may still miss.
    4. Transparent cache billing: Show cached and uncached token usage so developers can measure the financial benefit.

    4. How Much GPU Memory Does a KV Cache Use?

    Caching is not free. Its main resource cost is memory.

    A basic estimate for KV cache size is:

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

    The factor of two accounts for both keys and values. In conventional multi-head attention, the number of KV heads matches the number of query heads. With multi-query or grouped-query attention, fewer KV heads reduce the cache size.

    Consider a model with:

    • 32 layers
    • 32 KV heads
    • A head dimension of 128
    • A sequence length of 4,096 tokens
    • FP16 storage, using 2 bytes per element

    The cache required per token per layer is:

    1. 2 × 32 × 128 × 2 = 16,384 bytes = 16 KiB

    Across all layers and tokens:

    1. 16 KiB × 32 layers × 4,096 tokens = 2 GiB

    Ten concurrent sequences of this length would require approximately 20 GiB for their KV caches alone, before accounting for model weights and other memory usage.

    For long-context or large-batch workloads, the KV cache can consume more memory than the model weights and become a central bottleneck in the inference system.

    Several approaches address this pressure:

    • KV cache quantization: Store keys and values in INT8 or INT4 instead of FP16, reducing their nominal storage requirements to one-half or one-quarter.
    • Multi-query attention and grouped-query attention (MQA/GQA): Share KV heads across multiple query heads, reducing the number of states that must be stored.
    • Sliding-window attention: Retain only a recent window of tokens, trading access to more distant context for lower memory usage.
    • Cache offloading: Move cold cache entries to system memory or fast storage and load them back into GPU memory when needed.

    5. Practical Lessons for Developers

    Understanding cache behavior can help developers reduce API costs and make better infrastructure decisions.

    Keep Reusable Prefixes Stable

    Place fixed content—such as system instructions, role definitions, and reusable document context—at the beginning of the input, and keep it consistent across requests.

    Putting changing content, such as a timestamp, at the start of every prompt can prevent reuse of the prefix that follows. Stable prompt templates make cache hits more likely.

    Avoid Unnecessary Context

    Not every previous conversation turn needs to be included in every request. Trimming irrelevant history or summarizing older exchanges can reduce input charges and cache memory requirements.

    Caching makes repeated context cheaper to process; it does not make unlimited context free.

    Evaluate Cache-Aware Pricing

    When comparing inference services, look beyond the headline input-token price. Check whether the provider offers:

    • Separate rates for cached and uncached input
    • Cache-hit usage statistics
    • Billing information that makes cache savings visible

    Cloud providers, including Baidu AI Cloud, continue to optimize inference infrastructure. The practical benefit should be evaluated against your own request patterns and the service’s applicable billing structure, rather than inferred from its advertised price alone.

    Compare Self-Hosted and Managed Inference

    Highly uniform workloads, such as question answering over a shared knowledge base, can benefit substantially from a managed service’s prefix caching.

    For workloads with widely varying inputs and naturally low cache hit rates, cache-related discounts may have a smaller effect. Decisions about self-hosted versus managed inference should therefore use workload-specific cost estimates, not assume that every request will benefit equally.

    6. Conclusion

    Lower LLM inference prices can reflect more than commercial competition. KV cache reuse, prefix-cache optimization, attention architecture improvements, and cache quantization can all reduce the cost of serving requests.

    The key distinction is between avoiding repeated work during generation and reusing identical prefixes across separate requests. Together, these techniques can create substantial savings, especially for repetitive workloads.

    For developers, the practical takeaway is to design stable prompts, limit unnecessary context, and measure cached versus uncached usage. Understanding how caching works makes it easier to choose an inference service—and to structure applications so that infrastructure improvements translate into lower costs.