KV Cache and the Cost Structure of Large Model Inference

    Inference costs do not scale linearly with model size. They depend heavily on how much computation each request performs and how much context can be reused through the key-value (KV) cache. This article explains how KV caching reduces redundant Transformer computation, how to estimate memory usage, what high cache-hit rates really mean, and how model architecture, precision, routing, scheduling, and prompt design together shape inference cost.

    Inference bills often fluctuate according to how much computation each request actually performs and how much context remains cached, rather than increasing linearly with model size. A common pattern is that real spending falls more sharply than list prices after a price reduction because many requests share nearly identical prefixes. When those prefixes hit the cache, most new computation is limited to the final few tokens.

    To understand this difference, it is necessary to examine the key-value cache used during Transformer inference rather than focusing only on price figures.

    Why Autoregressive Generation Repeats Computation

    Text generation is autoregressive: the model produces one new token at each step, appends it to the context, and then uses the expanded context for the next step. In an attention layer, every token produces three groups of vectors: queries, keys, and values.

    Without caching, the model recomputes projections and attention over the entire sequence at step n. The keys and values for the first n − 1 tokens were already calculated during the previous step and have not changed, yet they are computed again. As the sequence becomes longer, the proportion of repeated work increases, causing both compute usage and latency to be dominated by historical context.

    A KV cache stores the keys and values generated by each token as it passes through each layer. During subsequent steps, the model calculates queries, keys, and values only for the newest token. It then compares the new query with all cached keys and computes a weighted sum over the cached values.

    The historical portion changes from “recompute” to “read.” Per-step computation therefore falls from processing the entire sequence to primarily processing the newly added token, plus attention reads and operations proportional to the cache length. This is a general inference optimization and is not tied to any particular model provider or pricing model.

    Estimating KV Cache Memory Usage

    The KV cache size for a single sequence can be approximated as:

    1. Cache bytes ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element

    The factor of 2 accounts for storing both keys and values. With half-precision storage, each element is typically 2 bytes. If the cache is quantized to a lower bit width, the byte count should reflect the actual storage format. Quantization should not be assumed to have no effect on numerical error.

    For example, consider a model with 32 layers, 32 KV heads, a head dimension of 128, a sequence length of 4,096, and half-precision storage. The key and value data for one token in one layer require approximately:

    1. 2 × 32 × 128 × 2 = 16,384 bytes

    That is about 16 KB. The cache for the full sequence is therefore approximately:

    1. 16 KB × 32 × 4,096 ≈ 2 GB

    If 10 independent sequences run concurrently without sharing, the cache alone requires roughly 20 GB. This can be comparable to the memory occupied by the model weights and may become the primary bottleneck with long contexts or high concurrency.

    Grouped-query attention and multi-query attention reduce the number of key-value heads, shrinking cache usage linearly. This is an architectural choice, not a billing trick.

    In practice, memory usage also includes block alignment, page tables, prefix indexes, and fragmentation. The theoretical estimate and actual allocation can differ significantly, so capacity planning should rely on runtime metrics rather than the formula alone.

    What Does an Almost-Perfect Cache Hit Rate Mean?

    On the serving side, a cache hit generally means that the existing prefix of a request exactly matches a KV-cache segment in GPU memory or another storage tier. Those tokens do not need to undergo the full forward pass again.

    Multi-turn conversations, code completion, templated system prompts, and retrieval results placed at the beginning of a prompt can all create stable prefixes. If the scheduler routes requests with the same prefix to an instance that still holds the corresponding cache, the hit rate can become very high.

    In that case, incremental cost mainly comes from:

    • Computing newly added tokens
    • Reading a long cache during attention
    • The attention and memory-bandwidth overhead associated with the growing context
    • Generating the output tokens themselves

    A high hit rate does not make inference free. Providers still incur the cost of:

    • Full prefill when the first token is processed or when the cache misses
    • GPU memory occupied by resident cache entries
    • Cache eviction and replacement
    • Attention reads that increase with context length
    • Output-token generation

    A hit rate approaching saturation means that marginal computation has been reduced substantially. It does not eliminate fixed costs or the attention cost of long sequences.

    For a billing system, charging the full input-token price while performing little or no repeated computation can create a gap between price and cost. Later price reductions may therefore reflect an adjustment to the underlying cost structure. For users, however, lower bills depend on stable prefixes and stable routing. They do not necessarily mean that the model has suddenly become cheaper by a fixed percentage.

    Cache invalidation is also common. Changing a single punctuation mark in the system prompt, rewriting history because of sampling-related behavior, scaling instances up or down, or routing a request to another GPU can reduce a previously high hit rate to zero. When that happens, prefill once again becomes the main source of latency and cost.

    What Level of Caching Is Considered Advanced?

    Common implementation levels can be distinguished as follows without tying them to a specific product:

    1. Per-request caching
      During generation, already produced tokens are not recomputed. This is the baseline capability. It eliminates repeated computation within one autoregressive request but does not reuse state across requests.

    2. Same-instance prefix caching
      Identical prefixes are reused within the same process or on the same device. This works well with session stickiness, but the hit rate depends on routing and cache retention time.

    3. Block-based and paged caching
      KV data is managed in blocks, allowing non-contiguous GPU memory and prefix lookup through hashes. This reduces fragmentation and makes it easier for multiple requests to share common prefixes.

    4. Tiered storage
      Frequently used prefixes remain in GPU memory, while less frequently used prefixes are moved to host memory or high-speed external storage. Cache transfer bandwidth and consistency then become new bottlenecks.

    “Almost always hits” generally indicates at least the second level and depends on several conditions:

    • Prefix normalization
    • Session affinity
    • Sufficient cache capacity
    • Scheduling that avoids frequent full eviction

    This metric reflects system engineering, not just model weights. If public information provides only prices but omits hit rates, context lengths, and concurrency distributions, it is impossible to determine whether the cost structure is healthy.

    How Capacity, Precision, and Scheduling Shape Cost

    A larger cache is not always better. Once KV data consumes most of the available GPU memory, the system can serve fewer sequences concurrently, increasing queueing latency. Aggressive eviction or swapping may then reduce the cache-hit rate.

    In practice, four categories of metrics should be monitored together:

    • Prefix hit rate
    • Prefill latency and per-token decode latency
    • GPU memory used per token
    • Cache eviction frequency

    Optimizing only for hit rate can leave a GPU fully occupied and reduce overall throughput. Compressing precision too aggressively can introduce accumulated attention errors in long-context workloads.

    Weights and KV caches can be quantized independently. Because the cache is particularly sensitive to memory bandwidth, lower-bit storage can improve concurrency. However, extremely low bit widths may be more sensitive to long-range dependencies. The effect should be evaluated through regression tests on the target workload rather than assumed from a fixed compression ratio.

    Scheduling also matters. Requests that share system prompts can be grouped together, requests can be bucketed by prefix length, and the maximum residency time for a single request’s cache can be limited. These strategies are often more effective than simply increasing batch size.

    Batching can amortize weight reads, but it cannot replace prefix reuse. If requests have completely different prefixes, their cache requirements still add together.

    Controls Available to Application Developers

    Applications do not need to depend entirely on a provider’s internal implementation to improve reuse and reduce cost fluctuations. They can:

    • Place stable instructions at the beginning of the sequence and per-turn content at the end, avoiding unnecessary changes to the prefix.
    • Limit the number of conversation turns. Older messages can be summarized before being sent again, reducing the KV length that must remain resident.
    • Keep templates, tool descriptions, and retrieved passages byte-for-byte stable whenever possible. Content that looks identical to a human may still produce different hashes if its bytes differ.
    • Distinguish interactive latency from offline throughput. Interactive workloads care more about time to first token and whether the cache is still resident, while offline workloads care more about concurrency and memory utilization.

    The following pseudocode illustrates the strategy without referring to any specific provider interface:

    1. prefix = normalize(system_prompt + tool_spec)
    2. state = cache.lookup(hash(prefix))
    3. if state is miss:
    4. state = model.prefill(prefix)
    5. cache.insert(hash(prefix), state, ttl)
    6. logits = model.decode(state, new_user_tokens)

    A failed lookup requires a full prefill of the prefix. A successful lookup means that decoding only needs to process newly added tokens. This is why cache-hit rate directly enters the inference cost equation.

    How to Evaluate News About Another Price Reduction

    A price change answers only one question: whether the listed price changed. More informative questions include whether the reduction comes from improved weight-side efficiency, higher cache reuse, or a temporary promotion.

    If reuse remains high over time, charging the full input-token price may overstate the cost of serving those requests. A permanent reduction may then represent a return toward the underlying cost structure. If the discount applies only during a limited period or under strict cache-hit conditions, actual spending may still be driven by prefill and long-context attention.

    A useful evaluation keeps the workload fixed while comparing:

    • The same system prompt
    • Multi-turn additions
    • Multiple context lengths
    • Cold-start and warm-cache paths
    • Latency and cost for each path

    Looking only at list prices or a single demonstration cannot distinguish between “the system performs less computation” and “the provider is charging less.”

    For platform and infrastructure teams, the key technical factors are KV-cache capacity planning, prefix-aware routing, and eviction policy. These mechanisms determine whether inference costs can continue to decline. Prices are only the result visible on the bill.