The Core of LLM Inference Cost Reduction: How KV Cache Works

    This article breaks down the real structure of large language model inference cost and explains why KV Cache is the central optimization behind it. It covers why autoregressive generation repeats work, how caching Key and Value states removes that redundancy, how to estimate KV Cache memory usage, what cache hit rate means in serving, and common engineering techniques such as prefix reuse, paged memory management, quantization, grouped-query attention, and continuous batching. It also offers a framework for judging whether a price reduction is sustainable and a practical checklist for developers.

    1. What Price Cuts Reveal About the Real Cost Structure

    A pattern has emerged in the industry recently: after launch, certain large model services have cut prices significantly and kept them low for the long term. Much of the discussion attributes this to subsidies or price wars. From an engineering perspective, the more interesting question is what changed structurally on the cost side.

    Inference cost breaks down into three parts: compute (the floating-point operations needed to generate each token), memory (the context state that must stay resident at the same time), and scheduling efficiency (how many requests a given piece of hardware can serve per unit of time). Memory and scheduling efficiency are routinely underestimated. When a shared prefix in the context can be reused at scale, and when batching is no longer held hostage by a few long requests, the same hardware can carry several times the concurrency, and the amortized cost per token falls with it. That is the engineering logic that makes a permanent price cut possible.

    To be clear, pricing is a commercial decision by the vendor. This article makes no claims about the prices or billing rules of any specific service. It only discusses technical mechanisms that the industry can broadly verify.

    2. Why Autoregressive Generation Repeats Itself

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

    1. Step 1: input [today, the, weather] -> predict is
    2. Step 2: input [today, the, weather, is] -> predict nice
    3. Step 3: input [today, the, weather, is, nice] -> predict ...

    In the attention mechanism, every token produces three vectors: Q (Query), K (Key), and V (Value). The problem is that in step 2, the K and V of the first four tokens are identical to step 1, yet they are computed again. The longer the sequence, the larger this redundant share becomes: total computation grows quadratically with length, while the only genuinely new information is the final token.

    This is the single largest source of waste on the inference side, and the starting point for every optimization.

    3. KV Cache: Storing Historical State

    The core idea is straightforward: after computing a token, write its K and V into memory. On the next inference pass, read the K and V of historical tokens directly, compute Q, K, and V only for the new token, score attention between the new Q and all cached K, then multiply by the cached V to get the output.

    The effect: per-step computation drops from “process the entire sequence” to “process one new token,” which produces a qualitative improvement in long-text generation speed.

    Illustrative pseudocode:

    1. # No cache: recompute the full sequence at every step
    2. for _ in range(max_new_tokens):
    3. logits = model(input_ids) # O(n^2) per step
    4. input_ids = append(input_ids, argmax(logits))
    5. # With cache: reuse historical K/V
    6. cache = empty_kv_cache()
    7. for _ in range(max_new_tokens):
    8. logits, cache = model(last_token, cache) # only the new token is computed
    9. last_token = argmax(logits)

    4. How to Quantify KV Cache Memory

    KV Cache size can be estimated with the following formula:

    1. KV = 2 × layers × heads × head_dim × sequence_length × bytes_per_value

    Take 32 layers, 32 heads, head dimension 128, and FP16 (2 bytes) as an example:

    • Per token, per layer: 2 × 32 × 128 × 2 = 16384 bytes = 16 KB
    • Length 4096: 16 KB × 32 layers × 4096 ≈ 2 GB
    • Batch size 10: about 20 GB

    The conclusion is direct: with long contexts and high concurrency, KV Cache can consume more memory than the model weights and become the real bottleneck. Capacity planning has to treat it as a first-class citizen.

    5. What Cache Hit Rate Actually Means

    The high cache hit rate that serving teams talk about usually refers to reusing the K/V of a shared prefix across requests, which skips the redundant prefix computation. As the hit rate approaches its upper bound, time to first token (TTFT) drops sharply and compute consumption falls too.

    Typical high-hit-rate scenarios: a fixed system prompt, repeated question answering over a long document, repository-level code context, and the same growing history across a multi-turn conversation. Conversely, if every request has a completely different prefix, there is little room for reuse. Understanding this is what lets you judge how much a given optimization is actually worth in your business.

    6. Common Engineering Optimization Directions

    • Prefix reuse: persist the K/V of a shared prefix or share it across requests, skipping computation on a hit.
    • Paged memory management: split one large contiguous cache block into fixed-size small blocks allocated on demand, reducing fragmentation and reserved waste.
    • Quantization and compression: lower cache precision or compress storage, trading memory for throughput, with accuracy loss to be evaluated.
    • Attention structure optimization: techniques such as multi-query or grouped-query attention let multiple heads share K/V, directly shrinking the cache.
    • Continuous batching and preemption: assemble batches dynamically and swap out lower-priority requests when needed, so long requests do not block the queue.
    • Observability: build monitoring and alerting for cache hit rate, memory watermark, and queueing latency, and use logging and monitoring systems to locate bottlenecks.

    On the cloud, these capabilities are typically combined: a container platform hosts elastic inference instances, object storage holds reusable prefix caches, and monitoring, alerting, and logging handle watermark and latency visibility. General-purpose cloud product categories from platforms such as Baidu AI Cloud can serve as the foundation for this kind of architecture.

    7. How to Judge Whether a Price Cut Is Sustainable

    Four dimensions are worth checking. First, whether the cost structure has genuinely changed (reuse rate, batching efficiency) rather than reflecting a one-off subsidy. Second, whether service levels stay stable (peak latency, rate-limiting policy). Third, whether capability boundaries are clear (context length, concurrency limits). Fourth, whether migration cost is manageable (API compatibility, whether caches can be reused across versions). Price cuts driven by technical optimization usually hold up over the long term; cuts driven by marketing may not.

    8. A Practical Checklist for Developers

    1. Measure first: count the average prefix length and the shared-prefix share in your traffic, and estimate the theoretical reuse gain.
    2. Then restructure: put fixed content such as system prompts, tool definitions, and long documents at the front and keep it stable, avoiding volatile content inserted in the middle of the shared prefix.
    3. Then tune: combine batching strategy with cache precision settings to balance latency against throughput.
    4. Keep observing: track hit rate, memory watermark, TTFT, and cost per thousand tokens as core metrics over the long run.

    Summary: the fall in inference cost comes down to turning repeated computation into compute-once, reuse-many. Understanding how KV Cache works and how to quantify it is worth more in the long run than chasing any single price announcement.