Sub topic 6
How long a cache entry lives and what refreshes it
This chapter assumes you have read the earlier chapters on exact prefix matching and on explicit versus automatic caching. You should also be comfortable reading short Python snippets and thinking in terms of requests per minute. Provider numbers below (lifetimes, multipliers) are the published values at the time of writing. They change, so confirm them in the provider's documentation before you build a cost model on them.
Why cache entries expire at all
A cache entry is the saved attention state (the key/value data) for a prefix of your prompt. The provider keeps it in fast accelerator memory or nearby storage. That memory is limited and shared by every customer, so the provider cannot hold entries forever. It gives each entry a lifetime and drops it when the lifetime ends.
The lifetime is the main reason a cache that works in your test fails in production. In a test you send two requests a few seconds apart. In production the same prompt might be used once every 20 minutes, and every request is then a miss.
Time to live and refresh on use
The time to live (TTL) is how long an entry stays valid after its last use. Two parts of that definition matter:
- The clock is usually measured from the last use, not from when the entry was created.
- A cache hit resets the clock. This is called refresh on use.
So a prefix that is requested steadily can stay cached indefinitely, even with a short TTL. A prefix that goes quiet for longer than the TTL is evicted, and the next request pays the full write price again.
The sequence below shows an entry with a 5 minute TTL.
Typical lifetimes by provider style
Providers differ, and the differences affect design.
| Provider style | Default lifetime | Longer option | Refreshed by hits |
|---|---|---|---|
| Anthropic Messages API (explicit breakpoints) | 5 minutes | 1 hour, set per breakpoint, at a higher write price | Yes, at no extra charge |
| OpenAI (automatic caching) | A few minutes of inactivity, often 5 to 10, and always cleared within about an hour | Extended retention of up to 24 hours on some models, selected with a request parameter | Yes |
| Google Gemini (implicit and explicit caching) | Implicit: not guaranteed. Explicit: you set a TTL, 1 hour by default | You choose the TTL, and storage is billed for the time held | Explicit entries do not refresh. You update the TTL yourself |
Treat these as typical, not guaranteed. For automatic caching in particular, the provider decides when to evict, so a hit is never promised. Design for "usually hits" and keep the uncached path correct and affordable.
Choosing a lifetime on an explicit breakpoint
With Anthropic's API you pick the lifetime per breakpoint. The default is 5 minutes. Add ttl to ask for 1 hour.
import anthropic
client = anthropic.Anthropic()
POLICY = open("policy.md").read() # must meet the model's minimum cacheable length
response = client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=512,
system=[
{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral", "ttl": "1h"},
}
],
messages=[{"role": "user", "content": "Summarize the refund rules."}],
)
u = response.usage
print("written:", u.cache_creation_input_tokens)
print("read:", u.cache_read_input_tokens)If you mix lifetimes in one request, put the longer-lived breakpoints earlier in the prompt than the shorter-lived ones. Content that rarely changes, such as a policy document, gets the 1 hour breakpoint. Content that changes more often, such as the running conversation, gets the 5 minute breakpoint after it. Check the provider's documentation for the exact ordering rule and how the usage fields report each lifetime.
Simulating refresh behavior
A small model makes the rules concrete. This script replays request times against a TTL, with refresh on use switched on or off.
def simulate(request_times, ttl, refresh=True):
"""Return 'hit' or 'miss' for each request time, in seconds."""
expires = None
results = []
for t in request_times:
alive = expires is not None and t <= expires
results.append("hit" if alive else "miss")
if not alive or refresh:
expires = t + ttl # written on a miss, extended on a hit if refresh
return results
times = [0, 240, 480, 900, 1100]
print(simulate(times, ttl=300, refresh=True))
print(simulate(times, ttl=300, refresh=False))The output is:
['miss', 'hit', 'hit', 'miss', 'hit']
['miss', 'hit', 'miss', 'miss', 'hit']With refresh, the request at 240 seconds extends the entry to 540, so the request at 480 still hits. Without refresh, the entry written at 0 dies at 300, and the request at 480 misses. Both runs miss at 900 because the gap since the previous request is 420 seconds, longer than the 300 second TTL.
The rule to take from this is that the gap between consecutive requests that use the prefix is what matters, not the total age of the entry.
What counts as a use
Several details decide whether the clock really resets.
- Only a matching prefix refreshes. If a request changes any early token, it does not hit, so it does not extend the old entry. It may write a new entry under the new prefix instead.
- Each breakpoint has its own entry. A request that hits a long prefix and a shorter one refreshes the entries it read. An older shorter entry that a request did not touch can still expire.
- Writes are not hits. A miss creates an entry with a fresh lifetime, but you paid the write price to get it.
- The entry is not instantly available. An entry usually becomes readable only after the first response has started. A second request sent at the same moment can miss. A later chapter covers parallel requests and warming.
- Eviction can come early. Under heavy load, an automatically cached entry may disappear before its nominal lifetime. Do not treat the TTL as a promise.
Keeping an entry alive
If your traffic has gaps longer than the TTL, you have three options.
- Pay for a longer TTL. Use the 1 hour option (or extended retention). Compare the higher write price with the cost of misses.
- Send keep-alive requests. A cheap request that reuses the prefix, for example with a very small
max_tokens, resets the timer. You pay the cache read price plus a few output tokens each time. This only pays off if a keep-alive costs less than the rewrite it avoids. - Accept the misses. For low-traffic prompts this is often the right choice.
The break-even calculation is simple. This function compares the cost of letting an entry expire between requests with the cost of a 1 hour write, using multipliers on the base input price. The values shown (1.25 for a 5 minute write, 2.0 for a 1 hour write, 0.1 for a read) match Anthropic's published pricing at the time of writing.
def cost_per_request(tokens, requests_per_hour, gap_minutes, ttl_minutes,
write_5m=1.25, write_1h=2.0, read=0.1):
"""Cost in units of 'base-priced input tokens' per request, one prefix."""
if ttl_minutes == 5:
write = write_5m
else:
write = write_1h
if gap_minutes <= ttl_minutes:
# Steady traffic: one write per hour, every other request is a read.
writes = 1
else:
# Every request arrives after expiry, so every request is a write.
writes = requests_per_hour
reads = requests_per_hour - writes
total = tokens * (writes * write + reads * read)
return total / requests_per_hour
# 10,000-token prefix, one request every 20 minutes (3 per hour)
print(cost_per_request(10_000, 3, gap_minutes=20, ttl_minutes=5)) # 12500.0
print(cost_per_request(10_000, 3, gap_minutes=20, ttl_minutes=60)) # 8000.0
# One request every 2 minutes (30 per hour)
print(cost_per_request(10_000, 30, gap_minutes=2, ttl_minutes=5)) # 1250.0 + 10000*29*0.1/30 -> about 1,217The first call prints 12500.0 because every request is a 5 minute write at 1.25 times the base price, which is worse than sending the prompt uncached (10,000). The second prints 8000.0: one 2.0 write and two reads, averaged over three requests. At 2 minute gaps the 5 minute TTL is already enough, and the 1 hour option would only raise the write cost. The last line prints a value near 1,217.
Common mistakes
- Testing with back-to-back calls. Two calls a second apart always look like a hit. Test with realistic gaps, including one longer than the TTL.
- Assuming a hit means a long life. A hit extends the entry only by the TTL from that moment. Traffic that pauses overnight starts cold in the morning.
- Paying for 1 hour on busy prefixes. If a prefix is hit every minute, the 5 minute TTL never expires. The 1 hour write price is wasted.
- Using keep-alives on cold, rarely used prompts. Pings to keep a prompt warm that nobody asks for cost more than a miss.
- Reading a miss as a bug in your prompt. An expired entry and a changed prefix both show as a miss. Check the gap between requests before you start editing the prompt.
Exercise
A prompt has a 5 minute TTL with refresh on use. Requests arrive at minutes 0, 3, 7, 14 and 16. Which are hits and which are misses? Would a 1 hour TTL change the result, and what would you check before paying for it?
Show answer
Minute 0 is a miss (the entry is written, valid until minute 5). Minute 3 is a hit (refreshed until minute 8). Minute 7 is a hit (refreshed until minute 12). Minute 14 is a miss, because the gap since minute 7 is 7 minutes, more than 5 (a new entry is written, valid until minute 19). Minute 16 is a hit. With a 1 hour TTL, minute 14 would also be a hit, so you would turn one 5 minute write into a read. Before paying the higher 1 hour write price, check how often gaps longer than 5 minutes occur in real traffic and compare the cost of those extra writes with the extra write premium of the 1 hour option.
Exercise
You run the simulate function with times [0, 100, 450] and ttl=300. What does it return with refresh=True and with refresh=False?
Show answer
With refresh=True it returns ['miss', 'hit', 'hit']. The hit at 100 extends the entry to 400, but 450 is later than 400, so the third request is actually a miss: ['miss', 'hit', 'miss']. With refresh=False the entry written at 0 expires at 300, so the result is ['miss', 'hit', 'miss'] as well. The two settings agree here because the gap from 100 to 450 is 350 seconds, longer than the TTL.