The Key to Lowering LLM Inference Costs: KV Cache Optimization in Practice
This article explains why sustainable price reductions in large language model (LLM) inference depend on real efficiency gains rather than short-term discounts, and why KV Cache is the central mechanism involved. It covers what KV Cache stores during autoregressive generation, how to estimate its memory footprint, why cache hit rate drives marginal cost, and six general optimization paths including prefix reuse, paged cache management, quantization, sparse attention, grouped-query attention, and observability. Readers will also find practical steps for auditing prefixes, measuring hit-rate baselines, and validating throughput and memory usage under load.
1. What Inference Cost Really Consists Of, Beyond the Price Cuts
Recent discussions about sharp price reductions for certain LLM services often attribute the change to subsidies or promotions. From an engineering perspective, however, inference pricing has always been driven by the compute and memory cost per token. Prices only have room to fall permanently when resource utilization improves by an order of magnitude. So the real test of whether a “permanent price cut” is sustainable is whether it rests on genuine efficiency gains rather than a temporary giveback.
In autoregressive generation, cost breaks down into three parts: the floating-point work of matrix multiplications, memory capacity and bandwidth pressure, and idle resources caused by request scheduling. The third is the most easily overlooked. When memory is fully occupied by long contexts, the system cannot run more requests concurrently, GPU compute sits idle, and the cost per token stays high. KV Cache, the context cache, is the core mechanism that affects all three at once.
2. What KV Cache Actually Stores
When a Transformer generates each token, it computes three sets of vectors for every position in the sequence: query (Q), key (K), and value (V). Attention compares the current position’s Q against the K of all previous positions, then takes a weighted sum over V.
Autoregressive generation advances one token at a time. Given the input “The weather today is”, the model produces “nice”; given “The weather today is nice”, it produces “and”. The problem is that in the second step, the K and V of the first three positions are identical to the first step, yet they are computed again. The longer the sequence, the worse this repeated waste becomes, and overall complexity degrades from linear to nearly quadratic.
KV Cache takes a direct approach: the K and V computed for each position are written to memory and retained. Later steps compute Q, K, and V only for the new token, and the new Q reads the cached historical K and V to complete attention. Per-step work drops from processing the whole sequence to processing a single token, which is the main source of higher inference throughput.
Illustrative pseudocode:
# Without cache: recompute the full sequence at every stepfor _ in range(max_new_tokens):q, k, v = model(ids) # full-sequence forward passids = append(ids, sample(q))# With cache: reuse historical K/Vcache = empty_kv_cache()for _ in range(max_new_tokens):q, k, v = model(last_token, cache) # forward pass for the new token onlycache.append(k, v)last_token = sample(q)
3. Estimating the Memory Footprint
KV Cache size can be approximated as:
KV bytes = 2 × num_layers × num_kv_heads × head_dim × sequence_length × bytes_per_value × concurrency
Take 32 layers, 32 attention heads, a head dimension of 128, and FP16 (2 bytes) as an example. Per token per layer, that is 2 × 32 × 128 × 2 = 16384 bytes, or 16KB. Across 32 layers, a sequence length of 4096 adds up to roughly 2GB, and 10 concurrent requests come to about 20GB. This excludes weights, activations, and framework fragmentation. In long-context scenarios, the cache can easily exceed the size of the weights themselves and become the real bottleneck.
Note that with structures such as grouped-query attention (GQA), the number of KV heads is smaller than the number of query heads, so cache usage drops significantly. Actual numbers must be based on the published architecture parameters of the target model; a single formula cannot be applied universally.
4. Why Cache Hit Rate Is the Core Metric
When multiple requests share the same prefix, such as the same system prompt, the same lengthy document, or the same code repository context, the K and V for that prefix need to be computed only once and can be reused by subsequent requests. A higher hit rate means less repeated compute, more concurrency that fits in memory, and lower marginal cost. The experience of something feeling nearly free after a few days is essentially a hit rate approaching 1 in workloads with heavy prefix reuse, which sharply reduces the amortized cost per token.
A high hit rate does not happen automatically. It depends on three conditions: request prefixes are byte-for-byte identical; the scheduling policy routes requests with the same prefix to the same instance or the same cache pool; and the eviction policy keeps hot prefixes resident. If any condition is not met, the hit rate will drop noticeably.
5. General Optimization Paths
- Prefix reuse and prompt normalization: place stable content first and variable content last, and keep timestamps and random IDs out of the prefix.
- Paged cache management: split the cache into fixed-size blocks allocated on demand to reduce fragmentation and reserved waste.
- Cache quantization and low-precision storage: reduce cache bytes within an acceptable precision range, trading capacity for concurrency.
- Sparse and windowed attention: retain cached entries only for key positions in very long contexts to control the memory growth curve.
- Structured attention designs: compress the number of KV heads with GQA or multi-query attention.
- Scheduling and observability: build monitoring and alerting around hit rate, cache residency time, and queue latency, and use general capabilities such as logging and alerting services to locate long-tail requests.
6. Practical Recommendations and Conclusion
For enterprise users, judging whether a price cut is sustainable means looking at whether the provider discloses its caching mechanism, concurrency capacity, and rate-limiting policy, not just the unit price. On the engineering side, the actionable sequence is to start with a prefix audit and a hit-rate baseline measurement, then introduce paging and quantization, and finally validate throughput and memory levels with load testing. On platforms such as Baidu AI Cloud, you can combine general capabilities like container platforms, object storage, and monitoring and alerting to build a reproducible load-testing and cost dashboard.
The conclusion is clear: the long-term driver of lower inference prices is the resource efficiency gained from cache reuse. Understanding and actively optimizing KV Cache is the right way to turn “cheap” into “sustainably cheap.”
