KV Cache for LLM Inference: How It Cuts Costs and How to Use It
This article explains why large language model inference costs are dropping and how KV Cache makes that possible. It breaks down the real cost of a request, shows why autoregressive generation repeats computation, and walks through how KV Cache stores key and value vectors to avoid recomputation. It also provides a formula for estimating KV Cache memory usage, explains why cache hit rate is the key metric, and lists practical engineering steps for prefix design, batching, capacity planning, and observability.
1. What Falling Inference Prices Reveal About Real Costs
When LLM inference services drop in price by an order of magnitude, it is usually not just a commercial subsidy. It is the result of significantly compressing the compute and GPU memory consumed per request. To understand this, break the cost of a single request into three parts: GPU memory occupied by model weights, compute required to generate each token, and the batching and scheduling overhead paid for throughput. Weights are a fixed cost, while compute and memory overhead depend heavily on how repetitive the input sequences are. When many requests share the same prefix (for example, a long system prompt, a fixed template, or repeated questions over a small set of documents), a large portion can theoretically be reused, which creates the engineering basis for lower costs.
So when evaluating the cost-effectiveness of an inference service, do not look only at the price per token. Look at its actual performance in cache reuse, batching efficiency, and long-context management. Price is the result; resource utilization is the cause.
2. Why Autoregressive Generation Is Expensive: The Source of Repeated Computation
Text generation is an autoregressive process: each step produces one token, appends it to the end of the sequence, and generates the next one. For example:
step1: input [today weather] -> output isstep2: input [today weather is] -> output goodstep3: input [today weather is good] -> output ...
In the attention mechanism, every token produces three vectors: Q (query), K (key), and V (value). The problem is that step2 needs the K and V of the previous three tokens, which were already computed in step1 and are exactly the same. Without caching, every step recomputes K and V for the entire sequence, and the computation accumulates quadratically with sequence length. This is the root cause of why long-context inference is expensive and slow.
3. How KV Cache Works
The idea behind KV Cache is straightforward: after computing a token, write its K and V into GPU memory. Later steps only compute the Q, K, and V of the newest token, use the new Q with all cached K to compute attention scores, and then weight the cached V.
# Pseudocode: single-step decoding with KV Cachekv_cache = [] # one (K, V) set per layerfor step in range(max_new_tokens):q, k, v = model.forward(last_token, kv_cache) # compute only the new tokenkv_cache = append(kv_cache, (k, v)) # append instead of recomputelast_token = sample(attention(q, kv_cache))
The benefit is that per-step computation drops from “process the whole sequence” to “process one token,” improving both latency and throughput. The cost is that GPU memory usage grows linearly with sequence length and concurrency.
4. Estimating KV Cache Memory Usage
The size of KV Cache can be estimated with a general formula:
KV bytes = 2 × layers × heads × head_dim × sequence_length × bytes_per_value
For 32 layers, 32 heads, head dimension 128, and FP16 (2 bytes): per token per layer is 2 × 32 × 128 × 2 = 16384 bytes (16 KB); at sequence length 4096, that is about 16 KB × 32 × 4096 ≈ 2 GB; with 10 concurrent requests, about 20 GB. In long-text, high-concurrency scenarios, the cache itself can approach or even exceed the memory used by weights, becoming the real bottleneck. In practice, teams control this overhead with paged memory management, quantization, and limits on maximum context length and concurrency.
5. Why Cache Hit Rate Is the Core Metric
Hit rate is the fraction of a new request’s prefix that can be reused from existing cache. When system prompts, tool definitions, and retrieval templates are highly consistent, the hit rate can approach saturation, meaning most prefill computation is skipped and only a small amount of incremental computation remains. This explains why the cost feels like it drops sharply “after a few days of use”: the hit rate depends on real traffic patterns and needs time to accumulate and for scheduling strategies to settle in. It does not take effect on day one.
Note that a high hit rate does not change model output quality; it only changes the resource consumption path. It also depends heavily on the business scenario, with limited benefit when templates are scattered and prefixes differ.
6. Engineering Practices
- Prefix normalization: put stable content (system instructions, examples, documents) first and keep the order fixed; avoid inserting dynamic fields in the middle, which breaks reuse.
- Session-level reuse: keep the history prefix stable across multi-turn conversations and only append new content.
- Batching and scheduling: group requests by prefix to raise the reuse rate within a batch, balancing latency and throughput.
- Capacity planning: use the formula above with target concurrency and context length to work backward to memory requirements, leaving headroom for fragmentation and peaks.
- Observability: track hit rate, cache usage, and queue latency through logging services and monitoring alerts to close the tuning loop.
7. Conclusion
The continued drop in inference costs is fundamentally a gain in resource efficiency from cache reuse and scheduling optimization. For developers, the transferable skill is to understand the principles and memory model of KV Cache, design reusable prefix structures based on business characteristics, and drive capacity and cost planning with metrics. With this framework, you can shift from “looking at price” to “looking at utilization” when evaluating any inference service and make more robust technical choices.
