Prompt Caching Pricing Explained: Cache Writes, Hits and Expiry
Prompt caching bills in three parts. The first time a prefix is written to the cache, you pay a write price (which some providers set higher than the normal input price). Within the validity window, the part that hits the cache is billed at a read price, clearly below normal input. Anything that misses is billed at the regular input price. So it is not "turn it on and save money": if the prefix is short, the content changes often, or the gap between two requests exceeds the validity period, you keep paying for writes and rarely get the read discount.
This article does not target one provider. It covers the mechanics they share, derives a break-even formula, and ends with steps for diagnosing your hit rate. Multipliers, validity periods and minimum lengths differ by provider and change over time, so for any specific number, check the provider's official pricing page and docs.
What does prompt caching actually cache?
It caches the model's intermediate computation for the input prefix, not the answer. If the next request is identical, token for token, from the first token up to some position, that segment does not need to be recomputed. It is billed at the read price, and the first token also arrives faster.
First, separate it from another kind of "cache". Some gateways or applications do response caching: for the same question they return the previous answer without calling the model at all. The differences:
| Model prefix cache (this article) | Application-level response cache | |
|---|---|---|
| What is cached | Computed state of the input prefix | The complete answer |
| Model called? | Yes, only the prefix part is cheaper | No |
| Output regenerated each time? | Yes | No, the old answer is returned |
| Who bills it | The model provider, visible in usage | You or the gateway; not on the provider's bill |
| Best for | Long system prompts, multi-turn chat, agents | Exactly repeated questions |
Many articles online mix the two. When you read "cache hit rate 90%", first check which one it refers to. This article covers only the former.
What is the difference between implicit and explicit caching?
Implementations fall into two broad groups:
- Implicit (automatic) caching: no code changes. The platform detects repeated prefixes on its own. There is usually no extra write fee; hits are discounted and misses cost the normal price. All you control is how the prompt is laid out.
- Explicit caching: you mark cache breakpoints in the request, or first create a separate cache object and then reference it. Writes usually carry a premium, and some providers also charge storage by how long the cache lives. The upside is that hits are more controllable, and the selectable validity period may be longer.
One provider may offer both, and support can differ between models. The quickest way to tell which one you are using is to check whether the docs have a "write price" column and whether the request needs extra parameters. For Claude's explicit markers, see the step-by-step guide in How to use Claude API prompt caching to save money.
The five variables in the bill
Whichever provider's caching pricing page you read, you can reduce it to these five items:
| Variable | Meaning | Where to look |
|---|---|---|
| Write multiplier w | Cache write price ÷ normal input price; for implicit caching usually w = 1 | Official pricing page |
| Read multiplier r | Price of the hit portion ÷ normal input price, r < 1 | Official pricing page |
| Validity period (TTL) | How long after writing, without use, the entry expires; on some providers a hit refreshes the timer | Official docs |
| Minimum length | Prefixes shorter than this are not cached | Official docs, often per model |
| Storage fee | Some explicit caches charge by "tokens × duration" | Official pricing page |
Once you have filled in all five, the calculations below apply. Pricing pages change. You can use cdnping's site changes to follow row-level changes on major providers' pricing pages (with RSS), or see price changes recorded from the OpenRouter catalog in model monitoring. For tracking methods, see How to find out right away when an LLM API price changes.
How many hits before you start saving?
Let the prefix length be L tokens and the normal input price be P. Looking only at the cost of the prefix:
- Without caching, N calls:
N × P × L - With explicit caching, written on the first call and hit on the other N−1 calls:
w × P × L + (N−1) × r × P × L
Requiring the latter to be smaller than the former and simplifying gives:
N > (w − r) / (1 − r)
This is the minimum number of calls within the validity period. The table below plugs in hypothetical multipliers, only to illustrate the formula; they are not any provider's actual prices:
| Assumed w | Assumed r | (w − r)/(1 − r) | Conclusion |
|---|---|---|---|
| 1.0 | 0.5 | 1.0 | Saves money from the second request on (implicit caching has no write premium, so it cannot lose) |
| 1.25 | 0.1 | 1.28 | One write plus one hit breaks even |
| 2.0 | 0.1 | 2.11 | Needs at least two hits |
In practice not every request hits, so it is more useful to work with the hit rate. Let h be the fraction of the prefix that hits. The average cost on the prefix per request is P × L × [h × r + (1 − h) × w]. Compared with P × L without caching, the break-even point is:
h > (w − 1) / (w − r)
Using the same hypothetical multipliers: with w = 1.25 and r = 0.1, the hit rate must be above about 22% to pay off; with w = 2.0 and r = 0.1, it must be above about 53%. The higher the write premium, the higher the hit rate you need.
If there is also a storage fee, add storage price × L × cache retention time. This term does not depend on the number of calls, and with sparse traffic it is the easiest thing to eat up the savings.
When does enabling caching actually cost more?
Working backward from the formulas, these are the common cases:
- The gap between requests exceeds the TTL. For example, a scheduled job runs once an hour while the validity period is only a few minutes. Every call is a write and never a hit, so you pay an extra (w − 1) × P × L each time.
- Content that changes every time leaks into the prefix. If the start of the system prompt includes the current time, a request ID, or a randomized example order, the hit breaks at the changing point and everything after it is rewritten.
- The breakpoint is placed too late. If the part before the breakpoint includes the user's question for this turn, the next request naturally cannot match.
- The prefix is below the minimum length. You marked it explicitly but it did not take effect. The bill shows no reads, and possibly no writes either, which is easy to mistake for "the cache is broken".
- Concurrent requests write at the same time. Several requests sent before the cache exists are each billed as writes or at full price. Send one request first to warm the cache, then open up concurrency, to cut this waste.
- Tool definitions or model parameters change often. In many implementations the tool definitions sit at the very front of the prefix, so changing one tool description invalidates the whole cache.
Is caching worth doing? Check how much of the bill is input
Caching reduces only input cost; output is billed at full price. So first confirm how much of your bill is input.
As a reference, take the public OpenRouter model catalog that cdnping fetched on 2026-10-17 (prices per million tokens). Among the 16 major model entries it tracks, input prices range from 0.1 to 4 USD, and for all but one entry the output price is 3 to 5 times the input price. Suppose an agent call carries 50,000 tokens of context and outputs only 1,000 tokens, at 2 USD per million input tokens and 10 USD per million output tokens: input is about 0.1 USD and output about 0.01 USD, so input is over 90% of the cost. Long context with short output is where caching is most valuable.
Conversely, if your requests are short prompts with long output (long-form writing, generating lots of code), input is a small share and even a perfect cache saves little. Look first at approaches that split work by task, such as multi-model routing. For other pitfalls in comparing unit prices, see How to compare LLM API prices.
How should you lay out the prompt to get hits?
The principle: the more stable the content, the further forward it goes; the more often it changes, the further back. The recommended order:
- Tool definitions (keep order and wording as fixed as possible)
- System prompt (no time, user name, request ID or other dynamic fields)
- Long reference material: documents, codebase context, few-shot examples
- Conversation history (multi-turn chat is naturally append-only, so earlier turns can hit)
- This turn's user input and dynamic information (time, retrieval results, etc.)
A few details that are easy to miss:
- Keep field order fixed when serializing JSON. In some languages dictionaries do not guarantee order, so the same content may serialize to different strings.
- Put retrieval-augmented generation (RAG) results after the fixed material and before the user's question; do not insert them into the middle of the system prompt.
- When you truncate or summarize conversation history, the truncation point changes the prefix, so the first request after truncation is necessarily a write. Truncate in chunks rather than sliding the window every turn.
How do you check the hit rate from the usage field?
The bill is the final authority, but to locate a problem you need the usage in each response. Field names differ by provider. Below are the common ones; they may change between versions, so follow the official docs for the API you use:
| API style | Hit tokens | Written tokens | Uncached input |
|---|---|---|---|
| Anthropic Messages | cache_read_input_tokens | cache_creation_input_tokens | input_tokens |
| OpenAI Chat / Responses | prompt_tokens_details.cached_tokens (Responses: input_tokens_details.cached_tokens) | No separate field | Total input minus hits |
| DeepSeek | prompt_cache_hit_tokens | No separate field | prompt_cache_miss_tokens |
| Gemini | usageMetadata.cachedContentTokenCount | No separate field (explicit caching is metered when the cache object is created) | Total input minus hits |
Note that in the Anthropic style, input_tokens does not include the cache read and write portions, so total input is the sum of three items; in the OpenAI style, cached_tokens is included in total input. Mixing the two conventions will make your hit rate come out very differently. For a fuller breakdown of token accounting, see How token billing works.
A script you can use as is
Append each response's usage as-is to a JSONL file (one usage object per line), then run:
# cache_stats.py: prompt cache hit-rate statistics. Usage: python3 cache_stats.py usage.jsonl
import json, sys
hit = write = miss = n = 0
for line in open(sys.argv[1], encoding="utf-8"):
u = json.loads(line)
n += 1
if "cache_read_input_tokens" in u or "cache_creation_input_tokens" in u: # Anthropic style
r = u.get("cache_read_input_tokens") or 0
w = u.get("cache_creation_input_tokens") or 0
hit, write, miss = hit + r, write + w, miss + (u.get("input_tokens") or 0)
elif "prompt_cache_hit_tokens" in u: # DeepSeek style
hit += u["prompt_cache_hit_tokens"]
miss += u.get("prompt_cache_miss_tokens") or 0
else: # OpenAI style
total = u.get("prompt_tokens") or u.get("input_tokens") or 0
d = u.get("prompt_tokens_details") or u.get("input_tokens_details") or {}
c = d.get("cached_tokens") or 0
hit, miss = hit + c, miss + total - c
total = hit + write + miss
print(f"请求数 {n},输入共 {total} token")
if total:
print(f"命中 {hit/total:.1%},写入 {write/total:.1%},未命中 {miss/total:.1%}")
Once you have the hit rate, plug it into h > (w − 1)/(w − r) from the previous section to see whether you are currently ahead or behind.
Order of checks when the hit rate is low
- Send the exact same request twice in a row. Is the hit field greater than 0 on the second one? If not, check the minimum length and whether explicit marking is required.
- Save the full request bodies of the two requests and diff them. The first point of difference is where the prefix breaks.
- Check the relationship between request interval and TTL by looking at the distribution of time gaps between consecutive requests.
- Confirm that all requests go to the same model with the same parameters; switching models or changing some parameters makes the cache unusable.
- When calling through a gateway or relay, confirm whether it passes the cache fields through unchanged and whether writes and reads are billed on the upstream's terms. If the bill and usage do not match, follow the steps in When your AI API bill doesn't match.
Pre-launch costing steps
Fill the official pricing page's w, r, TTL, minimum length and storage fee into a table, compute the hit rate from a week of usage logs, and plug it into the formulas. Caching is worth serious effort only when the hit rate is above the break-even point and input makes up most of the bill. Otherwise, adjust the prompt layout first, or skip explicit caching and take only the discount from implicit caching. Recompute whenever a pricing page changes.