LLM Inference Cost Reduction: Caching Mechanisms and Cost Evaluation
Lower LLM service prices and higher cache hit rates do not automatically translate into proportional savings. This article explains the differences between within-sequence KV caching and cross-request prefix caching, examines cache memory requirements and billing metrics, and outlines how to evaluate cost, latency, and quality using real workloads. The key measure is cost per successfully completed business task—not token pricing alone.
1. Break Down Costs Before Evaluating a Price Cut
When an LLM service reduces its price to one-quarter of the previous rate, the immediate assumption is that the same budget can handle four times as many requests. That holds only if the billing categories, input-to-output ratio, request mix, and service quality remain unchanged.
For developers and enterprise users, more useful questions are: Which charges have decreased? How much repeated computation can caching eliminate? And does the change reduce the cost of completing a business task?
A model call typically involves:
- Receiving the input, then tokenizing, validating, and scheduling it.
- Processing the input context to establish the intermediate states needed for generation.
- Generating output incrementally.
- Releasing resources after the request, or retaining cache states that qualify for reuse.
A reduction in one price category does not imply an equivalent reduction in the overall bill. Uncached input charges, output charges, cached input charges, and any applicable cache storage charges should be calculated separately.
Lower prices may also encourage applications to call the model more often, use longer contexts, or generate more content. In that case, the total bill can increase. The right unit of evaluation is not just “cost per million tokens,” but also “cost per successfully completed business task.”
2. Distinguish Two Commonly Confused Types of Caching
Before discussing cache hit rates, identify where caching takes place.
Within-Sequence KV Caching: Avoiding Repeated Computation During Generation
Text generation in causal-attention models is typically autoregressive: the model predicts the next token from the current context, then continues predicting subsequent tokens.
A token is a basic unit produced by the tokenizer; it does not necessarily correspond to a complete word or character.
During attention computation, each layer constructs query, key, and value vectors, conventionally written as Q, K, and V.
If the model reprocessed the entire context from scratch for every generated token, it would repeat substantial computation at historical positions. In common causal-attention models, earlier tokens cannot attend to future tokens. As long as model parameters, positional settings, and other relevant computation conditions remain unchanged, the previously computed keys and values can therefore be reused.
KV caching works as follows:
- Process the input context and generate historical K and V states for each layer.
- Read the existing cache when generating a new token.
- Compute the representations for the newly added position.
- Perform attention using the current query and the historical keys and values.
- Append the new position’s K and V states to the cache.
This substantially reduces repeated computation at historical positions. However, it does not mean that each generation step has a cost independent of context length simply because only one new token is being processed.
In common full-attention implementations, the new position still needs to access historical keys and values. Attention computation and cache-reading overhead generally increase as the context grows. KV caching removes redundant computation; it does not eliminate long-context costs.
Cross-Request Prefix Caching: Reusing Shared Input Across Calls
Cross-request prefix caching addresses a different problem: whether multiple requests submit the same beginning of an input.
For example, every request in an enterprise application might contain:
- The same system role instructions.
- The same output format constraints.
- The same tool definitions.
- The same fixed examples.
- The user’s question at the end.
If the shared portion meets the service’s cache reuse requirements, later requests can reuse its intermediate states rather than processing that input again.
Although both mechanisms may use KV states, their scope differs:
| Comparison | Within-sequence KV caching | Cross-request prefix caching |
|---|---|---|
| Primary purpose | Accelerate successive decoding steps within one generation | Reduce repeated input processing across requests |
| Reused content | Historical positions in the current sequence | A shared prefix across different requests |
| Key requirement | Historical states remain valid for subsequent generation | The prefix and relevant execution conditions satisfy reuse requirements |
| Main limitation | Cache memory usage grows with sequence length | Reuse depends on prefix changes, retention periods, capacity, and scheduling |
A “cached input tokens” metric in an API response or bill must be interpreted according to the service documentation. It should not be equated directly with the amount of within-sequence KV caching used internally by the model.
3. Why Caching Saves Compute but Consumes GPU Memory
Caching trades storage for computation. Retaining more intermediate states can avoid more repeated work, but also consumes more device memory.
For common attention architectures, the KV cache size for a single sequence can be approximated as:
Cache size in bytes ≈ 2 × number of layers × number of KV heads × head dimension × sequence length × bytes per element
Here:
- The factor of 2 accounts for both keys and values.
- The number of KV heads is not necessarily equal to the number of query heads.
- Bytes per element depend on the data type actually used for the cache.
- Concurrent sequences further increase total memory usage.
Consider an illustrative configuration:
- 32 layers.
- 32 KV heads.
- A head dimension of 128.
- A context length of 4,096 tokens.
- 2 bytes per cached element.
The theoretical cache size for one sequence is:
2 × 32 × 32 × 128 × 4,096 × 2 = 2,147,483,648 bytes, or approximately 2 GiB.
Processing 10 sequences of the same length concurrently, with no cache sharing between them, would require approximately 20 GiB of theoretical cache storage.
These figures illustrate the formula; they do not represent the actual configuration or capabilities of any particular service. Real deployments must also account for model weights, temporary computation buffers, memory allocation metadata, fragmentation, and other runtime overhead.
The formula does not apply to every model architecture. Fewer KV heads can reduce cache capacity requirements, while different attention mechanisms or intermediate-state compression methods may change how states are stored. Layer count and query head count alone are not enough to accurately estimate cache usage for an arbitrary model.
4. A Near-100% Cache Hit Rate Does Not Make Requests Free
A high cache hit rate can be valuable, but the measurement must be clearly defined.
Request Hit Rate and Token Hit Rate Are Different
A request-level cache hit rate can be defined as:
Requests with at least one cache hit ÷ total requests
An input-token cache hit rate can be defined as:
Cached input tokens ÷ total input tokens
A request that reuses only a short prefix may still count as a cache-hit request. A high request hit rate therefore does not mean that most input tokens are being reused.
Conversely, if every request contains a long fixed instruction block and only a small portion at the end changes, the input-token hit rate may be very high.
For example, suppose a request contains 9,900 fixed prefix tokens and 100 new tokens. If the entire prefix hits the cache, the input-token hit rate is 99%. That describes this particular input structure; it does not demonstrate that every workload can achieve the same result.
Cache Hits Can Still Incur Charges
A simplified billing model is:
**Total cost = uncached input volume × uncached input price
- cached input volume × cached input price
- output volume × output price
- other applicable charges**
A lower price for cached input does not mean that cached input is free. Output generation typically still requires inference computation, and reading, maintaining, and storing cached states still consumes resources.
The following claims are therefore misleading:
- “A 99% cache hit rate reduces total cost by 99%.”
- “Reducing input prices to one-quarter reduces every task’s cost to one-quarter.”
- “Once the prefix is cached, long contexts have no cost.”
Actual savings depend on the original cost breakdown. If output charges account for a large share of the bill, input-side optimization has a limited effect on total cost.
5. Cache Hit Rates Depend on Workload and Engineering Design
High cache hit rates usually reflect both stable application inputs and a service’s ability to reuse those inputs effectively.
Place Stable Content Near the Beginning
Prefix caching depends on a continuous, reusable beginning. Inserting a random identifier, current timestamp, or dynamic field before otherwise stable instructions may prevent a long shared prefix from being reused.
A useful arrangement is often:
Fixed rules → fixed format constraints → fixed examples or documents → dynamic business data → current question
This is not a universal prompt layout. The principle is to separate stable and frequently changing content without compromising task quality.
Equivalent Meaning Does Not Guarantee a Cache Match
Cache matching generally relies on a specific input representation, not on whether two passages have similar meanings.
Extra spaces, different line breaks, changes in field order, and template revisions may affect matching. Standardize how shared templates are constructed so that different code paths do not assemble the same rules into different text.
Matching granularity and reuse conditions depend on the implementation. Do not assume every service handles them identically.
Retention Periods and Request Intervals Matter
Identical prefixes make reuse possible, but do not guarantee that the cache still exists.
Cache misses can occur because capacity is insufficient, entries have been evicted, requests are too far apart, or the execution environment has changed. Test bursty traffic and low-frequency requests separately. Results from consecutive repeated calls should not be treated as representative of an entire day’s workload.
Security Isolation Takes Priority Over Hit Rate
Enterprise caches may contain internal knowledge, customer data, or user conversations. Reuse must respect authentication, authorization boundaries, and data retention requirements.
Do not combine sensitive content from users with different permissions into a shared prefix just to improve hit rates. Manage general instructions and sensitive business data separately, and avoid logging unnecessary raw content.
6. Practical Optimization Steps for Developers
Remove Unnecessary Context Before Optimizing Cache Reuse
A lower cached-input price does not justify retaining redundant input.
Excessively long contexts can increase cache memory requirements and attention access costs, and may make it harder for the model to focus on relevant information. First remove repeated instructions, outdated conversation history, and material unrelated to the current task. Then optimize reuse of the content that remains necessary.
For long-document applications, select passages relevant to the question instead of submitting the entire document by default. For extended multi-turn conversations, periodic summaries can help manage history, provided that critical facts are preserved.
Version Shared Prompt Templates
Maintain shared prompts independently and record their versions, reasons for changes, and validation results.
Do not reject necessary rule updates merely to preserve cache hit rates. After an update, reassess task quality, cost, and caching behavior to determine whether the change improves the overall outcome.
Test Cold and Warm Caches Separately
Cold-cache tests measure behavior on the first request or when a cache is unavailable. Warm-cache tests measure behavior when a shared prefix is already available for reuse.
At a minimum, test:
- The first request.
- Consecutive requests with the same prefix.
- Changes near the end of the prefix.
- Changes at the beginning of the prefix.
- Repeated requests after a longer interval.
- Stability under high concurrency.
Testing only ideal consecutive-repeat scenarios can overestimate production savings.
Track Cost, Latency, and Task Quality Together
Useful metrics include:
- Total input tokens.
- Cached and uncached input tokens.
- Output tokens.
- Time to first token.
- Total request duration.
- Request success rate and retry count.
- Task acceptance rate.
- Cost per successful task.
Prefix reuse generally helps reduce input-processing overhead, but total response time also depends on output length, scheduling, and resource contention. A single latency metric is not enough to determine whether a caching optimization has succeeded.
7. How to Determine Whether a Price Cut Benefits Your Application
Evaluate model service pricing changes in the following order.
Step 1: Confirm which prices changed.
Determine whether the adjustment applies to cached input, uncached input, output, or other charges, and verify the billing units.
Step 2: Characterize real requests.
Measure the fixed-prefix share, dynamic input length, output length, call frequency, and concurrency.
Step 3: Establish a baseline.
Record cost, latency, retries, and task completion under the current configuration. New-scheme results need a meaningful comparison.
Step 4: Run a limited validation.
Use real business samples and cover cold caches, warm caches, and permission-isolation requirements.
Step 5: Compare cost per successful task.
Include model charges, failed attempts and retries, and necessary supporting resource costs rather than comparing a single listed price.
A price cut delivers practical value only when business quality remains stable, latency meets requirements, and the cost per successful task actually decreases.
8. Conclusion: Focus on Verifiable Cost Savings
Lower model service prices reduce barriers to adoption, while caching allows some computation on repeated context to be reused. But pricing, cache hit rates, and total costs do not have a simple one-to-one relationship.
Within-sequence KV caching reduces repeated computation during generation. Cross-request prefix caching reuses shared input across separate calls. Both can improve resource efficiency, but remain constrained by context length, cache capacity, input stability, and security boundaries.
For developers, the most effective approach is to clarify the billing structure, optimize input organization, and then validate cost, performance, and quality using real workloads. Only by evaluating these factors together can you distinguish a lower listed price from sustainable engineering savings.
