LLM Cache Hit Explained: How KV Cache Works and How to Optimize Token Billing
In identical LLM API usage scenarios, token costs can differ by tens of times between developers. The key factor is not business logic complexity but the cache hit mechanism in inference systems. This article explains the KV Cache principle behind cache hits, compares three mainstream cache pricing strategies, and shares practical Prompt design and engineering techniques—such as placing static content first and dynamic content last—to maximize cache hit rates and reduce AI compute costs.
In identical LLM API call scenarios, the token fees paid by different developers or enterprises can vary by tens of times. The core factor behind this gap is not the complexity of the business logic, but a critical mechanism in LLM inference systems — the cache hit. Understanding this mechanism not only helps enterprises control AI compute costs, but is also a required course for production-grade LLM engineering.
1. The Technical Principle Behind Cache Hits: The KV Cache Mechanism
To understand how cache hits affect costs, we first need to know what a large model actually does during inference. Most mainstream LLMs today are built on the Transformer architecture, whose core Self-Attention mechanism must reference all preceding context information every time it generates a new token.
At the mathematical level, the model converts the input token sequence into Key (K) and Value (V) matrices. During autoregressive generation, if every generation step had to recompute the KV matrices of all previous tokens, the computational cost would grow quadratically with context length — an enormous waste of compute.
To solve this performance bottleneck, the industry widely adopted the KV Cache mechanism: the system stores already-computed KV matrices in memory or on disk. When a subsequent API request carries a prefix that is exactly identical to a historical request, the model does not need to run the forward pass again. Instead, it directly reads and reuses the corresponding KV matrices from the cache.
This mechanism creates a win-win situation: the model provider saves extremely expensive GPU compute, and the developer receives a significant billing discount because of the reduced compute consumption. That is the essence of a “cache hit.”
2. How Cache Hits Reshape the Token Billing Model
LLM API billing is no longer a simple “pay per character” model. When counting token usage, providers divide input tokens into “cache hit” and “cache miss” portions and apply differentiated pricing. Looking at mainstream LLM services, cache billing rules generally fall into three strategies:
- Aggressive discount strategy: Some providers adopt aggressive pricing. Thanks to highly efficient underlying cache architectures (such as disk-based caching), the price of cache-hit tokens can be as low as one-thirtieth of the standard cache-miss price. This strategy is the most user-friendly, is typically enabled by default, and requires no code changes from developers. It suits high-frequency, repetitive call scenarios.
- High discount with conditions: Some leading models offer discounts of up to 90% (i.e., 10% of the standard price), but with multiple conditions attached. First, when content is written to the cache for the first time, a “cache write fee” is charged at 25% above the standard input price. Second, the cache usually has a short time-to-live (e.g., 5 minutes); once it expires without a hit, the cache is cleared. This model demands very high request concurrency and continuity from the system.
- Conservative strategy: Other providers are relatively conservative on cache discounts, typically offering 50% off. These services often set a minimum threshold — for example, the cacheable prefix in a request must reach at least 1024 tokens to qualify for the discount. This means that for short-text interaction scenarios, the caching mechanism is essentially ineffective.
When choosing an LLM service, developers must evaluate the actual costs of different billing models based on their own request frequency, prompt length, and session retention time.
3. Prompt Design Best Practices: Maximizing the Cache Hit Rate
Once you understand the billing rules, the practical goal becomes clear: how to maximize the cache hit rate. LLM caching strictly follows the prefix matching principle — matching starts from the very first token of the request, and only the continuously identical portion counts as a hit. As soon as even a single character differs in the middle, all cache after that position is invalidated.
Therefore, the highest principle of prompt design is just one rule: place static, stable content at the very front, and dynamic, changing content at the very end.
3.1 Absolute Stability of the System Prompt
The system prompt defines the model’s role, task background, and global rules, making it the best content to cache. It must be placed at the top of the request and kept absolutely identical across multiple calls.
3.2 Front-Load Few-shot Examples
When using few-shot prompting, place the fixed examples after the system prompt and before the user’s actual input.
3.3 Strictly Postpone Dynamic Parameters
Dynamic content — such as timestamps that need to be concatenated, user inputs, and document snippets retrieved via RAG — must be placed at the very end of the prompt.
Below is a comparison of prompt structures before and after optimization:
[Before optimization: cache easily invalidated]
{"messages": [{"role": "system", "content": "You are a professional coding assistant."},{"role": "user", "content": "Current time: 2023-10-24. Please explain this code:"},{"role": "user", "content": "def hello(): print('world')"},{"role": "user", "content": "Also, please follow these rules: 1. Answers must be concise... (with many rules)"}]}
Because the timestamp and user input are interleaved near the front, the subsequent rules section cannot be cached.
[After optimization: maximized cache hits]
{"messages": [{"role": "system", "content": "You are a professional coding assistant. Please follow these rules: 1. Answers must be concise... (with many fixed rules)"},{"role": "user", "content": "Please explain this code: def hello(): print('world'). Current time: 2023-10-24."}]}
By consolidating all static rules into the system prompt and concentrating dynamic input at the end, the rules portion can be stably cached, significantly reducing the number of billed tokens.
4. Advanced Optimization and Engineering Practices
In real production environments, adjusting the prompt structure alone is not enough — the engineering architecture must support it as well. For example, if your business runs on a cloud platform, you can leverage API gateway and monitoring/alerting services (such as those provided by Baidu AI Cloud) to build a complete cache hit rate monitoring dashboard.
By recording the latency and token consumption details of each API request at the gateway layer, developers can directly observe the cache hit behavior of different endpoints. When a high-frequency endpoint’s cost falls short of expectations, you should immediately check whether dynamic variables were placed at the front of the prompt, or whether uneven load balancing across multiple instances prevented cache hits from concentrating. In addition, for models with a 5-minute cache TTL, consider introducing a “heartbeat keep-alive” mechanism at the business layer — periodically sending minimal valid requests during idle periods to keep the cache alive.
Conclusion
The cache hit mechanism of LLM APIs appears to be a billing discount from the provider, but at its core it is the commercialization of underlying compute optimization. For developers and enterprises, deeply understanding the KV Cache principle, enforcing the “static first, dynamic last” prompt-writing convention in architectural design, and complementing it with a solid monitoring system are the key paths to cost reduction and efficiency gains in an era of expensive AI compute.
