Sub topic 6
Prompt caching and keeping prefixes stable
This chapter assumes you have read the earlier chapters on token pricing and agent loop cost. You should be comfortable reading short Python functions and JSON usage records. Prices in the examples are placeholders. Take real rates and cache rules from your provider's documentation.
What prompt caching does
An agent loop resends its whole context on every turn: system prompt, tool definitions, earlier messages, and tool results. Most of that text is identical to the previous request. Prompt caching lets the provider reuse its stored work on that repeated text, so you pay a reduced rate for it.
Three properties matter in practice:
- The cache matches a prefix. The provider compares the start of your new request with a stored earlier request. Reuse stops at the first difference. Everything after that point is billed at the normal rate, even if it is identical to something cached.
- Cached reads are cheaper. Cached input tokens are billed at a fraction of the normal input rate. Some providers charge a small premium to write a prefix into the cache. Others write automatically at no extra charge.
- Entries expire. A cached prefix stays alive for a limited time, often minutes, and the timer usually resets each time the prefix is read. A long pause by the user or a slow tool can let it lapse.
Caching does not change the output. It changes how much of your input is billed at the full rate.
The arithmetic for one turn
The function below computes input cost for one turn when part of the context is read from cache. cache_read_multiplier is the fraction of the normal rate charged for cached tokens.
def input_cost_with_cache(context_tokens, cached_prefix_tokens, price_input, cache_read_multiplier):
"""Input cost in USD for one turn when a prefix is read from cache.
cache_read_multiplier is the fraction of the normal input rate charged for
cached tokens. It varies by provider, so take it from the provider's docs.
"""
uncached = context_tokens - cached_prefix_tokens
effective_tokens = uncached + cached_prefix_tokens * cache_read_multiplier
return effective_tokens * price_input / 1_000_000
# Placeholder numbers: 40k-token context, 35k of it a stable cached prefix.
print(input_cost_with_cache(40_000, 35_000, 3.0, 0.1)) # 0.0255
print(input_cost_with_cache(40_000, 0, 3.0, 0.1)) # 0.12The 35,000 cached tokens count as 3,500 effective tokens. The turn is billed as 8,500 tokens instead of 40,000, about 79% less input cost. The saving grows with the share of the context that is stable.
The arithmetic for a whole loop
In an agent loop, each turn's context is the previous turn's context plus a new tool call and result. If the previous context is cached, only the new step is uncached. The sketch below extends the no-cache loop model from the earlier chapter. It charges the new tokens at a write multiplier, because some providers charge extra to create a cache entry.
def loop_effective_tokens(system_tokens, step_tokens, turns,
read_mult=0.1, write_mult=1.25):
"""Input tokens billed, in full-rate equivalents, across an agent loop.
Each turn reads the previous turn's context from cache and writes
only the new step. Multipliers are placeholders.
"""
total = 0.0
cached = 0
context = system_tokens
for _ in range(turns):
new = context - cached
total += cached * read_mult + new * write_mult
cached = context
context += step_tokens
return total
def loop_input_tokens(system_tokens, step_tokens, turns):
"""Total input tokens billed across an agent loop with no caching."""
total = 0
context = system_tokens
for _ in range(turns):
total += context
context += step_tokens
return total
plain = loop_input_tokens(5_000, 2_000, 20)
cached = loop_effective_tokens(5_000, 2_000, 20)
print(f"{plain:,}") # 480,000
print(f"{cached:,.0f}") # 97,450
print(f"{cached / plain:.0%}") # 20%Under these placeholder multipliers, the same 20-turn session costs about a fifth as much input. The first turn is slightly more expensive than without caching because of the write premium. The cost per turn then stays nearly flat instead of growing with the context. Caching does not remove growth. The cached portion still grows each turn, and it is billed at the lower read rate.
What keeps a prefix stable
A cache hit requires the start of the request to be byte-for-byte the same as before. In a coding agent the request is usually assembled in this order:
- System prompt and agent instructions.
- Tool definitions.
- Project rules and reference files.
- Conversation history, oldest first.
- The newest user message or tool result.
Order the content from least to most likely to change. Static content goes first, and anything that changes each turn goes last.
def shared_prefix_blocks(a, b):
"""Count the leading blocks that two requests have in common."""
n = 0
for x, y in zip(a, b):
if x != y:
break
n += 1
return n
stable = [
"You are a coding agent.",
"Tools: read_file, edit_file, run_tests",
"Repo rules: use pytest, keep functions small",
]
# Volatile value first: the prefix breaks at the very first block.
bad_1 = ["Time: 10:00:01"] + stable + ["user: fix the failing test"]
bad_2 = ["Time: 10:00:02"] + stable + ["user: fix the failing test"]
# Volatile value last: the stable blocks are shared.
good_1 = stable + ["Time: 10:00:01", "user: fix the failing test"]
good_2 = stable + ["Time: 10:00:02", "user: fix the failing test"]
print(shared_prefix_blocks(bad_1, bad_2)) # 0
print(shared_prefix_blocks(good_1, good_2)) # 3Real providers compare tokens, not blocks, but the principle is the same. Many providers also let you mark cache breakpoints explicitly. Others cache automatically once the prefix passes a minimum length. Check which model applies to your provider.
Common ways a prefix breaks
- Timestamps, random IDs or session IDs near the top. These change every request, so nothing after them can match. Move them to the end or remove them.
- Reordered tool definitions. If tools are built from an unordered collection, their order can differ between requests. Sort them or store them in a fixed list.
- Editing earlier messages. Rewriting or deleting an old message changes the prefix from that message onward. Append instead of edit.
- Truncating old tool output in place. Trimming a result from ten turns ago saves tokens in the long run but invalidates the cache from that point. Do it rarely and in batches.
- Compaction. Replacing history with a summary creates a new prefix. The next request pays the write cost on the summary. Compact when the saving outweighs that cost, not on every turn.
- Switching models. Caches are not shared across models. Routing a single step to a smaller model means that model starts with a cold cache.
- Changing tool or feature settings mid-session. Some providers include tool definitions or reasoning settings in the cache key. Changing them can invalidate the cached prefix.
Timing and minimum sizes
Two limits catch people out.
Time to live. If your agent waits longer than the cache lifetime between requests, for example while a long test suite runs or the user steps away, the next request pays the full rate and rewrites the prefix. Some providers offer a longer lifetime at a higher write price. That can be worth it for sessions with long pauses. It is rarely worth it for tight loops that call the model every few seconds.
Minimum prefix length. Providers usually cache only prefixes above a minimum size, often around a thousand tokens, and the minimum can differ by model. A short system prompt alone may never be cached. The loop-level benefit comes mainly from the accumulated history.
Parallel requests. If you fire several requests at once with the same new prefix, they may all miss because the first write has not finished. Send one request first, then fan out.
Verifying that caching works
Every provider reports cached tokens in its usage record, though field names differ. Typical fields are the number of tokens read from cache, the number written to cache, and the number of uncached input tokens. Look in your provider's response format for them.
A useful metric is the cache hit ratio per turn:
def cache_hit_ratio(usage):
"""Share of input tokens served from cache. Field names are placeholders."""
total = (usage["cache_read_tokens"]
+ usage["cache_write_tokens"]
+ usage["uncached_tokens"])
return usage["cache_read_tokens"] / total if total else 0.0
turn = {"cache_read_tokens": 35_000, "cache_write_tokens": 2_000, "uncached_tokens": 3_000}
print(f"{cache_hit_ratio(turn):.1%}") # 87.5%In a healthy loop the ratio is low on turn one and then stays high. If it drops to zero partway through a session, something broke the prefix, or the entry expired. Compare the requests before and after the drop and look for the first differing block.
Decision criteria
Caching pays off when the same large prefix is reused several times within the cache lifetime. That describes most coding agent sessions, so it is usually worth enabling. It helps less in these cases:
- One-off requests with no repeated prefix. The write premium can make them slightly more expensive.
- Very short prompts below the minimum size.
- Workflows with long idle gaps between requests, unless you choose the longer lifetime.
- Prompts that must contain per-request data near the top. Restructure them first.
Caching reduces the price of resent context. It does not reduce the context itself, so combine it with the context management techniques in the next chapter.
Exercise
A turn has a 30,000-token context, of which 24,000 tokens are a cached prefix. The input price is 3.0 USD per million tokens and the cache read multiplier is 0.1. What does the input cost with caching, what would it cost without, and what single change to prompt assembly would most likely turn the cached part into a cache miss?
Show answer
With caching, the uncached part is 6,000 tokens and the cached part counts as 24,000 × 0.1 = 2,400 effective tokens. The total is 8,400 effective tokens, so the cost is 8,400 × 3.0 / 1,000,000 = 0.0252 USD. Without caching, the cost is 30,000 × 3.0 / 1,000,000 = 0.09 USD. A likely cause of a miss is a changing value near the start of the prompt, such as a timestamp in the system prompt, or editing or reordering anything inside the prefix. The cache matches from the start, so any difference there invalidates everything after it.