KV Cache Optimization for LLM Inference: The Key to Lower Costs

    This article explains why large language model inference prices are falling and how KV Cache optimization makes those reductions sustainable. It breaks down the cost structure of inference, introduces KV Cache and the autoregressive generation process behind it, and shows how to estimate its GPU memory footprint. You will learn why cache hit rate is the core metric, get a practical optimization checklist covering prefix stability, paging, quantization, scheduling, and observability, and see how to run capacity and cost evaluations on the cloud.

    1. Behind the Price Drop: A Cost Structure Explanation

    The industry has recently seen large, permanent cuts to LLM inference service prices. Many developers assume these are promotions, but breaking down the bill shows the drop is not a subsidy. It is the result of engineering work pushing down the cost of serving each token. LLM inference cost comes from three main areas: GPU memory usage (which determines how many requests a single card can serve concurrently), compute usage (which determines the floating-point operations per token), and data movement bandwidth (which determines whether memory access becomes the bottleneck). Memory usage and memory access are both closely tied to caching strategy. When the cache hit rate rises, repeated prefix computation is skipped, effective compute drops, and the concurrency a single card can handle increases. The price per token can then keep falling. So whether a price cut is sustainable depends on whether it is backed by reusable structural optimization rather than a one-time concession.

    2. What Is KV Cache: Starting from Autoregressive Generation

    Text generation is an autoregressive process: it produces one token at a time, then appends it to the sequence and continues. In the attention mechanism, each token produces three vectors: Q (query), K (key), and V (value). Without caching, generating the second token requires recomputing the K and V of every previous token, even though those results are identical to the first step. That is pure duplicated work.

    The core idea of KV Cache is simple: after computing a token, keep its K and V in GPU memory. Later inference only computes Q, K, and V for the newest token, scores attention between the new Q and all cached K, then weights the cached V. Per-step computation drops from “process the whole sequence” to “process one token.” Complexity shifts from quadratic growth tied to sequence length to linear accumulation, with especially clear gains for long-text scenarios.

    Illustrative pseudocode:

    1. # No cache: recompute the full sequence at every step
    2. for step in range(max_len):
    3. q, k, v = model(input_ids) # full-sequence forward pass
    4. next_token = sample(q[:, -1], k, v)
    5. # With cache: reuse historical K/V
    6. cache = empty_kv_cache()
    7. for step in range(max_len):
    8. q, k, v = model(last_token, cache) # forward pass for the new token only
    9. cache.append(k, v) # append to the cache
    10. next_token = sample(q, cache)

    3. Accounting for GPU Memory: Estimating KV Cache Size

    Caching is not free; it consumes GPU memory. The general estimation formula is:

    KV Cache ≈ 2 × number of layers × number of attention heads × per-head dimension × sequence length × bytes per precision

    Take 32 layers, 32 heads, 128 dimensions per head, and FP16 (2 bytes) as an example: a single token in a single layer is 2 × 32 × 128 × 2 = 16384 bytes, or 16KB. At a sequence length of 4096, that is about 2GB; with 10 concurrent requests, about 20GB. This is on par with the model weights, showing that in long-context and high-concurrency scenarios, the memory bottleneck often comes from the cache rather than the parameters. In practice, paged cache management is commonly used: the cache is split into fixed-size blocks allocated on demand to reduce fragmentation and reserved waste. Combined with prefix sharing, multiple requests with the same system prompt can reuse the same cache.

    4. Why Hit Rate Is the Core Metric

    Cache hit rate is the proportion of prefix tokens in a request that can be reused. In real workloads, system prompts, tool definitions, few-shot examples, and long document bodies often stay completely unchanged across calls, so a near-full hit rate is achievable. The benefits are twofold: first, repeated forward computation is skipped, reducing compute consumption; second, time to first token drops significantly because the entire long prefix does not need to be read again. When evaluating cost efficiency, look at hit rate, time to first token, and cost per thousand tokens together, rather than focusing only on unit price.

    5. A Practical Optimization Checklist

    • Prefix stabilization: place invariant content first and variable content last, so a small change in one place does not invalidate the entire cache.
    • Cache paging and eviction: use block-level allocation and a sensible eviction policy to balance fragmentation and reuse.
    • Precision and quantization: store the cache at lower bit widths within an acceptable precision range to reduce GPU memory usage linearly.
    • Batching and scheduling: aggregate long-prefix requests in scheduling to increase block reuse probability.
    • Observability: collect hit rate, memory watermark, and queue time through logging services and monitoring alerts to close the loop on capacity planning.

    6. Capacity and Cost Evaluation on the Cloud

    When deploying inference on a platform such as Baidu AI Cloud, you can first build the foundation with general-purpose capabilities: a container platform to host inference services, object storage for models and corpora, a message queue to smooth request spikes, and logging and monitoring for metric collection. For capacity planning, estimate peak GPU memory with the formula above, then apply a safety factor. For cost evaluation, treat hit rate as an adjustable variable in a sensitivity analysis to see the actual impact of a lower unit price on the total bill. Conclusions reached this way are reproducible rather than driven by a single price change.

    7. Conclusion

    The essence of continuously falling inference prices is turning repeated computation into reusable cache. For developers, what matters is not the size of any single price cut but the engineering methodology behind the cache hit rate: account for GPU memory, stabilize prefix structure, make good use of paging and quantization, and build an observability loop. Do these, and you can keep the cost per token in a reasonable range regardless of price fluctuations.