KV Cache and Context Caching: The Technologies Powering LLM Inference Cost Reduction

    Large language model (LLM) API prices have been dropping steadily, driven not just by market competition but by maturing inference-side engineering optimizations. This article breaks down two of the most impactful techniques—KV Cache and Context Caching (also known as Prompt Caching)—explaining how they work under the hood, why cache hit rate has become a core metric for inference efficiency, and how developers can design applications to maximize cache reuse and control costs.

    The Computational Challenge of Autoregressive Generation

    To understand the value of KV Cache, it is essential to first grasp how large language models generate text token by token.

    Mainstream LLMs are built on the Transformer architecture and generate text through an autoregressive process: the model predicts one token at a time, appends it to the existing sequence, and then uses the extended sequence to predict the next token. This loop continues until an end-of-generation token is produced.

    Consider a simple example:

    • Step 1: Input “今天天气” (today’s weather), the model outputs “真” (really).
    • Step 2: Input “今天天气真”, the model outputs “好” (good).
    • Step 3: Input “今天天气真好”, the model continues predicting the next token.

    The problem lies precisely in this workflow. The attention mechanism in Transformers requires each token to generate Query (Q), Key (K), and Value (V) vectors. Attention weights are computed via the dot product between the current token’s Q and the K vectors of all preceding tokens. This means that in Step 2, the model must recompute the K and V vectors for “今”, “天”, “天”, “气”, and “真”—even though these vectors were already computed in Step 1 and their values remain identical. The longer the sequence, the more severe this redundant computation becomes. Without optimization, generating a sequence of length n results in near-quadratic growth in attention computation, making inference latency and compute costs prohibitive.

    KV Cache: Trading Memory for Compute

    The core idea behind KV Cache is straightforward: never recompute what has already been computed.

    The implementation works as follows: after processing each token, its K and V vectors from every attention layer are stored in GPU memory. When generating a new token, the model only needs to compute Q, K, and V for that single new token. The new K and V vectors are appended to the cached ones. For attention computation, the new token’s Q directly takes the dot product with all historical K vectors in the cache, and a weighted sum is computed over the cached V vectors.

    This reduces the per-step computation from “processing the entire sequence” to “processing just one new token,” delivering an order-of-magnitude improvement in inference efficiency. Today, KV Cache is a standard capability in virtually all LLM inference frameworks.

    However, KV Cache does not come without costs—it is fundamentally a trade-off: using GPU memory space in exchange for reduced computation time. Its memory footprint can be precisely estimated:

    1. KV Cache Size = 2 × Number of Layers × Head Dimension × Number of Heads × Sequence Length × Bytes per Value

    Take a hypothetical model with 32 layers, 32 attention heads, a head dimension of 128, a sequence length of 4096, and FP16 precision (2 bytes per value):

    • Per-token KV memory per layer: 2 × 32 × 128 × 2 = 16,384 bytes (16 KB)
    • Full sequence: 16 KB × 32 layers × 4096 tokens ≈ 2 GB

    Note that this estimate covers only a single request. If the inference service handles 10 concurrent requests, KV Cache alone would require approximately 20 GB of GPU memory. For long-context scenarios (e.g., sequences of 100K+ tokens), the memory footprint of KV Cache can even exceed the model weights themselves, making it the primary bottleneck for deployment. To address this, the industry has developed a range of optimization techniques—including paged memory management, KV quantization and compression, and sparse attention—all aimed at fitting more concurrent requests and longer contexts within limited GPU memory.

    Context Caching: Moving from “Less Computation” to “Zero Computation”

    While KV Cache addresses redundant computation within a single request, Context Caching (also referred to as Prompt Caching) tackles redundant computation across multiple requests. This is the key to understanding why API prices can be dramatically reduced.

    In real-world business scenarios, a significant number of requests share highly overlapping prefixes:

    • Multi-turn conversations: Each new request includes the entire conversation history from all previous turns, with the historical portion often accounting for more than 90% of the total input.
    • AI Agent applications: Every tool invocation carries the same system prompt, tool definitions, and accumulated execution logs.
    • Retrieval-Augmented Generation (RAG): The same long document is repeatedly passed as context, with only the user’s question changing.

    If an inference service can persist the KV Cache of previously processed prefixes and detect that a new request’s prefix is identical to a cached one, it can skip the prefill computation for that portion entirely and directly reuse the cached results. This is what is meant by a cache hit.

    A cache hit delivers twofold benefits:

    1. Substantial cost reduction: Compute is only consumed for the portion that misses the cache. For a 100K-token request with a 99% cache hit rate, the model only needs to process roughly 1,000 tokens—allowing the service provider to offer a correspondingly low price for the request.
    2. Lower latency: Time to first token (TTFT) is primarily determined by the prefill stage. With cache hits, response times for long-context requests can drop from tens of seconds to just a few seconds.

    As cache hit rates approach 100%, the marginal cost of long-context processing approaches zero for the user—this is the underlying reason why some LLM services can aggressively cut their API prices.

    How Developers Can Improve Cache Hit Rates

    Cache hits typically require exact, token-for-token prefix matching. Any difference in the prefix will invalidate the cache for all subsequent content. Therefore, in engineering practice, keep the following principles in mind:

    • Place stable content first: Put invariant elements such as system prompts, tool definitions, and reference documents at the beginning of the request. Put variable content like user questions and timestamps at the end.
    • Avoid irrelevant perturbations: Do not prepend fields that change on every request, such as random numbers or real-time timestamps, to the beginning of the prompt.
    • Append, don’t rewrite: In multi-turn conversations, extend history by appending. Avoid reformatting or rewriting existing content in previous turns.
    • Align prefixes for batch tasks: When asking multiple questions against the same document, keep the document portion formatted identically across all requests.

    Conclusion

    The declining cost of LLM inference is not merely a result of price wars. It is the product of continuous engineering progress in KV Cache, Context Caching, memory scheduling optimization, and related technologies. For developers, understanding these underlying mechanisms is essential—not only to interpret the logic behind price changes but also to design application architectures that are cache-friendly and cost-efficient. In an era where model capabilities are converging, the ability to utilize inference infrastructure effectively is what will separate competitive products from the rest.