Prompt Caching for LLM APIs: A Practical Guide to Cutting Input Token Costs by Up to 90%
This article explains how context caching can reduce LLM API input costs by up to 90% for workloads that repeatedly reuse long prefixes. It covers the three-part pricing model, the factors that break cache hits, a static-prefix/dynamic-tail implementation pattern, a cost example, workload fit, and observability practices for continuous optimization.
Prompt Caching for LLM APIs: A Practical Guide to Cutting Input Token Costs by Up to 90%
1. Why Your LLM Bill Stays High
When teams move large language models into production, many encounter a similar cost curve. In the early stage, call volume is low and spend is manageable. Once traffic grows, especially in scenarios involving long system prompts, multi-turn conversations, document Q&A, or coding assistants, token consumption can climb sharply. The largest part of the bill is often not the short user question visible in the interface, but the large context repeatedly sent with every request: system instructions, knowledge base snippets, conversation history, format constraints, and few-shot examples.
Under the billing model used by mainstream LLM APIs, input tokens are charged per request. Whether or not the context is identical to the previous request, as long as it appears in the current request body, it is fully counted as input tokens. A 2,000-token system prompt called 100,000 times per day therefore creates 200 million repeated input tokens. In most cases, that prefix content is fixed.
Context caching, also called prompt caching, is designed to address this structural waste. The core idea is simple: cache the repeated prefix portion of requests on the server side. When later requests hit the cache, those tokens are billed at a significant discount. Instead of paying full price every time, you pay full price for the first write and a reduced price for subsequent hits.
2. Breaking Down Cache Pricing: Hit Price, Write Fee, and Lifetime
To use caching effectively, you need to understand its three-part cost structure. In a relatively transparent industry implementation, a cached request returns two key usage fields in the response:
- Cache creation input tokens (
cache_creation_input_tokens): the number of tokens written to the cache in this request. This part usually costs more than ordinary input tokens. A common industry practice is an uplift of about 25%, which can be understood as a write cost. - Cache read input tokens (
cache_read_input_tokens): the number of tokens read directly from the cache in this request. This part receives a deep discount. A more aggressive industry practice bills it at 10% of the original price, which means a 90% saving.
The value of these two fields is observability. Without them, you only see total tokens and total cost, and you cannot tell whether caching is working, what the hit rate is, or where the money is going. With them, cost optimization becomes a measurable and iterative engineering problem rather than a matter of guesswork.
Caching is not free of trade-offs. Two constraints must be faced directly:
Constraint 1: Cache lifetime is limited. A common implementation keeps the cache for only about 5 minutes, counted from the last hit or creation, with specific rules varying by implementation. Beyond that window, the cache expires, and the next request must write again and pay the write fee. This means caching naturally fits traffic patterns with frequent reuse of the same context within a short period. It is nearly useless for sparse calls that arrive once every half hour.
Constraint 2: The first write has an extra cost. Creating the cache for the first time costs about 25% more in write fees. If a context is used only once or twice, caching can actually lose money: you pay the extra write fee but do not receive enough hit discounts to amortize it.
This leads to a simple break-even intuition: the more times the same prefix context is reused within the cache lifetime, the greater the savings; the fewer the reuses, the more likely the cost outweighs the benefit.
3. Hit Rate Determines Everything: Key Factors That Affect Cache Effectiveness
Whether a cache hit occurs depends on whether the request prefix is token-for-token identical to what the server has already cached. Any subtle difference causes a cache miss, and the entire prefix is billed again at full price. Common “cache killers” in practice include:
- Dynamic content mixed into the prefix. For example, placing a timestamp, user ID, random number, or request sequence at the beginning of the system prompt. Once the prefix changes, none of the following content can hit the cache. The correct approach is to put all static content first and dynamic content last.
- Unstable message order or format. The same semantics can become a different token sequence if JSON field order, whitespace, or line breaks differ. Normalize prompt templates and avoid subtle differences introduced by runtime string concatenation.
- Unbounded growth of multi-turn conversation history. In conversational scenarios, history messages are part of the prefix and change every turn. Without trimming or summarization, it is difficult to consistently hit the same prefix within the cache window.
- Concurrent scheduling disperses reuse. If requests for the same context are spread across multiple time periods and service instances, and the interval exceeds the cache lifetime, the hit rate drops significantly.
A practical engineering pattern for these problems is a layered design with a static prefix plus dynamic tail:
# Anti-pattern: dynamic content mixed into the prefix makes cache hits nearly impossibleprompt = f"Current time {now}, user {user_id} asks: {question}\n" + LONG_SYSTEM_PROMPT# Good pattern: long static prefix first, dynamic content concentrated at the endmessages = [{"role": "system", "content": LONG_STATIC_SYSTEM_PROMPT}, # stable, cacheable{"role": "system", "content": FEW_SHOT_EXAMPLES}, # stable, cacheable{"role": "user", "content": f"[{now}] [{user_id}] {question}"} # dynamic part, placed last]
With this structure, system prompts and few-shot examples form a stable cacheable prefix, while the changing user input accounts for only a small proportion. The cache hit rate can then remain consistently high.
4. Cost Calculation: Putting “90% Savings” into Numbers
An abstract discount ratio is less convincing than a calculation table. Assume a business uses a fixed 3,000-token system prompt, receives 10,000 requests per day, and the requests are concentrated during working hours with intervals far shorter than the cache lifetime. As a result, all requests except the first of each day hit the cache. Let the input token unit price be P, used only as a symbolic placeholder; actual pricing depends on the provider:
| Item | Without cache | With cache enabled |
|---|---|---|
| Daily input token volume | 3,000 × 10,000 = 30,000,000 | Same as left |
| Full-price billing portion | 30,000,000 | First write 3,000 × 1.25 + remaining hits 3,000 × 9,999 × 0.1 |
| Relative cost | 100% | About 10.0% + 0.0125% ≈ 10% |
As shown, under the ideal condition of frequent reuse of the same prefix, input-side cost can be compressed to about one tenth of the original. Even if not all requests hit the cache, for example with an 80% hit rate, total cost can still fall by more than 70%. This explains why caching is often called the single most cost-effective measure in LLM cost optimization.
The premise of the calculation above is sufficient reuse density. If the business makes only a few dozen low-frequency calls per day, the benefit of caching may be offset by write fees and rewrites after expiration. In that case, other measures such as shortening prompts, trimming context, and retrieval-based pruning should be considered first.
5. Scenario Fit: Which Workloads Benefit Most from Caching
Combining the three-part cost structure and the 5-minute cache lifetime gives a clear framework for judging scenario fit:
High-fit scenarios:
- Customer service or Q&A bots with long system prompts and frequent short requests;
- Code completion and code review tools where the same project conventions and context are reused repeatedly;
- Batch document processing where the same long document is queried multiple times, such as contract review or report analysis;
- Agent applications with fixed tool definitions and task instructions, and frequent looped calls.
Low-fit scenarios:
- Call intervals generally exceed the cache lifetime, such as scheduled jobs and low-frequency background tasks;
- Each request has a completely different context, such as asking one question each about a large number of different documents;
- Prompts are extremely short, so the absolute amount saved by caching is limited and the optimization benefit is not obvious.
For workloads in the middle ground, request clustering can artificially increase reuse density: schedule requests that use the same context into the same time window as much as possible instead of spreading them evenly throughout the day. For batch tasks, this often requires only adjusting the queue consumption strategy.
6. Observability and Continuous Optimization: Closing the Loop
The final step in cache optimization is to build a measurement system. On the application side, record the two cache usage fields returned by each request and calculate two core metrics:
- Cache hit rate = cache read tokens / (cache read tokens + cache creation tokens);
- Average input cost per request, observed as a daily or weekly trend.
When the hit rate drops unexpectedly, it usually means the prefix content has been changed accidentally, such as a template change, a dynamic field being inserted, or a format adjustment. This can be located quickly. Integrating these two metrics into monitoring and alerting turns cost optimization from a one-time tuning exercise into an ongoing engineering capability.
In addition, caching should be combined with other cost measures: shorten prompts to reduce the baseline, use retrieval augmentation to inject only relevant snippets, apply rolling summaries to conversation history, and set reasonable maximum output lengths. Caching addresses the problem that “repeated parts should not be billed at full price,” while prompt engineering addresses the problem that “there should not be so many tokens in the first place.” Only by combining both can overall cost be optimized.
7. Conclusion
Context caching is not magic. It is a billing mechanism with a clear cost structure and clear applicability boundaries. By understanding three basic facts, namely that hits are billed at a deep discount, writes carry an extra fee, and the cache window is short, developers can design stable static prefixes, clustered scheduling strategies, and observable metrics. In this way, they can reduce LLM input costs by an order of magnitude without sacrificing functionality. At a time when inference cost remains a major expense for production AI applications, this is a basic exercise that almost every technical team should do carefully.
