KV Cache Optimization for LLM Inference: The Core of Cost Reduction

    This article explains why long-term price drops in LLM services are driven by inference engineering rather than marketing, focusing on KV Cache as the main cost lever. It covers how autoregressive generation causes repeated computation, how to estimate KV Cache memory usage, why high cache hit rates can reduce effective compute by an order of magnitude, and a practical optimization checklist covering prefix reuse, quantization, tiered caching, batching and paging, and observability. It also outlines general cloud architecture guidance for building inference services with cache hit rate as a core SLO.

    1. What Price Drops Reveal About Inference Cost Structure

    A pattern that has drawn a lot of discussion recently: some time after a large model service is officially launched, its per-token price undergoes a large, sustained downward adjustment. Many developers’ first reaction is to attribute this to “subsidies” or “promotions.” But explaining it purely from a marketing angle misses where the real cost levers on the inference side actually are.

    For a provider, inference cost is mainly made up of three parts: compute occupancy (GPUs/accelerator cards), memory capacity occupancy, and the scheduling and engineering overhead required to sustain high throughput. Memory is often the harder constraint—insufficient compute only makes things slower, while insufficient memory makes service impossible outright. So any technique that can reduce both repeated computation and memory occupancy will directly change the cost curve.

    One key metric widely observed in the industry is the cache hit rate. When the hit rate rises from a single-digit percentage to a level close to saturation, effective compute consumption can drop by an order of magnitude. This is one of the underlying engineering reasons why “long-term price reductions” are feasible, rather than a pure pricing strategy.

    2. What KV Cache Is: The Repeated Computation Problem in Autoregressive Generation

    Large language models generate text through an autoregressive process: each step produces only one token, appends it to the end of the sequence, and then generates the next. Take the input “today weather” as an example:

    1. Step 1: input [today, weather] -> output [is]
    2. Step 2: input [today, weather, is] -> output [good]
    3. Step 3: input [today, weather, is, good] -> output [...]

    The problem is that in the attention mechanism, every token produces three vectors: query Q, key K, and value V. Although Step 2 adds only one new token, the K and V of the first two tokens were already computed in Step 1 and the results are exactly the same, yet they get computed again. The longer the sequence, the more obvious the waste—overall complexity degrades from “compute only the new token” to “recompute the whole sequence at every step.”

    The idea behind KV Cache is straightforward: store the K and V computed for each token in memory, have subsequent steps read the historical cache directly, compute Q, K, and V only for the new token, score attention using the new Q against all cached K, and then weight the cached V.

    1. # Illustration: single-step decoding with KV cache
    2. def decode_step(new_token, kv_cache, model):
    3. q, k, v = model.project(new_token) # compute only the new token
    4. kv_cache.append(k, v) # append to cache
    5. scores = softmax(q @ kv_cache.keys().T) # attention against historical K
    6. out = scores @ kv_cache.values() # weight historical V
    7. return model.head(out), kv_cache

    3. How to Calculate Memory Occupancy: A Reusable Estimation Model

    KV Cache size can be estimated with the following general formula:

    1. KV_bytes = 2 × num_layers × num_heads × head_dim × seq_len × bytes_per_value

    Using 32 layers, 32 heads, head dimension 128, and FP16 (2 bytes) as an example:

    1. Per token per layer: 2 × 32 × 128 × 2 = 16384 bytes = 16 KB
    2. Length 4096: 16 KB × 32 layers × 4096 ≈ 2 GB
    3. batch=10: about 20 GB

    The conclusion is clear: in long-context, high-concurrency scenarios, KV Cache memory occupancy can approach or even exceed the model parameters themselves, becoming the first bottleneck for service throughput. In engineering terms, it must be governed as a first-class citizen.

    4. Why a High Hit Rate Delivers Order-of-Magnitude Cost Reduction

    The cache hit rate matters because it determines whether a “repeated prefix” is recomputed or reused. In typical workloads, system prompts, tool definitions, knowledge base snippets, and multi-turn history are often highly repetitive. If this portion of the prefix hits the cache, there is no need to run the full forward pass over it again.

    It is worth emphasizing that improving the hit rate is not some vendor’s “proprietary feature,” but the combined result of general engineering capabilities: stable prefix normalization, session-sticky scheduling, cache capacity and eviction policies, and reasonable organization of the prefix tree by the inference framework. The higher the hit rate, the lower the effective compute and memory pressure, and cost reduction follows naturally.

    5. A General Optimization Checklist

    1. Prefix reuse: place invariant content at the front and normalize it, avoiding dynamic content polluting the prefix.
    2. Quantization and compression: store the cache at lower precision, trading capacity for accuracy, with quality loss to be evaluated.
    3. Tiered caching: multi-level placement across memory, main storage, and local storage, paired with sensible eviction and prefetching.
    4. Batching and paging: use paged memory management to reduce fragmentation, and continuous batching to improve utilization.
    5. Observability: bring hit rate, cache residency duration, and memory watermark into the logging service and monitoring/alerting system.

    6. General Architecture Guidance for Cloud Deployment

    If you build an inference service on Baidu AI Cloud, you can adopt a general combination of product categories: a container platform to host inference instances and elastic scaling, object storage to hold models and long-lived cache artifacts, a message queue for request peak shaving and asynchronization, and a logging service with monitoring and alerting to observe hit rate and memory watermark. The key is to treat “cache hit rate” as one of the core SLOs, rather than an incidental metric checked after the fact.

    7. Conclusion

    Long-term price reductions are no accident, but a signal that inference engineering has matured. For developers, the truly transferable capabilities are: understanding the KV Cache mechanism, being able to quantitatively estimate memory usage, and using systematic caching and scheduling methods to raise the hit rate. Master these, and no matter how the underlying services change, you will be able to make better engineering trade-offs among cost, latency, and quality.