Sub topic 12
Prompt caching
This chapter assumes you have read the earlier chapters on per-token pricing, usage data, and conversation history growth. You should also be comfortable reading short Python functions. Prompt caching is the main way to reduce the cost of resending the same tokens on every call.
What prompt caching does
An LLM call bills every input token at the input price. When many calls start with the same text, you pay full price for that repeated text each time. Examples are a long system prompt, a tool definition list, a reference document, or the history of a chat.
Prompt caching lets the provider keep the processed form of a prompt prefix for a short time. A later request that begins with the identical prefix is billed for that part at a discounted rate. Only the new tail of the request is billed at the normal rate.
Three points apply to every provider:
- Caching changes the price of input tokens. It does not change how many tokens there are.
- Cached tokens still occupy the context window. A 50,000-token cached prefix leaves 50,000 fewer tokens for everything else in a 100,000-token window.
- Output tokens are billed as usual. Caching never discounts them.
How the prefix match works
The cache matches on an exact prefix. The provider compares the start of your new request with prefixes it has stored. The cache is reused only up to the first token that differs. Everything after that point is processed and billed normally.
The match is on tokens, not on meaning. A prefix that differs by one space, one reordered JSON key, or one changed date produces different tokens, so it does not match.
Prices and the break-even point
Providers price caching in one of two ways. Some charge a write premium, a higher price the first time a prefix is stored, and then a steep discount on reads. Others cache automatically with no write premium and only discount reads. Check your provider's pricing page for the real multipliers, because they differ and change.
The examples below use made-up multipliers:
| Kind of input token | Price relative to normal input | Price at $3 per million |
|---|---|---|
| Normal, uncached | 1.0x | $3.00 |
| Cache write (first time stored) | 1.25x | $3.75 |
| Cache read (prefix hit) | 0.1x | $0.30 |
Take a prefix of P tokens that you send twice. Without caching, the cost is 2P at the normal price. With caching, it is 1.25P for the write plus 0.1P for the read, which is 1.35P. Caching already wins on the second call. If a provider charged a larger write premium, you would need more reads to recover it. The general rule is that caching pays off when the number of reuses within the cache lifetime is high enough that the read savings exceed the write premium.
Where the cache fits in a conversation
The history growth chapter showed that a chat resends its whole history on every turn. That makes it the best case for caching. Each request starts with the entire previous request, so most of every request is a prefix hit.
The function below extends the earlier simulation. It splits each turn's input into cache-read tokens (the previous request's tokens) and fresh tokens (the previous reply plus the new user message). The prices and multipliers are placeholders.
def conversation_input_cost(system_tokens, user_tokens, reply_tokens, turns,
price_per_million, read_mult, write_mult):
read_total = 0
fresh_total = 0
history = system_tokens
previous_input = 0
for _ in range(turns):
history += user_tokens
read_total += previous_input # prefix seen on the last call
fresh_total += history - previous_input # reply + new user message
previous_input = history
history += reply_tokens
cost = (
read_total * price_per_million * read_mult
+ fresh_total * price_per_million * write_mult
) / 1_000_000
return read_total, fresh_total, cost
read, fresh, cost = conversation_input_cost(500, 100, 300, 10, 3.0, 0.1, 1.25)
uncached = (read + fresh) * 3.0 / 1_000_000
print(read, fresh) # 19800 4200
print(f"${uncached:.4f}") # $0.0720
print(f"${cost:.4f}") # $0.0217The 24,000 input tokens split into 19,800 read from cache and 4,200 processed fresh. The input cost falls from $0.0720 to $0.0217, about 70 percent less. The output tokens are not in this calculation, because caching does not change them.
Two details in the model are worth noting:
- The first call of a conversation can never be a read. There is nothing stored yet.
- The model's reply is not in the cache when it is produced. It joins the cached prefix only once the next request contains it, which is why the reply is counted as fresh on the following turn.
Reading cache results from usage data
You should not assume the cache worked. The API response reports it in the usage data. The field names differ by provider, so treat the names below as illustrative and look up the real ones in your provider's documentation.
def cache_hit_rate(usage):
read = usage.get("cache_read_tokens", 0)
written = usage.get("cache_write_tokens", 0)
fresh = usage.get("input_tokens", 0) # check whether your API counts cached tokens here
total = read + written + fresh
return read / total if total else 0.0
usage = {"input_tokens": 400, "cache_read_tokens": 1600, "cache_write_tokens": 0}
print(f"{cache_hit_rate(usage):.0%}") # 80%Check how your provider defines the total. Some report cached tokens separately from the normal input count, and others include them in it. If you add them together when they overlap, your cost estimate will be wrong. Log the hit rate for each call. A hit rate of zero across a series of similar calls means something is breaking the prefix match.
Common reasons the cache misses
Most cache failures come from the prefix changing when you did not mean it to. Look for these:
- Variable text early in the prompt. A timestamp, request ID, or user name near the top changes every call, so nothing after it can match. Put stable content first and variable content last.
- Reordered or regenerated content. Tool definitions built from a dictionary or set may come out in a different order. Serialized JSON with unsorted keys can differ between runs. Keep the order fixed.
- A prefix below the minimum length. Providers set a minimum size for cacheable prefixes, often in the range of a thousand tokens. Shorter prompts are processed normally even if you ask for caching.
- Waiting too long. Cached prefixes expire. The lifetime is usually minutes, and on some providers each hit extends it. A chat with long pauses between turns can lose its cache and pay the write cost again.
- Changing the model or settings. The cache belongs to a specific model. Switching models, or changing settings that affect the processed prompt, starts a new cache.
- Editing earlier history. Changing, removing, or summarizing a message in the middle of the conversation invalidates every cached token after that point.
Caching versus trimming history
The context management chapter described trimming old messages to stay in budget. Trimming and caching pull against each other. If you drop the oldest message on every turn, the start of each request changes, and the stored prefix no longer matches.
There are two common ways to handle this:
- Trim in large steps. Let the history grow with the cache working until it nears the budget. Then cut or summarize a large chunk at once. The next call pays a write cost, and the following calls hit the new prefix.
- Keep a fixed head. Keep the system prompt and any reference material at the front unchanged, and trim only from the part after them. The fixed head stays cached even when the trimmed region changes.
Choose by comparing totals. Trimming every turn keeps each request small but pays full price on all of it. Trimming rarely keeps the cache hot, but each request carries more tokens, and those are billed at the cheaper read rate.
Practical checklist
- Put the system prompt, tool definitions, and reference documents first, in a fixed order.
- Put anything that changes per request (user input, timestamps, retrieved snippets) at the end.
- Log the cache read and write tokens from every response.
- Estimate with your provider's real multipliers before assuming savings. A large prefix that is used only once costs more with a write premium than without caching.
- Send related calls close together in time, so they fall inside the cache lifetime.
Caching also usually reduces latency for long prompts, because the provider skips reprocessing the cached part. Treat that as a likely benefit and measure it. It is not a guarantee.
Exercise
A 10,000-token reference document is the prefix of 5 requests sent within the cache lifetime. Use the placeholder prices from this chapter: $3 per million normal input tokens, a 1.25x write price, and a 0.1x read price. The first request writes the prefix and the other four read it. What is the input cost of the prefix with caching, and without caching? Ignore the tokens that follow the prefix.
Show answer
Without caching, 5 x 10,000 = 50,000 tokens at $3 per million = $0.15. With caching, the write costs 10,000 x $3.75 / 1,000,000 = $0.0375. The four reads cost 4 x 10,000 x $0.30 / 1,000,000 = $0.012. The total is $0.0495, about 67 percent less than $0.15.
Exercise
A chat application puts "Current time: <timestamp>" as the first line of its system prompt, and usage data shows zero cache-read tokens on every call. Explain why, and give one fix.
Show answer
The timestamp changes on every request, so the first tokens of the prompt differ each time. The cache matches only an exact prefix, so no stored prefix can match, even though the rest of the prompt is identical. Move the timestamp to the end of the prompt, after the stable content (or into the latest user message), so that the long stable part stays at the front.