KV Cache in LLM Inference: Principles, Memory Estimation, and Reuse Optimization

    This article explains why autoregressive LLM inference repeats computation for historical tokens, how KV cache avoids that repetition, and how to estimate its memory footprint. It also covers prefix caching and hit rates, engineering practices for deployment, and common misconceptions about KV cache.

    1. Background: Why Autoregressive Generation Repeats Computation

    Large language models generate text through an autoregressive process. The model predicts one new token at a time, appends it to the existing sequence, and then uses the updated sequence to predict the next token. Generating a response of length N therefore requires N forward passes.

    Consider an input such as “the weather today.” In the first step, the model predicts the next token based on “the weather today.” In the second step, it uses “the weather today is” as input to predict the following token, and so on.

    In the standard attention mechanism, each token produces three vectors: a query vector (Q), a key vector (K), and a value vector (V). To compute the output at position t, the model compares the Q of the current position with the Ks of all historical positions, then computes a weighted sum of the historical Vs.

    The problem lies in the K and V of historical tokens. In the second step, the K and V of the tokens “the,” “weather,” and “today” are exactly the same as those computed in the first step, because they depend only on themselves and the preceding content, not on later generation. Recomputing them at every step makes computation grow quadratically with sequence length, wasting significant compute on repeated work.

    2. The Basic Idea of KV Cache

    KV cache (Key-Value Cache) takes a direct approach: compute the K and V of each token only once and store them in GPU memory. Later steps read these cached values directly and compute Q, K, and V only for the new token.

    The process is as follows:

    1. The new token is projected to obtain its own q, k, and v.
    2. The k and v are appended to the cache.
    3. The new q is used to compute attention scores against all cached k values. After normalization, the model computes a weighted sum of all cached v values.

    The computation per step drops from “processing the full sequence” to “processing one new token plus one read of the cache.” The cost is that memory usage grows with sequence length. KV cache is therefore essentially a technique that trades memory for compute.

    Illustrative code (logic only, independent of any specific framework):

    1. def decode_step(new_token_embedding, kv_cache, d_head):
    2. q, k, v = project_qkv(new_token_embedding) # compute only for the new token
    3. kv_cache.append(k, v) # write to cache
    4. scores = q @ kv_cache.keys().T / sqrt(d_head)
    5. weights = softmax(scores)
    6. return weights @ kv_cache.values() # read historical K and V

    3. Memory Footprint Estimation

    The size of the KV cache can be calculated with the following formula:

    KV cache size = 2 × num_layers × num_attention_heads × head_dim × sequence_length × bytes_per_value

    The coefficient 2 accounts for storing both K and V.

    Consider a hypothetical model with 32 layers, 32 heads, head dimension 128, sequence length 4096, and FP16 precision (2 bytes per value).

    • KV size for one token in one layer: 2 × 32 × 128 × 2 = 16,384 bytes, or 16 KB.
    • KV size for one token across all 32 layers: 16 KB × 32 = 512 KB.
    • Total KV cache at sequence length 4096: 512 KB × 4096 ≈ 2 GB.

    If the model processes 10 sequences simultaneously (batch size 10), the total cache is about 20 GB. This number does not include the model parameters themselves.

    The table below shows the trend under several common configurations (based on the same model structure):

    Sequence length Batch size Approximate KV cache
    4096 1 2 GB
    4096 10 20 GB
    8192 1 4 GB
    8192 10 40 GB

    Long context and large batch size both amplify memory demand. When combined, KV cache can easily exceed model weights and become the main bottleneck in inference deployment.

    In actual models, some architectures reduce the number of KV heads (for example, grouped-query attention) or use lower-precision storage, significantly reducing cache usage. Estimation should be based on the actual configuration of the target model.

    4. Cache Reuse and Hit Rate

    In online inference services, many requests share identical prefixes, such as a fixed system prompt, multi-turn conversation history, or the same long document. If the service can identify these identical prefixes and directly reuse the already-computed KV cache, it does not need to run a forward pass over that content again. This approach is commonly called prefix caching.

    A cache hit requires the token sequence to be exactly identical and to match continuously from the beginning of the sequence. If even one token in the prefix differs, the subsequent cache cannot be reused. A common practice for improving hit rate is therefore to place stable content at the front of the prompt and variable content at the end.

    Hit rate reflects the proportion of repeated computation that is avoided. A high hit rate means:

    • Lower time to first token (the wait before the first output token is generated);
    • Lower compute resource consumption per request;
    • In token-based billing services, cached portions are often cheaper, reducing the overall unit price.

    Note that hit rate depends on the business scenario. Customer service bots and batch tasks with fixed templates have highly similar request prefixes and can achieve high hit rates. Open-ended creation, where every input is completely different, has a hit rate close to zero. A fixed hit-rate number cannot be discussed without considering the scenario. Specific billing methods are subject to the provider’s published rules.

    5. Engineering Best Practices

    1. Estimate before deployment. Use the formula in Section 3, together with the target model’s layer count, head count, precision, and expected maximum context length, to calculate the maximum concurrency a single instance can support.
    2. Control context length. Truncate or summarize conversation history to avoid unbounded cache accumulation.
    3. Standardize prompt structure. Fix stable content such as system instructions and role settings at the front to ensure the prefix is reusable.
    4. Monitor cache metrics. Record hit rate, memory usage, and request queuing, and use the data to determine whether cache capacity is sufficient.
    5. Allocate different resources for long and short requests. Long-context requests consume much more cache than short requests. In mixed scheduling, set limits to prevent a few long requests from exhausting all GPU memory.

    6. Common Misconceptions

    Misconception 1: KV cache reduces model parameter memory. In reality, the cache is temporary data generated during inference and is stored separately from the model weights. Both occupy GPU memory at the same time.

    Misconception 2: The higher the cache hit rate, the better, regardless of the business. Hit rate measures the proportion of repeated computation avoided, and its value should be judged together with the request distribution of the business.

    Misconception 3: Enabling cache always improves performance. Cache saves compute but increases memory usage. When memory is tight, batch size may have to be reduced, and throughput can actually decrease.

    The key to understanding KV cache is the trade-off of “memory for compute.” Mastering the memory estimation formula and designing prompts and scheduling strategies based on request prefix characteristics are essential for finding the right balance among cost, latency, and throughput.