LLM Inference Cost Reduction: The Role of KV Cache and Optimization Practices

    This article explains why large language model inference prices keep falling by looking at the underlying cost structure of serving, with a focus on KV Cache. It covers how autoregressive generation repeats attention computation, how KV Cache turns repeated work into a single computation, a reusable formula for estimating cache memory usage, the main sources of high cache hit rates, and practical recommendations for capacity planning. Developers will learn how to plan capacity and control costs in long-context, high-concurrency scenarios without relying on price changes from a single service.

    1. The Cost Structure Behind Price Cuts: Why Inference Prices Keep Dropping

    A certain class of large language model services recently announced another long-term price reduction, bringing prices down to a quarter of their previous level. For developers, what matters is not the price number itself but the change in the cost structure behind it: inference billing is mainly determined by GPU memory usage, compute throughput, and request scheduling efficiency. Among these, the repeated consumption of memory and compute is the part most easily compressed through engineering.

    In autoregressive generation, the model produces only one token at a time, yet it repeats attention computation over the existing sequence. This repeated computation wastes compute and occupies GPU memory, directly limiting the concurrency a single GPU can handle. Whoever reduces this waste can serve more requests on the same hardware and therefore has room for continued price reductions. Key-value caching is the general-purpose technical solution to this problem.

    2. Key-Value Cache: Turning Repeated Computation into a Single Computation

    2.1 Generation Without Caching

    Language models generate text autoregressively: feed in the current sequence, get the next token, append it back to the sequence, and continue. Using “today weather” as an example:

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

    In the attention mechanism, every token produces three vectors: query (Q), key (K), and value (V). In Step 2, the K and V of the first three tokens are exactly the same as in Step 1, yet they are computed again. The longer the sequence, the worse this duplication becomes, and the overall complexity degrades from “processing one token” to “processing the entire sequence.”

    2.2 The Core Idea of Caching

    The key-value cache works as follows: once a token is computed, its K and V are written to GPU memory. During subsequent inference, 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 the cached V is weighted accordingly.

    1. # Illustration: cache read/write during incremental decoding
    2. past = None
    3. for step in range(max_new_tokens):
    4. logits, past = model(input_ids[:, step:step+1], past_key_values=past)
    5. next_id = logits[:, -1].argmax(dim=-1, keepdim=True)
    6. input_ids = torch.cat([input_ids, next_id], dim=-1)

    The effect is that the per-step computation drops from the full sequence to just the newest token. Generation throughput improves significantly, and output per unit time becomes more stable after the first token.

    3. How to Calculate GPU Memory Usage: A Reusable Estimation Formula

    The cache is not free; it trades GPU memory for compute. The general estimation is:

    1. KV Cache bytes = 2 × layers × heads × head_dim × sequence_length × bytes_per_precision

    For 32 layers, 32 heads, head dimension 128, and FP16 (2 bytes):

    1. Per token, per layer: 2 × 32 × 128 × 2 = 16384 bytes = 16 KB
    2. Per token, full model: 16 KB × 32 layers = 512 KB
    3. Sequence length 4096: 512 KB × 4096 ≈ 2 GB
    4. Batch size 10: about 20 GB

    As shown, when long contexts are combined with high concurrency, cache memory can exceed the model parameters themselves and become the real bottleneck. Common engineering mitigations include: lowering cache precision, using more compact attention structures, paging and tiered management of the cache, and reusing the cache of identical prefixes across requests.

    4. Why Cache Hit Rates Can Be High

    There are four common sources of high hit rates: first, fixed prefixes such as system prompts, templates, and tool descriptions are reused repeatedly; second, the historical portion of multi-turn conversations is naturally stable; third, many requests in a batch share the same prefix; fourth, a reasonable cache eviction policy keeps hot prefixes resident in GPU memory. A hit means this prefix does not need to be recomputed, reducing both compute and memory at the same time. This is also the key engineering foundation that allows services to offer lower prices.

    5. Practical Recommendations and Capacity Planning

    1. Structured prefixes: place stable content first and variable content last to maximize prefix reuse.
    2. Control context length: trim and summarize history promptly to avoid linear cache growth.
    3. Capacity estimation: estimate peak GPU memory based on “layers × heads × dimension × concurrency × length × precision” and leave headroom.
    4. Metrics to monitor: hit rate, cache residency time, average generated length per request, and peak GPU memory.
    5. Cloud deployment: use container platforms for elastic scaling, use monitoring, alerting, and logging services to locate cache jitter, and use object storage to store reusable prefix templates.

    6. Conclusion

    The continued decline in inference prices is essentially the result of squeezing out repeated computation and memory waste one item at a time. By understanding the mechanism of the key-value cache, the memory formula, and the path to hit-rate optimization, developers can make more reliable capacity plans and control costs in long-context, high-concurrency scenarios, without depending on price fluctuations from a single service.