KV Cache Optimization: The Core of Cutting LLM Inference Costs

    This article explains why KV Cache optimization is central to reducing large language model inference costs. It covers the structural shift in pricing driven by engineering improvements, why autoregressive generation repeats computation, how KV Cache works, how to estimate its memory footprint, why cache hit rates can be high, mainstream optimization paths, and practical metrics for evaluating whether a price reduction is sustainable.

    1. Reading the Structural Shift in Inference Costs from Price Cuts

    The price of a large model service is not an arbitrary number. It reflects the real resource cost per token. When a model service announces something like a “permanent price cut to one quarter of the original price,” it is usually not a marketing move but the inevitable result of accumulated engineering optimization on the inference side reaching a certain threshold. To judge whether such a price cut is reasonable and sustainable, you first need to answer a more fundamental question: what does a single text generation actually consume?

    The answer comes down to two things: compute (GPU matrix multiplication throughput) and memory bandwidth/capacity. In typical workloads with long context, multi-turn conversations, and fixed system prompts, memory often becomes the bottleneck first, and a large part of it is the KV Cache. Therefore, every step up in cache hit rate is equivalent to scaling up effective compute by one level, which naturally leaves room for lower prices.

    2. Why Autoregressive Generation Repeats Computation

    Text generation is an autoregressive process: the model produces one token at each step, appends it to the end of the sequence, and predicts the next one. Using the input “The weather today” as an example:

    1. step1: [The weather today] -> predict "is"
    2. step2: [The weather today is] -> predict "nice"
    3. step3: [The weather today is nice] -> predict ...

    In the attention mechanism, every token produces three vectors: Q (Query), K (Key), and V (Value). The problem is that step2 needs the K and V of “The,” “weather,” and “today,” but the K and V of the first two tokens were already computed in step1 and are exactly the same. The longer the sequence, the more this repeated projection overhead grows toward quadratic scaling.

    3. How KV Cache Works and What It Delivers

    The core idea is straightforward: compute each token’s K and V only once and write them into a memory cache. During subsequent decoding, historical tokens are read directly from the cache, and only the latest token goes through a full Q/K/V projection. The new Q is then used with all cached K to compute attention scores, and the cached V is weighted to produce the output.

    1. # Pseudocode: single-step decoding with cache
    2. def decode_step(new_token, kv_cache):
    3. q, k, v = project(new_token) # compute only the new token
    4. kv_cache.append(k, v) # append to cache
    5. scores = softmax(q @ kv_cache.K.T / sqrt(d))
    6. return scores @ kv_cache.V # weighted sum with historical V

    The benefit is that the computation per step drops from “processing the entire sequence” to “processing one token.” This is the fundamental reason inference throughput improves dramatically, and the technical prerequisite that allows providers to amortize costs.

    4. Quantifying Memory Usage

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

    1. KV_bytes = 2 × L × H × d_head × S × bytes_per_value

    Here, 2 represents the two copies for K and V, L is the number of layers, H is the number of attention heads, d_head is the dimension per head, and S is the sequence length. With L=32, H=32, d_head=128, S=4096, and FP16 (2 bytes) as an example:

    1. per token per layer: 2 × 32 × 128 × 2 = 16384 B = 16 KB
    2. total: 16 KB × 32 × 4096 ≈ 2 GB
    3. at batch=10 ≈ 20 GB

    The conclusion is clear: in long-text or high-concurrency scenarios, the KV Cache can exceed the model weights themselves and become the primary bottleneck. In engineering practice, “memory per thousand tokens” is commonly used as a unified measure for capacity planning, combined with monitoring, alerting, and logging services to observe real peak usage.

    5. Why Cache Hit Rates Can Be Made High

    High hit rates usually come from the combination of four types of reusable structures:

    • Fixed prefixes: system prompts, tool definitions, and few-shot examples that are identical across requests;
    • Multi-turn conversations: earlier turns are a strict prefix of the next turn;
    • Shared documents: the same knowledge base snippet referenced by many requests;
    • In-batch homogeneity: batch generation from the same template, with highly overlapping prefixes.

    A hit means the K and V of that prefix do not need to be recomputed, which compresses both first-token latency and compute at the same time. It is worth emphasizing that a hit depends on byte-for-byte consistency of the prefix. Any timestamp or random ID placed at the front will break the cache, which is a detail that can be optimized on the business side.

    6. Mainstream Optimization Paths

    • Prefix reuse: place stable content first and fix the order, with dynamic content last;
    • Paged cache management: split the cache into fixed-size blocks allocated on demand to reduce fragmentation and reserved waste;
    • Cache quantization and offloading: store K/V at lower precision, or offload in tiers to host memory for greater capacity;
    • Sparse and window attention: limit the range of history that can participate in attention to curb cache growth;
    • Scheduling and batching coordination: route requests with the same prefix into the same batch to increase reuse probability.

    7. Practical Recommendations and Conclusion

    To assess whether a price cut is sustainable, look at three metrics: cache hit rate, peak memory per token, and batch utilization. If all three improve at the same time, the lower price is backed by real cost savings rather than a short-term subsidy. For users, the most worthwhile thing to do is restructure the prompt: put the invariant part first and the variable part last. This is usually the cheapest way to cut costs. With general inference services and foundational capabilities such as container platforms and monitoring/alerting on platforms like Baidu AI Cloud, teams can observe these metrics more precisely and turn cost optimization from experience-based judgment into a data-driven process.