How Context Caching Reduces the Cost of Repeated Tokens
Context caching reduces the cost of repeatedly sending the same long documents to large language models. This article explains how caching works, compares automatic and explicitly declared caching, shows how to estimate potential savings, and outlines implementation, monitoring, security, and infrastructure considerations.
Why the Same Document Is Billed Repeatedly
In production applications, users often ask several questions about the same long document. For example, they may first ask whether a company’s profit increased year over year, then ask about cash flow, and finally follow up with a third question.
Although these appear to be three separate requests, the entire document may be submitted to the model each time. If the document contains 300,000 tokens, three requests result in 900,000 input tokens being billed—even though the document itself never changes.
Large language model APIs are stateless by default. For every request, the service must process the system prompt, conversation history, and reference documents again before generating an answer to the new question. Input-token charges are based on this processing workload. As the amount of repeated content increases, so does the amount paid for redundant processing.
The Basic Idea Behind Context Caching
Context caching identifies a repeated prefix in a request and stores the result of processing it. When a later request contains the same prefix, the service can reuse the cached result instead of processing the entire prefix again. Providers typically charge a lower rate for cached input, reducing the total cost.
Caching generally applies only to the repeated prefix. The question itself still needs to be processed for every request. The savings therefore depend on how much of the total input is made up of repeated content.
Two Common Caching Models
Most large language model services use one of two broad caching models. The key difference is whether the developer must explicitly declare the content to be cached and how long the cached content is retained.
Automatic Caching
The service automatically detects a shared request prefix. When it finds an overlap with a previous request, it attempts to serve that portion from the cache. Developers do not need to modify their request code.
This model has a low integration cost and works well for standardized request patterns. However, it also has several limitations:
- Cache retention is often short, so the cache may need to be rebuilt after expiration.
- Cache matching can be strict. The prefix may need to be exactly identical, meaning that an extra space or a timestamp in the system prompt can invalidate the cache.
- The discount varies by provider and model, so the applicable pricing documentation must be checked.
Automatic caching is well suited to scenarios such as customer-service bots, where the same user asks several questions within a short period and the context structure remains stable.
Explicitly Declared Caching
With this model, the developer marks the content blocks that should be cached using a dedicated field in the message body. This tells the service that the content is intended for reuse rather than only for the current request.
For example, Anthropic’s Messages API supports adding a cache_control field to a content block. The exact format should be verified in the official prompt caching documentation.
An illustrative structure is:
{"role": "user","content": [{"type": "text","text": "This is the long document to cache...","cache_control": { "type": "ephemeral" }}]}
These APIs typically return two important metrics: the number of tokens used to create the cache and the number of tokens served from the cache. Developers can use these values to monitor caching effectiveness.
The trade-off is that the initial cache creation cost is often higher than the cost of standard input. Retention time also varies by provider and cache type, so the relevant documentation should be consulted.
Hybrid and Layered Strategies
Some teams divide the context into two parts:
- Long-lived, stable content, such as system prompts and fixed knowledge bases
- Dynamic content, such as recent conversation history
Each part can use a different caching strategy and expiration period. This approach better reflects the lifecycle of the content, but it requires more application-level design.
Comparing the Three Strategies
| Dimension | Automatic caching | Explicit caching | Hybrid and layered caching |
|---|---|---|---|
| Developer effort | Almost none | Add cache markers to requests | Design and separate content layers |
| Cache condition | Automatic matching of a shared prefix | Explicit reuse of marked content blocks | Depends on the strategy for each layer |
| Write cost | Determined by the provider’s rules | Initial creation may cost more than standard input | Depends on the selected model |
| Retention period | Usually short and provider-defined | Varies by provider and cache type | Can be configured by layer |
| Suitable use cases | Stable, standardized requests | Multiple follow-up questions in one session | Long-lived knowledge bases combined with dynamic conversations |
How to Choose a Caching Strategy
The main factors are how often the context is reused and how much time passes between interactions.
- Frequent, short-term interactions: For example, multiple questions in a single session. Explicit caching may be more suitable because the same context is reused repeatedly within a short period.
- Multiple users accessing the same knowledge base: Automatic caching may be more suitable because it requires no additional declaration and can naturally cover common content across requests from different users.
- Infrequent access with a long lifecycle: Model-level caching may not cover the full interval between requests. In this case, cache results at the application layer or preprocess the knowledge base to reduce repeated model calls.
Calculate the Economics Before Enabling Caching
Caching does not always reduce costs. For content that is accessed infrequently, the cost of creating the cache may exceed the savings from later reads. Before deployment, estimate the expected result with the following formula:
Net savings = H × L × (P − R) − C × L × (W − P)
Where:
His the number of cache hits.Lis the number of tokens in the repeated prefix.Pis the standard input price.Ris the cached-read price.Cis the number of cache writes.Wis the cache-write price.
All prices should be taken from the provider’s current pricing documentation.
If net savings are negative, the content is not being reused often enough. Consider shortening the cache retention period or using a different approach.
Key Implementation Details
Keep the Prefix Byte-for-Byte Identical
Most caching systems require cached content to be exactly identical, including spaces, line breaks, and field order. When constructing requests, place stable content first and dynamic content last.
For example, keep the system prompt and reference document fixed, and place the user’s question and timestamp in the final user message.
Monitor Actionable Metrics
Record metrics at the request, tenant, and document levels. Recommended metrics include:
- Cache hit rate = cached-read tokens ÷ (cached-read tokens + standard input tokens)
- The number of tokens used to create caches and the associated write cost
- The net savings for each document, based on the formula above
Total spending alone cannot show whether caching is working. Hit rate and net savings should be monitored separately.
Consider Data Security and Consistency
Cached content may contain customer information or internal documents. It must be isolated by tenant and assigned an expiration policy that matches the business requirements.
When a document is updated, the old cache should be invalidated. Otherwise, the model may generate answers based on outdated content.
Building a Reuse System with Infrastructure
Model-level caching addresses repeated requests, but it does not cover every source of cost. A common architecture is:
- Store the original document in object storage and record its version.
- Use a message queue to process document splitting, embedding generation, summarization, or other preprocessing asynchronously, then persist the results.
- When a request arrives, generate a stable prefix from the document version and pass it to the model-level cache.
- When the document version changes, send an invalidation message to remove the old prefix and preprocessing results.
This design ensures that repeated preprocessing is performed only once and gives cache invalidation a clear trigger. Object storage and message queues should also have appropriate access controls and retention periods to prevent sensitive data from being stored indefinitely.
Conclusion
Context caching applies the broader engineering principle of trading storage for computation to large language model applications. It can reduce the cost of repeated prefixes, but the actual savings depend on reuse frequency, prefix length, and the provider’s pricing rules.
Calculate the economics before enabling caching, choose a strategy based on the application’s access pattern, and verify prices and parameters against each provider’s official documentation.
