KV Cache in LLM Inference: How It Works and How to Improve Prefix Hits
KV cache avoids recomputing attention keys and values during autoregressive decoding. This article explains why decoding repeats work without cache, how to size KV memory, what prefix hit rate actually saves, how to separate cost from latency, and how to ship prefix reuse without treating a high average hit rate as free compute.
In inference serving, the expensive part is often not whether the model can answer, but how many times the same context is recomputed. Clarifying key-value cache (KV cache) and prefix hit rate is how you tell a billing change from a cheaper compute path.
Why autoregressive generation recomputes work
A typical decoder emits one new token at a time, appends it to the sequence, and predicts the next. Without cache, step n runs attention over the full length-n sequence: every token forms query Q, key K, and value V. Historical K and V were already computed on the previous step and are identical if weights and inputs are unchanged, yet they are recomputed for the whole sequence. The longer the sequence, the worse the duplication; decode FLOPs are dominated by history.
KV cache writes a token’s K and V to GPU memory per layer once they are computed. The next step computes Q, K, and V only for the newest token, attends the new Q against all cached K, and weighted-sums cached V. Work shifts from “full sequence every step” to “mostly the new token.” Prefill still builds cache for every prompt token; decode is mainly one new token per step plus reads and writes of a growing cache.
Estimating GPU memory
A common order-of-magnitude estimate for one sequence (implementations differ by architecture, e.g. shared KV heads):
cache bytes ≈ 2 × layers × KV heads × head dim × sequence length × bytes per element
The leading 2 is K and V. Illustration only, not a specific model: 32 layers, 32 KV heads, head dim 128, sequence 4096, FP16 (2 bytes). K+V per token per layer is about 2 × 32 × 128 × 2 = 16384 bytes (16 KB). Times layers and length: about 16 KB × 32 × 4096 ≈ 2 GB. Batch 10 at that full length is about 20 GB of KV alone, often a memory bottleneck before weights.
Long context, large batch, and high precision all grow cache. Usual levers: fewer KV heads or grouped sharing, lower cache precision, keep only needed history, and swap inactive blocks to host memory or object storage. Any memory save must be judged against quality loss and extra movement latency, not only a smaller formula.
What hit rate is optimizing
Ordinary KV cache avoids recomputing history inside one generation. Extra gains come from prefix reuse across requests: system prompts, tool specs, long documents, and unchanged prefixes of multi-turn chats can keep K and V. If a new request’s prefix matches cache, prefill skips that span, computes only the miss suffix, then decodes.
Hit rate is roughly reusable prefix tokens over tokens that need cache this request. When it is high, long-prompt prefill collapses toward incremental work; time to first token and that compute cost drop. The model did not shrink; the same prefix was not rebuilt as K and V.
High hits usually need all of: byte-identical prefixes (an extra space or different serialization can miss); cache not evicted; the request scheduled onto an instance that still holds that prefix. “Theoretically reusable” is not “hit in production.” Stable system prompts, fixed document chunks, and session stickiness raise hits; rewritten prompts, frequent scale-out, and cache smaller than hot prefixes drop them fast.
Separate cost from latency
Uncached tokens still need full prefill; hits are mostly cache reads plus later attention. If pricing splits miss vs hit tokens, reuse lowers marginal cost. If billing is output tokens only, the user bill may not fall, but GPU occupancy and queue time still can. To judge “cheaper,” look together at how much input is a stable prefix, TTFT after hits, decode throughput, and whether cache memory crowds out concurrency.
Cache has a cost. After hits rise, hot prefixes occupy memory for a long time and fewer independent long requests fit. Refusing eviction to protect hits can hurt cluster throughput. Give prefix cache its own capacity, TTL, and eviction, and monitor hit rate, evictions, and miss tokens per request—not a single near-100% average. Averages can be inflated by short repeated system prompts while long-document jobs still miss almost everything.
How to use this in production
Ship in this order rather than chasing peak hit rate first.
Stabilize reusable prefixes. Put role, output format, and tool lists at the front with stable serialization; put user questions and volatile fields last. Unstable prefixes make cache keys useless.
Control cache keys. Keys should cover model version, precision, tokenization, and a prefix digest. After a model or template upgrade, old cache must invalidate so wrong K/V are not applied to new weights.
Split session cache and global prefix cache. Multi-turn chats keep generated history per session; cross-user sharing should be public prompts without private data. User documents and account data must not enter a global cache for hit rate.
Budget memory. Use the formula at peak length and target concurrency to set batch size, max context, and whether to drop precision. If the budget is tight, shorten unused history before blindly growing batch.
Watch percentiles, not only means. Split hit rate and TTFT for short prompts, long documents, and multi-turn chats. One class hitting well does not mean the tail is faster.
Illustrative prefill control flow (not a platform API):
function prefill(tokens):prefix_len = longest_cached_prefix(tokens, model_version)if prefix_len > 0:kv = load_kv(tokens[0:prefix_len])else:kv = empty_kv()for t in tokens[prefix_len:]:q, k, v = project(t)kv = append(kv, k, v)attend(q, kv)store_kv(tokens, kv, model_version)return kv
Common mistakes
A high cache hit is not “model compute for free.” Every new decode token still reads full (or compressed) history and runs attention; long sequences still cost bandwidth and attention. Hits mainly skip repeated prompt prefill.
Another mistake is adding cache without changing prompt structure. Timestamps, randoms, or reordered paragraphs at the start never align prefixes; cache is useless while memory stays full.
Correctness: sampling parameters usually do not change already computed K/V, but a different model, quantization, tokenizer, or truncation must be a different cache. If a user rewrites an earlier turn, later cache is invalid; you cannot only append new tokens.
Whether the optimization actually landed
Replay the same request set before and after: total miss tokens, TTFT P50 and P95, requests completed per unit time, peak GPU memory. If miss tokens drop and latency improves without throughput collapsing under cache occupancy, prefix reuse is real. High hits with worse throughput: shrink capacity or TTL. Bill down with unchanged latency is more likely a pricing change than saved compute.
KV cache is a basic inference mechanism: it trades GPU memory for repeated compute; prefix reuse extends that trade across requests. Putting the size formula, hit conditions, and memory budget together shows whether a high hit rate saved prefill or only moved cost into memory and scheduling.
