LLM Inference Cost Optimization: How KV Cache and Prefix Caching Shape Effective Pricing
This article explains how to evaluate sharp reductions in LLM inference pricing by looking beyond the headline price per million tokens. It covers the effective cost of uncached input, cache reads, cache writes, and output; why autoregressive generation repeats historical computation; how KV cache and cross-request prefix caching reduce prefill work; why cache hit rate and memory footprint determine the real benefit; how to assess a roughly fourfold price cut; and how to use real workload data, latency, throughput, and stability metrics to verify whether a price reduction lowers effective cost.
When an LLM inference service announces a sharp price reduction—sometimes down to roughly one quarter of its previous level—the immediate reaction often falls into one of two extremes. One view treats it as a broad technological benefit; the other suspects that service quality or model capability may have been reduced. A more professional assessment returns to the cost structure of inference systems: the list price is only the entry price. Real cost is determined by input tokens, output tokens, context length, cache reads and writes, concurrency scheduling, latency requirements, and other factors. For developers, the key question is not simply “how much per million tokens,” but whether effective cost, throughput, and latency are all acceptable under their own workload.
1. Evaluate a Price Cut Through “Effective Cost”
LLM inference billing usually has more than one dimension. On the input side, prompt tokens are processed in prefill; on the output side, decoding produces tokens one by one. Long contexts significantly increase attention computation and memory usage, while high concurrency tests batching and scheduling capabilities. If a service provides context caching or prefix caching, cache-hit portions may be billed at different prices, while cache-miss portions still require full computation. As a result, even when two model services advertise similar price cuts, the real savings can differ greatly across workloads.
A simplified formula can describe effective cost:
Effective cost = uncached input cost + cache-hit read cost + amortized cache-write cost + output cost
Let h be the hit rate for reusable prefixes among input tokens, I the number of input tokens, and O the number of output tokens. Let P_in, P_out, P_cache_read, and P_cache_write represent the unit prices for uncached input, output, cache reads, and cache writes, respectively. Then the effective cost per output token can be approximated as:
Cost_per_output = [P_in * I * (1 - h) + P_cache_read * I * h + P_cache_write * W + P_out * O] / O
Here, W is the number of cache-write tokens. This formula shows that workloads with high hit rates can benefit more from caching. Short requests, low-reuse traffic, and workloads with frequently changing prefixes dilute the benefit. To judge whether a price cut “to one quarter” is truly meaningful, you must substitute your workload into the formula rather than looking only at the advertised unit price.
2. Why Autoregressive Generation Repeats Computation
Language model text generation is an autoregressive process: the model generates one token at a time, appends it to the sequence, and then generates the next token. Without optimization, suppose step 1 takes “The weather today” as input and the model computes “is.” Step 2 takes “The weather today is” as input and computes “nice.” Step 3 takes “The weather today is nice” and continues to the next token. The problem is that each step performs attention over the entire sequence, even though historical tokens were already processed in step 1.
In the attention mechanism, each token produces three vectors: Q, K, and V—query, key, and value. When step 2 recomputes the K and V for the first three tokens, the results are exactly the same as in step 1. The longer the sequence, the more repeated computation occurs. In long-context tasks, multi-turn conversations, code-repository question answering, and similar scenarios, repeated prefill can become one of the main sources of cost.
3. How KV Cache Turns “Full Recomputation” into “Compute Only the New Token”
The core idea of KV Cache is straightforward: after computing each new token, cache its K and V in GPU memory. On the next inference step, the K and V for historical tokens are read directly from the cache instead of being recomputed. Only the newly generated token needs full Q, K, and V computation. The new Q is then used to compute attention scores against all cached K values and multiplied by the cached V values. As a result, the computation per step changes from “process the entire sequence” to “mainly process the latest token,” significantly improving inference speed.
Pseudocode can be simplified as follows:
cache_k = []cache_v = []for step in range(max_new_tokens):q, k, v = model.compute_qkv(current_token)cache_k.append(k)cache_v.append(v)score = softmax(q @ concat(cache_k).T / sqrt(head_dim))out = score @ concat(cache_v)current_token = sample(model.project(out))
It is important to distinguish two concepts. KV Cache within a single request avoids recomputing historical K/V values during token-by-token generation. A cross-request prefix cache goes further by reusing already computed KV values for identical prompt prefixes, avoiding repeated prefill for each request. The “cache hit rate” commonly discussed in price-cut analyses usually refers more closely to the latter: the system identifies a stable prefix shared by multiple requests and reuses its computed results.
4. Why Cache Hit Rate Becomes a Cost Lever
Cache hit rate can be defined as the number of reusable prefix tokens in the input divided by the total number of input tokens. High hit rates often come from stable system prompts, fixed tool descriptions, multi-turn conversation history, fixed retrieval-augmented generation templates, code-repository context, and similar sources. After a hit, the system does not need to perform full prefill over the repeated prefix, reducing computation and time to first token.
However, a high hit rate is not free. Caches need storage, indexing, retrieval, eviction, and consistency management. Cache writes may also incur cost. Long-context caches consume GPU memory or external storage. A slight change in the request prefix can lower the hit rate. Therefore, a high hit rate is the result of system capabilities and workload usage together, not magic created by a single model parameter.
For business workloads, common ways to improve hit rate include:
- Keep system prompts stable.
- Preserve a fixed prefix across multi-turn conversations.
- Use fixed templates and document ordering in retrieval-augmented generation.
- Avoid inserting timestamps, random IDs, and other volatile content near the beginning of the prompt.
- Put stable instructions first and dynamic content later.
These practices reduce prefix changes and increase the probability of reuse.
5. Memory Footprint and Scheduling: Where the Limits of High Hit Rates Lie
KV Cache is not free. Its memory usage can be estimated with the following formula:
KV cache bytes = 2 × layers × heads × head_dim × sequence_length × batch_size × bytes_per_element
The factor 2 represents the two caches for K and V. Consider a model with 32 layers, 32 heads, head dimension 128, sequence length 4096, FP16 precision, and batch size 1:
def kv_cache_bytes(layers, heads, head_dim, seq_len, batch, bytes_per_elem=2):return 2 * layers * heads * head_dim * seq_len * batch * bytes_per_elemprint(kv_cache_bytes(32, 32, 128, 4096, 1))# 2147483648 bytes, about 2 GB
At batch size 10, this is about 20 GB. For long texts or large batches, KV Cache may consume more memory than the model parameters themselves and become a concurrency bottleneck. Real systems therefore need paged or block-based cache management, prefix sharing, cache quantization, eviction policies, continuous batching, and other general optimizations to balance hit rate, memory usage, throughput, and latency.
6. How to Evaluate a “Fourfold” Price Reduction
If a large price reduction comes from cache reuse, batch scheduling, memory management, model architecture optimization, and economies of scale, it is more likely to reflect the maturation of inference systems engineering rather than pure marketing. For workloads with high reuse, long contexts, and multi-turn conversations, the prefill savings from cache hits can be substantial. For short requests, low-reuse traffic, and frequently changing prompts, the effective cost reduction will be much smaller.
An evaluation should focus on four points:
- Billing details. Check whether cache writes, cache reads, uncached input, and output are priced separately.
- Workload hit rate. Load-test real requests rather than estimating with idealized prompts.
- Latency and throughput. A price cut should not come at the cost of worse time to first token or stricter rate limits.
- Stability. Pay attention to tail latency under cold starts, cache eviction, and long-context concurrency.
Developers can use the following pseudocode for an initial estimate:
def effective_cost(input_tokens, output_tokens, hit_rate,p_in, p_out, p_cache_read,cache_write_tokens, p_cache_write):reusable = input_tokens * hit_ratefresh = input_tokens - reusableinput_cost = fresh * p_in + reusable * p_cache_readwrite_cost = cache_write_tokens * p_cache_writetotal = input_cost + write_cost + output_tokens * p_outreturn total / max(output_tokens, 1)
Only by substituting real input lengths, output lengths, hit rates, and cache-write ratios can you determine whether a price reduction genuinely covers your scenario.
7. Practical Recommendations: Turn a Price Cut into Verifiable Returns
- Establish baseline workloads. Mix short requests, long-context requests, multi-turn conversations, and high-concurrency traffic. Record time to first token, per-output-token latency, throughput, error rate, and cache hit rate separately.
- Optimize prompt structure. Place stable prefixes first and dynamic content later, reducing random fields that disrupt caching.
- Control context length. Irrelevant history increases both computation and cache usage; longer context is not always better.
- Monitor cache efficiency. Beyond hit rate, track cache write volume, eviction rate, read-hit latency, and storage cost.
- Run A/B measurements. Use the effective-cost formula to compare real bills before and after the price cut instead of comparing unit prices alone.
8. Conclusion
Large price reductions for LLM inference services are worth acknowledging, but they should not be equated simply with “fully free” or “lower quality.” A more reasonable evaluation asks whether, under a specific workload, cache hit rate, batching and scheduling, and memory management can translate the advertised price cut into lower effective cost. For developers, the most reliable approach is to measure effective cost using real production data, optimize stable prefixes and context structure, and monitor latency, throughput, and stability at the same time. Only then can teams make rational decisions amid pricing changes rather than being led by a single unit-price number.
