KV Cache Optimization for LLM Inference: The Key to Lowering Serving Costs

    This article explains why LLM inference costs are driven less by token generation than by repeated computation over shared prefixes, and how KV Cache optimization addresses it. It covers why autoregressive decoding recomputes historical keys and values, how KV Cache turns full-sequence recomputation into incremental updates, and a hand-calculable formula for estimating its GPU memory footprint. It then outlines four levers for achieving high cache hit rates—prompt structure, prefix hashing, tiered caching, and batch scheduling—along with a recommended rollout order and the metrics to track. The takeaway: sustainable price reductions come from eliminating duplicate computation while preserving output consistency, not from short-term promotions.

    1. What a Price Cut Reveals About the Real Cost Structure

    A pattern worth watching has recently emerged in the industry: after a version update, a major model service announced a long-term price reduction to one quarter of its previous calling cost. Many developers’ first reaction is that the vendor is starting a price war. But if you break down the cost structure of an inference service, the room for price cuts does not come only from commercial strategy—it comes just as much from the engineering side’s ability to eliminate repeated computation.

    An easily overlooked fact is that in an LLM inference pipeline, the expensive part is not “generation” but “repeated generation.” When a large number of requests share the same prefix (system prompts, long documents, code context, knowledge base snippets), computing full attention from scratch every time wastes compute on historical segments that are completely identical. Whoever can drive that repeated computation close to zero holds real room for price reductions.

    So the right way to evaluate such a price cut is not to look at the discount number, but at three things: whether the cache hit rate can stay consistently high, whether output after a hit is exactly identical to output after a miss, and whether cache management becomes a new bottleneck under high concurrency. Let’s start from the most basic mechanism.

    2. Why Autoregressive Generation Produces Repeated Computation

    Text generation is an autoregressive process: each step produces a single token, appends it to the end of the sequence, and generates the next one.

    1. Step 1: input [Today, is] -> output true
    2. Step 2: input [Today, is, true] -> output good
    3. Step 3: input [Today, is, true, good] -> output ,

    Notice that in Step 2, the first two tokens are exactly the same as in Step 1. Under standard attention, every token produces three vectors: query Q, key K, and value V. The K and V of a historical token depend only on that token itself and the positions before it—not on what is appended later. This means the K and V already computed in Step 1 are recomputed from scratch in Step 2.

    The longer the sequence, the worse the waste. Step n theoretically needs to process only 1 new token but actually processes n tokens, degrading overall complexity from linear to quadratic. This is the root cause of inference cost rising sharply with context length.

    3. KV Cache: Keeping Historical K and V in GPU Memory

    The fix is straightforward: after computing each token, write its K and V into a GPU memory cache. On the next inference step, read the historical part directly, run the full Q, K, V computation only for the new token, compute attention scores between the new Q and all cached K, and finally take a weighted sum over the cached V.

    In pseudocode, it looks like this:

    1. # Without cache: recompute the full sequence at every step
    2. for step in range(max_len):
    3. q, k, v = model.forward(all_tokens) # complexity grows quadratically with length
    4. next_token = sample(q[:, -1, :])
    5. # With cache: history is read-only, only one token is computed incrementally
    6. cache = init_empty_cache()
    7. for step in range(max_len):
    8. q, k, v = model.forward(new_token, past_kv=cache)
    9. cache = cache.append(k, v) # append only, no recomputation
    10. new_token = sample(q[:, -1, :])

    The payoff is twofold: compute drops, and because historical K and V already sit in GPU memory, the memory access pattern becomes more regular. But there is no free lunch—the compute you save shows up as GPU memory consumption.

    4. How Much GPU Memory KV Cache Actually Uses: A Formula You Can Compute by Hand

    GPU memory usage can be estimated with the following general formula:

    1. KV Cache bytes = 2 × num_layers × num_kv_heads × head_dim × sequence_length × bytes_per_element

    The factor of 2 accounts for the two caches, K and V. Take a configuration with 32 layers, 32 KV heads, head dimension 128, sequence length 4096, and FP16 (2 bytes):

    • Per token, per layer: 2 × 32 × 128 × 2 = 16384 bytes = 16 KB
    • One sequence of 4096 tokens: 16 KB × 32 layers × 4096 ≈ 2 GB
    • 10 concurrent requests: about 20 GB

    The conclusion is clear: with long contexts and high concurrency, KV Cache memory usage can exceed the model weights themselves and become the real deployment bottleneck. Common mitigations in engineering include adopting multi-query or grouped-query attention to reduce the number of KV heads, storing the cache at lower precision, paging or tiering cache management, and sharing and reusing cache by prefix content. These are general industry directions; the specific implementation must be evaluated against the actual model architecture and hardware.

    5. Where High Cache Hit Rates Come From: Prefix Reuse and Scheduling Design

    Back to the original question: why can some services push cache hit rates close to saturation? The core reason is that the requests’ “reusable prefix” is long enough and stable enough. There are four levels to work on:

    1. Prompt structure governance. Move stable, unchanging content (role settings, tool descriptions, output specifications, knowledge base snippets) to the front as a unified prefix, and place volatile content such as user input at the end. The more stable the prefix, the higher the hit rate.
    2. Prefix hashing and content addressing. Compute hashes over token sequences block by block; on a hit, reuse the corresponding cache block, avoiding the overhead of comparing the full sequence.
    3. Tiered caching and eviction policies. Keep hot data in GPU memory, push warm data down to host memory or a faster storage tier, and combine this with recency-based, block-granularity eviction to balance hit rate against capacity.
    4. Batch scheduling alignment. Group requests that share a prefix into the same batch to reduce repeated prefill; at the same time, avoid long and short requests blocking each other, and keep tail latency under control.

    It is worth stressing that the cache must guarantee semantic equivalence: output on the hit path should match output on the miss path, otherwise the cost reduction comes at the expense of quality.

    6. Implementation Advice and Measuring Results

    Recommended order of work: first add instrumentation to measure the distribution of prefix lengths and the potential hit rate, then restructure prompts, then introduce block-level caching and tiered storage, and finally tune batching and the concurrency limit. Metrics should cover at least four items: cache hit rate, time to first token, cost per token, and the pass rate of output consistency spot checks.

    Building cost optimization on the certain payoff of “eliminating repeated computation” rather than on short-term promotions is the sustainable engineering path. When cache hit rate, latency, and quality are all stable at the same time, a lower inference unit price follows naturally.