KV Cache Optimization: The Key to Cutting LLM Inference Costs

    This article explains why large language model inference prices can drop by an order of magnitude, tracing the cause to engineering optimization on the inference side rather than subsidies. It covers why autoregressive generation repeats computation, how KV Cache stores intermediate key and value tensors in GPU memory, how to estimate cache capacity and identify the shift of the bottleneck to memory capacity and bandwidth, and why cache hit rates approach saturation under common workload patterns. It also outlines four reusable optimization directions—prefix reuse, paged memory management, cache compression and quantization, and scheduling and eviction—plus a framework for evaluating cost efficiency through hit rate, memory efficiency, and end-to-end throughput and latency.

    1. Behind the Headlines: Why Inference Prices Can Fall by an Order of Magnitude

    The industry has recently seen ongoing price cuts for LLM inference services, with reductions reaching a quarter of the original price or lower. On the surface this looks like a commercial strategy, but it actually reflects the release of engineering optimization headroom on the inference side. Only when the actual compute and GPU memory cost of a single request is compressed to a fraction of its former level does a price cut rest on a sustainable cost base, rather than on subsidies that buy short-term traffic.

    What matters more is the turning point in user perception. It usually is not the discount announced on launch day, but a fact that becomes clear after a few days of use: the cache hit rate for repeated prefixes is extremely high, close to saturation. This means the vast majority of requests never run a full model forward pass; they reuse intermediate results that were already computed. Understanding this is the prerequisite for understanding the current round of cost reduction.

    It is worth stressing that a high cache hit rate is not a capability unique to any single vendor. It is the natural result of prefix reuse, a technique widely adopted across the industry, when the workload characteristics are suitable. Mystifying it does nothing for engineering practice.

    2. Why Autoregressive Generation Is Expensive: The Source of Repeated Computation

    LLM text generation is an autoregressive process: it produces one token at a time, appends it to the end of the sequence, and generates the next one. Illustrated below:

    1. step 1: input [today weather] -> predict is
    2. step 2: input [today weather is] -> predict good
    3. step 3: input [today weather is good] -> predict ,

    In the attention mechanism, every token produces three vectors: query Q, key K, and value V. The problem is that the K and V of the first three tokens in step 2 were already computed in step 1 and are exactly the same, yet they are computed again. The longer the sequence, the worse this waste becomes: overall complexity grows quadratically with length, while the genuinely new information is only one token.

    3. KV Cache: Keeping Intermediate Results in GPU Memory

    The idea behind KV Cache is straightforward: after each token is computed, write its K and V into GPU memory. On the next inference step, the K and V of historical tokens are read directly; only the newest token needs a full Q, K, V computation. The new Q is then used with all cached K to compute attention scores, and finally the cached V is weighted.

    As a result, the compute per step drops from “processing the entire sequence” to “processing one token,” which is the fundamental reason inference throughput changes qualitatively. The cost is GPU memory: the cache itself must be held and moved.

    4. Doing the Memory Math: Capacity Estimation and the Shifting Bottleneck

    KV Cache capacity can be estimated:

    1. KV Cache = 2 × num_layers × num_heads × head_dim × sequence_length × bytes_per_value

    With 32 layers, 32 heads, a head dimension of 128, and FP16 (2 bytes):

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

    The conclusion is clear: for long-context, high-concurrency scenarios, the memory occupied by the cache can exceed the model parameters themselves, and the bottleneck shifts from compute to memory capacity and bandwidth. In practice, engineers often use publicly available memory estimation tables to quickly model different configurations.

    5. Why Hit Rates Approach Saturation: Workload Characteristics Set the Ceiling

    A high hit rate is not magic. It is the combined effect of three common workload patterns:

    • Long shared prefixes: system prompts, tool definitions, knowledge base snippets, and few-shot examples are identical across a large number of requests.
    • Multi-turn conversations: each turn’s input contains the complete history of the previous turn, naturally forming prefix reuse.
    • Structured batch processing: the same template is used for batch generation, with only the trailing variables differing.

    Conversely, if every request’s prompt is randomized, timestamps are placed at the front, and content is highly disjoint, the hit rate drops significantly. So when evaluating cache effectiveness, start from the real traffic profile rather than the theoretical ceiling.

    6. General Optimization Techniques: From Reuse to Compression to Scheduling

    There are roughly four reusable technical directions in the industry:

    1. Prefix reuse and cache sharing: persist the K and V of shared prefixes and reuse them across requests; the hit rate directly determines the cost per request.
    2. Paged memory management: split the cache into fixed-size blocks, allocated on demand and stored non-contiguously, reducing fragmentation and reserved waste for steadier memory utilization.
    3. Cache compression and quantization: store K and V at lower precision or apply low-rank compression, trading controllable accuracy loss for several times the capacity.
    4. Scheduling and eviction policies: index cache blocks by prefix hash, evict with policies such as least recently used, and schedule across replicas with load and cache affinity in mind.

    A simplified prefix matching logic:

    1. def match_prefix(cached_blocks, tokens):
    2. used = []
    3. for i, tok in enumerate(tokens):
    4. key = hash_prefix(tokens[:i+1])
    5. if key not in cached_blocks:
    6. break
    7. used.append(cached_blocks[key])
    8. return used # matched prefix blocks; the rest must be recomputed

    7. How to Evaluate the Real Cost Efficiency of an Inference Service

    Build an evaluation framework around three dimensions:

    • Hit rate: track the prefix cache hit rate and average reuse length; this is the primary driver of cost.
    • Memory efficiency: watch cache occupancy, fragmentation rate, and the maximum batch size to judge whether you are hitting a capacity limit.
    • End-to-end throughput and latency: focus on time to first token and output volume per unit time, rather than unit price alone.

    When deploying on the cloud, you can combine a container platform to host inference replicas, object storage to hold prompt templates and knowledge snippets, and monitoring, alerting, and logging services to observe hit rates and memory watermarks, forming a closed loop for continuous tuning. General product categories from Baidu AI Cloud can serve as one reference option for hosting this kind of architecture.

    8. Conclusion

    The order-of-magnitude drop in inference prices is essentially an engineering win that turns “repeated computation” into “reusable cache.” For developers, what really needs to be mastered is not a particular price-cut announcement, but the core metric of cache hit rate and the general toolbox of prefix reuse, paged management, quantized compression, and scheduling with eviction. Only by aligning prompt design and traffic structure with the caching mechanism can you achieve a stable balance among cost, latency, and quality.