KV Cache Explained: The Core Mechanism Behind LLM Inference Cost Reduction

    This article breaks down the KV cache mechanism in large language model inference, explains how it eliminates redundant computation during autoregressive generation, provides a formula for estimating its GPU memory footprint, and examines prefix caching and other optimization techniques that lower serving costs in production.

    From a Price Drop to the Real Cost Driver

    Recently, a major LLM provider announced a significant price reduction for its new model service, sparking discussion among developers: why can some vendors offer inference at a fraction of the cost of their peers? Is the price war driven by subsidies, or by genuine technical advantages?

    To answer this, we need to examine the cost structure of LLM inference. Serving costs are dominated by two factors: compute (GPU cycles) and memory footprint (which determines how many concurrent requests a single GPU can handle). One of the core technologies that governs both is the KV cache and its hit-rate optimization. Understanding KV caching is the key to understanding the technical path toward cheaper inference.

    This article walks through the KV cache mechanism from scratch, explains how to estimate its memory consumption, and discusses engineering practices that improve cache reuse.

    The Problem Without Caching: Repeated Computation in Autoregressive Generation

    Large language models generate text autoregressively: each step predicts a single token, appends it to the input sequence, and then predicts the next token.

    A simplified generation flow:

    • Step 1: Input “Today’s weather” → model outputs “is”
    • Step 2: Input “Today’s weather is” → model outputs “nice”
    • Step 3: Input “Today’s weather is nice” → continue generating the next token…

    The issue is that the Transformer attention mechanism requires computing attention over the entire sequence at every step. For each token, the model produces three vectors: Query (Q), Key (K), and Value (V).

    Notice Step 2: the model must recompute the K and V vectors for the historical tokens “Today’s”, “weather”, and “is”. But those were already computed in previous steps, with identical results. As the sequence grows, this redundant computation accumulates linearly — generating a response of length N means the K/V of all historical tokens are recomputed N times, wasting enormous compute.

    KV Cache: Trading Memory for Compute

    The KV cache approach is straightforward: each time a new token generates its K and V, store them in GPU memory; in subsequent steps, read the cached values directly instead of recomputing the historical portion.

    With caching, each inference step becomes:

    1. Compute Q, K, V only for the newest token.
    2. Append the new K and V to the cache.
    3. Use the new Q to compute attention scores against all cached K vectors.
    4. Weighted-sum the cached V vectors to produce the current step’s output.

    This reduces per-step compute from “process the whole sequence” to “process only one token”, yielding an order-of-magnitude speedup. It also explains the two distinct inference phases: Prefill (processing the input prompt, parallelizable, compute-bound) and Decode (token-by-token generation, heavily dependent on cache reads/writes, memory-bound). The KV cache is what makes the Decode phase efficient.

    How Much Memory Does the KV Cache Consume? A Calculable Formula

    The KV cache is not free; it occupies valuable GPU memory. Its size can be precisely estimated:

    1. KV Cache Size (bytes) = 2 × num_layers × num_heads × head_dim × sequence_length × precision_bytes

    (The factor of 2 accounts for two separate caches: K and V.)

    Example: a model with 32 layers, 32 heads, head dimension 128, sequence length 4096, and FP16 precision (2 bytes):

    • Single token, single layer: 2 × 32 × 128 × 2 = 16,384 bytes = 16 KB
    • Total cache for one sequence: 16 KB × 32 layers × 4096 tokens ≈ 2 GB
    • With 10 concurrent sequences (batch size = 10): ≈ 20 GB

    As shown, for long contexts and high concurrency, the KV cache can consume more memory than the model parameters themselves, becoming the primary bottleneck for inference throughput. The total cache capacity a GPU can hold directly determines the number of concurrent requests it can serve, which in turn determines the per-token serving cost — the technical foundation of inference pricing.

    Cache Hit Rate: The Key Lever for Cost Reduction

    A further cost optimization is cache reuse. In real-world workloads, many requests share common prefixes: system prompts, multi-turn conversation histories, fixed tool descriptions in agent scenarios, and so on. If the system can identify that a request’s prefix matches an already-cached portion, that part does not need to be prefilled again — the historical KV values are reused directly. This is called a “prefix cache hit.”

    A high cache hit rate provides:

    1. Massive savings in prefill compute: a long system prompt is computed only once, and subsequent millions of requests reuse it directly.
    2. Significantly lower time-to-first-token (TTFT): skipping repeated context computation.
    3. Very low marginal cost: the served portion can be priced at a small fraction of the original cost.

    To achieve high hit rates in practice, engineering efforts typically include: efficient KV cache storage and retrieval (e.g., prefix-tree or hash-based matching), multi-level caching across GPU memory, host memory, and SSD, session-affinity request scheduling (so the same session lands on the instance holding its cache), and reasonable cache eviction policies.

    Additional Optimization Techniques

    Beyond prefix caching, common inference optimizations include: quantizing KV cache precision (from FP16 to FP8/INT8, halving memory usage), grouped-query and multi-query attention (GQA/MQA, which reduce the number of KV heads at the source), latent-attention-style structures that compress KV dimensions, and PagedAttention-style paged memory management to reduce fragmentation. Combined, these techniques form the overall cost-reduction space for next-generation inference services.

    Practical Takeaways for Developers

    For enterprise users and developers, three practical insights emerge:

    1. Design cache-friendly request structures: Put fixed content (system prompts, knowledge base excerpts) at the beginning of the prompt, and variable content at the end, to maximize prefix cache hits.
    2. When self-hosting, calculate memory accurately: Use the formula above to estimate cache overhead and plan context length and concurrency accordingly.
    3. When evaluating model services, look beyond unit price: Examine whether the platform offers cache-hit billing discounts, elastic compute, and robust monitoring and alerting. For example, Baidu AI Cloud’s LLM service platform provides general capabilities such as model inference, compute scheduling, and observability; developers can assess total cost of ownership based on their own context characteristics.

    Conclusion

    A significant price drop is often not a marketing gimmick but a reflection of inference systems engineering. The KV cache eliminates redundant computation; prefix cache reuse eliminates redundant prefill; quantization and attention-structure optimizations reduce memory footprint — each technical lever builds on the others to deliver an order-of-magnitude cost reduction. Understanding this mechanism helps developers make smarter technical and business decisions in an era of increasingly affordable models.