KV Cache in Large Model Inference: How It Works and Why Hit Rates Matter
KV Cache is a core mechanism in large language model inference that stores the key and value vectors of processed tokens so they are not recomputed at every decoding step. This article explains why autocratic generation repeats computation without caching, how KV Cache trades memory for compute, what cache hit rates mean for effective pricing, and which factors—prefix stability, block granularity, lifecycle, batching, and correctness boundaries—determine hit rates in production. It also covers practical guidance for prompt design, observability, and cost evaluation.
KV Cache in Large Model Inference: How It Works and Why Hit Rates Matter
Discussions about inference pricing often stop at the “price per million tokens.” Yet for long conversations, code completion, retrieval-augmented generation, and multi-turn agent workflows, latency and cost are largely determined by whether historical context gets recomputed. KV Cache (key-value cache) is the core mechanism that turns this repeated work from computation into reads. Understanding it clearly is what lets you judge what “a high cache hit rate” actually means in engineering terms, and how much it can reduce effective cost.
Why Autoregressive Generation Recomputes
Mainstream decoder-only large models generate text autoregressively: each step produces one new token, appends it to the context, and continues predicting the next. Without a cache, step n requires re-running attention over the entire sequence of length n. Every token produces a query vector Q, a key vector K, and a value vector V. The K and V of historical tokens were already computed in previous steps, haven’t changed, yet get recomputed over and over. The longer the sequence, the greater the redundancy: when generating the 1000th token, the projections and partial attention computations for the previous 999 tokens may all be executed again.
As a result, the per-step cost of a naive implementation grows roughly with the current context length, and the total computation for a full generation approaches the square of the sequence length. This inflates latency, saturates compute, and makes long-context services economically unviable.
What KV Cache Computes and Saves
The idea behind KV Cache is straightforward: once a token’s K and V are computed, they are written to GPU memory (or a tiered storage layer), organized by layer and head. The next step only computes Q, K, and V for the new token; the new Q is matched against all cached historical K vectors to produce attention scores, then weighted-sums the cached V vectors. Historical tokens no longer undergo repeated linear projections. The prefill phase still processes the entire prompt, but the decode phase reduces “processing the whole sequence” to “processing the newest token and reading historical key-values.”
Two things need to be distinguished. First, per-step floating-point operations drop, so decoding becomes faster—this is the speed users perceive. Second, memory usage grows: cache size is roughly proportional to the number of layers, heads, head dimensions, sequence length, and batch size, and precision (FP16, BF16, or lower bit-widths) also changes footprint. The cache trades memory for compute—it’s not a free lunch. With large batches and long contexts, the bottleneck often shifts from compute to memory capacity and bandwidth.
Here is minimal pseudocode showing the difference for one decode step. It illustrates only the data flow, not any specific framework’s API:
# Without cache: re-project all tokens at every stepfor t in range(new_len):Q, K, V = project(tokens[:t+1])out = attention(Q, K, V)# With cache: historical K/V are read-only; only the new token is projectedK_cache, V_cache = load_prefix(session_id)q, k, v = project(new_token)K_cache, V_cache = append(K_cache, k), append(V_cache, v)out = attention(q, K_cache, V_cache)
Cache Hits and “Effective Price”
When billing accounts for input tokens, output tokens, and a separate price for cache-hit prefixes, the hit rate directly changes the effective cost of a request. A hit does not mean “the model remembers what you said.” It means the server has found that this request’s prefix matches stored KV blocks, allowing it to skip prefill for that segment.
The hit rate can be roughly understood as: the number of reused prefix tokens divided by the number of cacheable input tokens in the request. If system prompts, tool descriptions, code repository indexes, or long documents appear unchanged at the front every time, that portion of prefill can be amortized across many requests. Within a single generation, KV Cache accumulates step by step; across requests, reuse additionally depends on whether the prefix is stable, whether the cache is still within its lifetime, and whether routing sends the request to the instance holding that cache.
“Nearly full hits” is not magic—it’s determined by workload shape: a fixed system prompt with small increments, multi-turn conversations that only append to the tail, and code completion sharing the same file prefix all tend to produce stable prefixes. Conversely, rewriting the prompt every time, inserting dynamic retrieval results at the front, or placing user content before the system prompt will break the longest common prefix and cause hit rates to plummet. Rounding this to “almost free” is not rigorous: output tokens still need to be decoded one by one, uncached increments still require prefill, and the cache itself consumes memory and storage bandwidth, while the service also pays for scheduling, replicas, and eviction. A high hit rate reduces the marginal cost of repeated computation on the input side—it does not turn the entire inference into a zero-cost operation.
What Determines the Hit Rate
Prefix stability. Cache keys are usually exact prefixes of the token sequence (sometimes also including model version, precision, and sampling-independent compute graph configuration). An extra space, one changed character in the system prompt, or retrieval snippets inserted at the front can invalidate all subsequent blocks. In engineering practice, stable instructions should go first, and per-turn varying content should go last.
Block size and granularity. Implementations commonly split the KV cache into fixed-length blocks for indexing. Blocks that are too large fail entirely with minor differences; blocks that are too small raise indexing and copying overhead. Granularity is a trade-off between hit rate and management cost—there is no universally optimal value independent of the workload.
Lifetime and capacity. GPU memory is limited, and hot prefixes are evicted based on recency, prefix frequency, or business priority. Sessions idle too long, instances scale up or down, or requests get routed to another replica—all cause misses. In multi-replica environments, if the cache is not shared, hit rates get fragmented by traffic distribution; with a distributed cache, you pay network read latency, and in extreme cases a remote cache read may not be cheaper than local recomputation.
Batching and concurrency. Continuous batching packs different requests into the same batch. Caches are isolated per request or per prefix—you cannot misapply A’s key-values to B. The higher the concurrency, the fewer hot prefixes fit in memory, creating tension between hit rate and throughput.
Correctness boundaries. KV data is bound to model weights, layer structure, positional encoding, and the processed token sequence. When the model version or inference configuration changes, old caches must be invalidated. Caching can skip repeated computation but cannot skip attention involving new tokens; the numerical path should be consistent with cache-free decoding (small numerical differences from quantization and kernel variations must be accepted or eliminated through evaluation).
Where It Stands
At the algorithmic level, KV Cache is a foundational optimization of decoder-only Transformer inference, not a trick unique to any particular model. The industry broadly implements prefill-decode separation, paged memory management, prefix caching, and cross-request reuse in serving stacks. Differences in maturity mainly show in engineering completeness: whether cache correctness holds under high concurrency, whether stable prefixes achieve high reuse, and whether the system degrades gracefully under memory pressure—not whether the feature exists as a switch.
Reader-perceivable effects can be understood in three tiers, and should not be presented as fixed performance numbers:
- Session-only caching: The same generation no longer recomputes historical tokens, and decoding after the first token is noticeably lighter than a naive implementation. But each new request with a long prompt still requires full prefill.
- Cross-request prefix reuse: Once system prompts and long documents are hit repeatedly, input-side latency and compute consumption drop in proportion to the hit rate, and the weight of “repeated input” in the bill shrinks.
- System-level scheduling: Prefix-aware routing, cache tiering (GPU memory, host memory, external media like object storage), and eviction policies must work together for hit rates to be stable at cluster scale—not just impressive in single-machine demos.
Cold caches on external media increase capacity, but read bandwidth and deserialization costs may offset the benefit; whether it pays off depends on prefix length and reuse frequency.
Practical Usage, Not Hype
Design prompt structure. Put fixed roles, tool protocols, and output formats in the prefix; put user questions, retrieval snippets, and per-turn variations in the suffix. Avoid concatenating timestamps, random numbers, or differently ordered results at the front.
Measure, don’t guess. Track prefill tokens, decode tokens, prefix-hit tokens, cache evictions, and per-request latency separately. Cost reduction is only real when the hit-token ratio stays consistently high and the prefill of uncached portions remains within capacity.
Control the cache footprint. Set size limits and idle expiration for sessions; for very long contexts, consider sliding windows, summarization, or keeping only essential history to prevent the cache from consuming all memory and undermining concurrency. Quantizing the KV cache reduces footprint, but quality degradation must be validated separately.
Evaluate effective cost. Estimate using “uncached input + actual billed weight of cached input + output,” not list price times total tokens. If your workload has short prefixes and major changes each turn, even the best caching won’t deliver order-of-magnitude savings.
Whether you run inference on a cloud model service or a self-hosted inference cluster, treat the cache as part of capacity planning: reserve GPU memory for weights, KV data, and concurrent batches, and make sure monitoring and alerting cover cache hit rate, eviction rate, and the prefill queue. Platforms like Baidu AI Cloud offer general-purpose inference and operations capabilities—elastic compute, logging, and monitoring—but whether the cache actually hits still depends on prompt stability, routing affinity, and whether cache lifetime matches your business. No vendor name alone guarantees that.
Summary
KV Cache turns the key-value data of historical tokens from repeated computation into on-demand reads, making decoding cost depend on newly added tokens rather than the square of the full history. High cross-request hit rates come from stable prefixes, sensible chunking, sufficient cache residency, and affinity-aware scheduling. It can significantly reduce the compute and latency of repeated prefill, thereby changing the effective cost of long-context scenarios—but output decoding, incremental prefill, and cache footprint still cost money. To evaluate a price cut or an “almost all hits” experience, return to the workload: how stable the prefix is, what fraction of tokens are cache hits, and whether memory is being squeezed by the cache. Measuring these three things is far more useful than repeating slogans when judging what level this technology has actually reached.
