Skip to content
Max Narditdata & ai systems
← Articles
14 mindev

Claude prompt caching TTL: when the 1-hour cache pays for its 2x write

Counting pauses works for a fixed prefix and misleads for one that grows, because the premium lands on every token the cache writes. A replay script for your own request log, two synthetic workloads that come out opposite ways, and a keep-alive whose verdict depends on knowing when a session ends.

Contents

Claude’s 1-hour prompt cache is usually chosen by counting pauses. Anthropic’s own guidance puts it there for prompts “likely used less frequently than every 5 minutes, but more frequently than every hour”: a user who replies after a coffee, a side agent that runs for ten minutes. The bill does not work by pauses. The hour costs 2 times the base input price on every token the cache writes, against 1.25 times on the default 5 minutes, and an agent loop writes new tokens on every turn.

For a prefix that stays the same size, counting pauses gives the right answer, and there is an exact threshold for it. For a prefix that grows, it can point the wrong way: a session with one 20-minute pause passes the pause test and still costs more on the hour. Nothing here was run against the API. The cache rules are the docs’, the dollar figures come from a replay script you can run on your own log.

What do Claude’s 5-minute and 1-hour cache TTLs cost?

A 5-minute write costs 1.25 times the model’s base input price, a 1-hour write costs 2 times, and a cache hit costs a fraction that depends on the model. That last multiplier is no longer one number. Fable 5.2, Mythos 5.2, Fable 5.1 and Mythos 5.1 read at 0.025 times base, Opus 5.5 and Sonnet 5.5 at 0.05, and all other models at 0.1. From the Anthropic pricing table, per million input tokens:

ModelBase input5m write1h writeCache hit
Claude Fable 5.2$8$10$16$0.20
Claude Opus 5.5$4$5$8$0.20
Claude Sonnet 5.5$2$2.50$4$0.10
Claude Opus 4.8$5$6.25$10$0.50
Claude Sonnet 4.6$3$3.75$6$0.30

On a hit, both lifetimes behave the same for latency, so the hour’s latency gain is only the hits it keeps alive past 5 minutes. One more reason that is not about the cache price: cache-read tokens do not count toward the input-tokens-per-minute limit, so a prefix that is still warm after a pause keeps an input-heavy workload further from a 429. Requests per minute and output tokens still count.

When does the Claude cache lifetime start and reset?

It starts when the request that writes or reads the entry starts, and every hit resets it at no extra charge. The docs spell out the consequence: if a response takes 4 minutes to stream, the follow-up that reuses the prefix has about 1 minute to start. The gap that matters is start to start, so log the time each request was sent. Measure a pause from the end of one response and it looks shorter than the cache sees it.

Three more rules from the prompt caching page shape any TTL decision:

  • A read does not upgrade an entry. A request that reads an entry written with the 5-minute TTL restarts its 5-minute lifetime, even if that request now sets "ttl": "1h". Only new writes get the hour, so switching right before a break does nothing for what is already cached.
  • Longer lifetimes go first. One request can mix both, but every 1-hour breakpoint must come before any 5-minute one. That allows a 1-hour stable head with a 5-minute conversation tail, and not the reverse.
  • Treat the lifetime as exact. The docs call it a minimum: entries are deleted “promptly, though not immediately” after it. Past the window, reuse is no longer guaranteed, and the replay below treats the entry as gone at exactly 5 minutes or 1 hour.

If reads stay at zero even between requests seconds apart, the TTL is not the first suspect. The prefix may change between requests, sit under the model’s minimum cacheable length, or have its breakpoint outside the lookback window, and cache diagnostics names where a changed prefix broke.

When is the 1-hour Claude cache TTL cheaper?

When the pauses it bridges save more than its premium costs on everything it writes. Take one pause between 5 and 60 minutes before reusing a cached prefix of P tokens. On 5 minutes that prefix is written again at 1.25 times base; on the hour it is read at the cache-hit rate. The saving is (1.25 minus the read rate) times P. Against that, every token written under the hour costs 0.75 times base more than it would on 5 minutes. That includes the first write of every session and every rewrite after a pause of an hour or more, where the hour loses outright (2 times instead of 1.25).

For a prefix that never grows, this reduces to a ratio. Count the cold writes (session starts plus pauses of an hour or more) and the pauses from 5 to 60 minutes. The hour wins when there are more than 0.75 / (1.25 minus the read rate) bridged pauses per cold write:

Cache-hit multiplierModelsBridged pauses needed per cold write
0.1Opus 4.8, Sonnet 4.6 and other models0.652
0.05Opus 5.5, Sonnet 5.50.625
0.025Fable 5.2 and 5.1, Mythos 5.2 and 5.10.612

The cheaper reads on new models barely move the threshold, because the saving is dominated by the 1.25 rewrite you avoid. The threshold is per cold write, so a session that starts, pauses once for 20 minutes and finishes is over it.

A growing prefix changes the arithmetic. In an agent loop each turn appends tool calls and results, and each of those tokens is written once, at 2 times base on the hour. A pause saves only on what was already cached when it started; the premium lands on everything written before and after it. Call S the tokens the hour reads that 5 minutes would have written again, and W every token the hour writes, rewrites included. The hour wins when (1.25 minus the read rate) times S exceeds 0.75 times W. The same 0.625 threshold on Opus 5.5 holds, measured in tokens: the hour wins when S is more than 62.5% of W.

The smallest case where the pause count misleads is one session. It grows from 30K to 200K tokens in 5K steps a minute apart, with a single 20-minute pause when it reaches 100K. One bridged pause per cold write is well over 0.625, so the pause test says take the hour. In tokens, S is 100K and W is 200K, so the ratio is 0.5 and the hour loses. The replay agrees: $2.37 on the hour against $2.25 on 5 minutes on Opus 5.5, and $2.20 for a 1-hour breakpoint on a 25K-token head with a 5-minute tail.

How do you compute the Claude TTL break-even from your own logs?

Replay your requests under each policy instead of repricing what you were billed. Multiplying today’s 5-minute writes by 2 ignores that under the hour some of those writes would have been reads. The script below needs three facts per request:

  • chain: which conversation or agent loop the request extends
  • start: when the request was sent, in epoch seconds
  • prefix: cache_read_input_tokens + cache_creation_input_tokens from the response usage

An optional static field gives the size of the stable head (tools and system instructions) inside the prefix. It drives a third policy, a 1-hour breakpoint on the head and 5 minutes on the tail; without it, that column equals the 5-minute one. A fourth policy stays on 5 minutes and keeps the prefix warm through pauses with scheduled reads, covered two sections down.

python
#!/usr/bin/env python3
"""Replay request logs under Claude prompt-cache TTL policies.
 
Input: JSONL, one request per line:
  {"chain": "conv-1", "start": 1764547200.0, "prefix": 48210, "static": 30000}
Each chain must be serial and append-only: one request at a time, each one
starting later than the last and extending its prefix.
"""
import json, math, sys
from collections import defaultdict
 
# $ per million input tokens, cache-read multiplier (Anthropic pricing page)
MODELS = {
    "claude-fable-5-2":  (8.00, 0.025),
    "claude-opus-5-5":   (4.00, 0.05),
    "claude-sonnet-5-5": (2.00, 0.05),
    "claude-opus-4-8":   (5.00, 0.10),
    "claude-sonnet-4-6": (3.00, 0.10),
}
W5, W1H = 1.25, 2.0
PING, GIVEUP = 270, 3600   # keep-alive every 4.5 min, stop after an hour idle
CLOSED = False             # True if your app knows when a session ends
 
 
def replay(chains, rm):
    """Cost in base-input-token units per policy."""
    cost = defaultdict(float)
    for reqs in chains.values():
        s = reqs[0].get("static", 0)
        prev = None
        for r in reqs:
            p = r["prefix"]
            if prev is None:
                cost["5m"] += p * W5
                cost["1h"] += p * W1H
                cost["split"] += s * W1H + (p - s) * W5
                cost["ping"] += p * W5
                prev = r
                continue
            gap = r["start"] - prev["start"]
            shared = prev["prefix"]
            new = p - shared
            for name, ttl, w in (("5m", 300, W5), ("1h", 3600, W1H)):
                cost[name] += shared * rm + new * w if gap < ttl else p * w
            # split: 1h breakpoint on the static head, 5m on the tail
            head = s * rm if gap < 3600 else s * W1H
            tail = (shared - s) * rm + new * W5 if gap < 300 else (p - s) * W5
            cost["split"] += head + tail
            # ping: max_tokens=0 re-send of the previous request every PING s
            pings = math.ceil(min(gap, GIVEUP) / PING) - 1
            warm = gap - pings * PING < 300
            cost["ping"] += pings * prev["prefix"] * rm
            cost["ping"] += shared * rm + new * W5 if warm else p * W5
            prev = r
        if not CLOSED:  # nobody came back: the pinger runs until it gives up
            cost["ping"] += (math.ceil(GIVEUP / PING) - 1) * prev["prefix"] * rm
    return cost
 
 
def main(path):
    chains = defaultdict(list)
    with open(path) as f:
        for line in f:
            if line.strip():
                r = json.loads(line)
                chains[r["chain"]].append(r)
    if not chains:
        sys.exit("no requests")
    gaps = []
    for name, v in chains.items():
        v.sort(key=lambda r: r["start"])
        if len({r.get("static", 0) for r in v}) > 1 or v[0].get("static", 0) > v[0]["prefix"]:
            sys.exit(f"{name}: static must be constant and fit inside the first prefix")
        if any(b["start"] <= a["start"] or b["prefix"] < a["prefix"] for a, b in zip(v, v[1:])):
            sys.exit(f"{name}: needs strictly increasing starts and a prefix that never shrinks")
        gaps += [b["start"] - a["start"] for a, b in zip(v, v[1:])]
    short = sum(g < 300 for g in gaps)
    mid = sum(300 <= g < 3600 for g in gaps)
    n = sum(len(v) for v in chains.values())
    print(f"requests: {n}, chains: {len(chains)}; gaps: {short} under 5 min, "
          f"{mid} from 5 to 60 min, {len(gaps) - short - mid} of an hour or more")
    print(f"{'model':<18}{'5m':>10}{'1h':>10}{'split':>10}{'ping':>10}   cheapest")
    for model, (base, rm) in MODELS.items():
        c = replay(chains, rm)
        usd = {k: v * base / 1e6 for k, v in c.items()}
        low = min(usd.values())
        best = " = ".join(k for k in ("5m", "1h", "split", "ping") if usd[k] - low < 1e-9)
        row = "".join(f"{'$%.2f' % usd[k]:>10}" for k in ("5m", "1h", "split", "ping"))
        print(f"{model:<18}{row}   {best}")
 
 
if __name__ == "__main__":
    main(sys.argv[1])

The model is narrow on purpose, and it will mislead you wherever your log breaks its assumptions. Each chain is one serial, append-only conversation whose cache breakpoint stays within the API’s lookback window; the script refuses a chain whose prefix shrinks or whose requests share a start time, and overlapping requests or a chain that branches need a richer replay. Nothing evicts an entry inside its lifetime, and everything is gone right after it. The static head has to be constant and at least the model’s minimum cacheable length. Output tokens and uncached input after the last breakpoint are left out, since they are the same under every policy as long as the keep-alive request carries nothing after its breakpoint. If several chains share one head, the split column charges each of them for writing it.

Check it on the smallest case first. One 100K-token prefix, a second request 20 minutes later:

shell
printf '%s\n' \
  '{"chain":"x","start":0,"prefix":100000,"static":100000}' \
  '{"chain":"x","start":1200,"prefix":100000,"static":100000}' > one_gap.jsonl
python3 ttl_breakeven.py one_gap.jsonl
requests: 2, chains: 1; gaps: 0 under 5 min, 1 from 5 to 60 min, 0 of an hour or more
model                     5m        1h     split      ping   cheapest
claude-fable-5-2       $2.00     $1.62     $1.62     $1.36   ping
claude-opus-5-5        $1.00     $0.82     $0.82     $0.86   1h = split
claude-sonnet-5-5      $0.50     $0.41     $0.41     $0.43   1h = split
claude-opus-4-8        $1.25     $1.05     $1.05     $1.52   1h = split
claude-sonnet-4-6      $0.75     $0.63     $0.63     $0.92   1h = split

On Opus 5.5 that is two writes at 1.25 times ($1.00) against one write at 2 times plus one read ($0.82), as the formula says. Split ties with the hour because the whole prefix is the head. Add a third request after a further 70-minute pause and, still on Opus 5.5, the hour loses ($1.62 against $1.50 on 5 minutes): one bridged pause per two cold writes is under the 0.625 line.

What does the replay show on two synthetic Claude workloads?

That the shape of the workload decides the TTL more than the model does. Both logs are generated, not measured, and they differ in pause pattern, growth and size; the generator is at the end so you can change its assumptions.

The first imitates a coding agent: 40 sessions that start at 30K tokens, of which 25K is tools and system instructions, run bursts of 6 to 15 turns 20 seconds to 2 minutes apart, grow by 1.5K to 6K tokens per turn, and then wait. Half the waits add 1 to 4 minutes, 30% add 6 to 40 minutes, 20% add more than an hour.

requests: 1487, chains: 40; gaps: 1391 under 5 min, 35 from 5 to 60 min, 21 of an hour or more
model                     5m        1h     split      ping   cheapest
claude-fable-5-2     $151.15   $171.11   $151.72   $144.46   ping
claude-opus-5-5       $89.66    $99.98    $90.04   $100.01   5m
claude-sonnet-5-5     $44.83    $49.99    $45.02    $50.00   5m
claude-opus-4-8      $147.29   $161.04   $147.98   $194.44   5m
claude-sonnet-4-6     $88.37    $96.63    $88.79   $116.67   5m

The hour costs 11.5% more on Opus 5.5, though 35 of the 56 gaps longer than 5 minutes fall inside its window. Here the pause count already points the right way: 35 bridged pauses against 61 cold writes (40 session starts, 21 long pauses) is 0.57, under the line. Growth sets the size of the loss. Replaying the same timestamps with every session held at its average size puts the hour 2.5% behind on Opus 5.5; with the real growth it is 11.5%, because every appended turn is written at 2 times and every long pause rewrites a context that can pass 200K tokens. Split barely matters here: a 25K head is small next to the tail.

The second imitates a chat over a fixed document: 200 conversations, each over its own 80K-token document, 2 to 8 questions apiece, 30 seconds to 25 minutes apart, a few hundred tokens of growth per turn.

requests: 922, chains: 200; gaps: 145 under 5 min, 577 from 5 to 60 min, 0 of an hour or more
model                     5m        1h     split      ping   cheapest
claude-fable-5-2     $653.16   $283.16   $296.79   $252.81   ping
claude-opus-5-5      $327.79   $147.60   $154.22   $168.08   1h
claude-sonnet-5-5    $163.89    $73.80    $77.11    $84.04   1h
claude-opus-4-8      $412.76   $199.56   $207.34   $314.31   1h
claude-sonnet-4-6    $247.65   $119.73   $124.40   $188.58   1h

Here the hour cuts the modeled cache spend by 52% to 57% depending on the model; output and uncached input are not in these numbers. The prefix is large and nearly static, so the premium is paid about once per conversation, and 577 bridged pauses against 200 cold writes is far over the line. Split costs 4% to 5% more than the full hour here, and on non-Fable rows it is never the cheapest column in either table and never far from the winner, which is what a hedge looks like. Use it when you know the head is reused across pauses longer than 5 minutes and cannot predict the tail. On Fable 5.2 the keep-alive beats it by 5% in the agent table and 15% in the chat.

The ping column wins the Fable 5.2 row in both tables. That is the next question.

Does a max_tokens 0 keep-alive beat the Claude 1-hour TTL?

On Fable 5.2 it came out cheapest in both workloads. On Opus 5.5 and Sonnet 5.5 it depends on whether your application knows when a session has ended. The keep-alive stays on the 5-minute tier and adds scheduled reads: a request with max_tokens: 0 reads the prompt, writes or refreshes the cache at its breakpoints and returns without output. The docs describe it as pre-warming, say to repeat it at least every 5 minutes, and recommend the 1-hour TTL for longer gaps. Comparing the two on price is the replay’s modeling, not Anthropic’s advice, and I have not run the keep-alive against the API.

It works on Fable 5.2 because a read there costs 0.025 times base. Across a 45-minute pause the pinger sends nine requests, which together cost under a quarter of the base price of the prefix, while the hour charges three quarters extra on every token it writes. Mythos 5.2 has the same published rates, so the same should hold there; it is not in the replay. On 0.05 models the decisive cost is the session nobody comes back to. The pinger cannot know a pause is final, so it keeps reading the full prefix until it gives up, an hour in the script. Those trailing pings decide it on Opus 5.5 in both tables. Set CLOSED = True, for an application that knows when a session ends and stops pinging there, and the picture changes:

agent, CLOSED = True
claude-fable-5-2     $151.15   $171.11   $151.72   $127.42   ping
claude-opus-5-5       $89.66    $99.98    $90.04    $82.97   ping
claude-sonnet-5-5     $44.83    $49.99    $45.02    $41.48   ping
claude-opus-4-8      $147.29   $161.04   $147.98   $151.85   5m
claude-sonnet-4-6     $88.37    $96.63    $88.79    $91.11   5m
 
chat, CLOSED = True
claude-fable-5-2     $653.16   $283.16   $296.79   $208.75   ping
claude-opus-5-5      $327.79   $147.60   $154.22   $124.03   ping
claude-sonnet-5-5    $163.89    $73.80    $77.11    $62.01   ping
claude-opus-4-8      $412.76   $199.56   $207.34   $204.17   1h
claude-sonnet-4-6    $247.65   $119.73   $124.40   $122.50   1h

On 0.1 models the keep-alive does not win either way.

Two conditions make the ping cost what the script charges. The ping has to end at the cached breakpoint, with nothing after it billed as fresh input; re-sending the previous request under automatic caching usually does that, because the breakpoint goes on the last eligible block. Check usage.input_tokens on a ping: if it is not zero, add that much fresh input per ping to the keep-alive’s cost. And it has to be a request the API accepts with max_tokens: 0, which rules out stream: true, thinking.type: "enabled", structured outputs via output_config.format, a forced tool_choice of any or tool, and anything inside Message Batches. Streaming is a transport option, so the ping can drop it. The thinking mode and structured outputs are part of the prompt, so a ping that drops them would not touch the same entry: for requests with thinking.type: "enabled" or output_config.format, the choice is between plain 5 minutes and the hour. Adaptive thinking is not on the list, so an adaptive request, which on Fable 5.2 is every request, can keep its thinking and effort settings on the ping.

Which TTL does Claude Code use, and how do you change it?

On a Claude subscription within plan usage, the main conversation gets the hour; with an API key, usage credits or a cloud provider, it gets 5 minutes. Everything outside the main conversation (subagents, workflows, compaction, session titles) gets 5 minutes, except a few helper requests that Anthropic sets to an hour server-side, and only within included subscription usage. Those five-minute subagent writes add up: in the background-subagent measurement on this site, about two thirds of the subagents’ priced usage was cache writes.

You can choose per bucket, per the Claude Code caching docs. promptCacheTtl in settings, or CLAUDE_CODE_PROMPT_CACHE_TTL, sets the main conversation; subagentPromptCacheTtl, or CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL, sets everything else. Both take 5m or 1h and need Claude Code 2.1.242 or later. FORCE_PROMPT_CACHING_5M=1 overrides everything, which is the switch for comparing the two. Claude Code 2.1.334, released December 1, added cacheWrite5m and cacheWrite1h keys to the modelPricing setting and cache_write_5m / cache_write_1h to gateway pricing overrides, so a custom price list can now price the two lifetimes separately.

My read for an API key: a Claude Code main conversation is a growing loop, so start from 5 minutes and switch only if you want idle compaction, which only runs on the one-hour TTL, or if your pauses bridge a large share of what the session writes. That is the S-over-W test from above, and a session that reads 100K tokens after every 20-minute coffee while adding 5K passes it easily. That post also shows how to check which lifetime your writes use.

How is OpenAI’s prompt cache lifetime different from Claude’s?

OpenAI gives 30 minutes for the write price Claude charges for 5. Per the OpenAI prompt caching guide, on GPT-5.6 and later:

ClaudeOpenAI, GPT-5.6 and later
Default lifetime and write price5 minutes, 1.25x30 minutes, 1.25x
Long lifetime and write price1 hour, 2x12 hours, 2.5x (Responses API)
Read price0.025x to 0.1x by model0.1x; 0.05x on GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol, GPT-6.1 Terra
What a read does to the clockrestarts it, counted from the request starta 30-minute read extends coverage to at least 30 minutes after it
Settingttl on cache_controlprompt_cache_options.ttl, or per breakpoint prompt_cache_breakpoint.ttl
Minimum cacheable prompt512 tokens on the newest models1,024 visible input tokens

The guide does not say whether OpenAI’s window counts from the start of the request, so I would not assume it matches Claude’s rule. Three more differences matter for the arithmetic: entries can outlive their minimum, moving valid 30-minute coverage to 12 hours is billed as a 12-hour write, and a 30-minute read of 12-hour coverage does not restart the 12-hour clock.

The 24-hour default that often comes up in this comparison belongs to older OpenAI models, which use prompt_cache_retention. GPT-5.5 and GPT-5.5 Pro support only 24h; other earlier models take in_memory or 24h where extended retention is available, and for models that support both, the default became 24h on May 29 for organizations without Zero Data Retention. The guide’s own wording is weaker than the name: 24h “typically keeps entries available for around 30 minutes and can retain them for up to 24 hours.” On those models a cache write costs nothing extra.

The break-even carries over with OpenAI’s numbers. The long tier’s premium over the default is 1.25 instead of 0.75, and it bridges pauses between 30 minutes and 12 hours, assuming 30-minute entries are gone at 30 minutes; since entries can outlive their minimum, count from actual reads and writes when you have them. For a static prefix, 12 hours pays at about 1.09 bridged pauses per cold write at a 0.1 read price, or 1.04 at 0.05, against about 0.65 and 0.63 for Claude’s hour.

Claude prompt caching TTL: which one to choose

My read, in this order. Measure the shape of the prefix before you count pauses: a large, stable prefix that is read again after breaks (a document, a codebase map, a long set of system instructions) belongs on the hour, or on a 1-hour head with a 5-minute tail when the tail is unpredictable. A context that grows every turn pays the hour’s premium on everything it appends; it needs bridged-pause tokens worth more than 62.5% of everything written (on Opus 5.5) before the hour comes back. On Fable 5.2, and by the same prices Mythos 5.2, price a keep-alive first, and on Opus 5.5 and Sonnet 5.5 price it too if your application knows when a session ends.

Then run the replay on a week of your own log before switching. The token test (S over W) holds for any append-only chain under the replay’s assumptions; counting pauses instead of tokens works only when the prefix stays the same size. The synthetic workloads here show the direction of each effect, not your bill. After the switch, watch the read count on the first request after a pause: it tells you whether the cache you paid for was still there.

Synthetic workload generator for the Claude TTL replay

python
#!/usr/bin/env python3
"""Synthetic request logs for ttl_breakeven.py (no real data)."""
import json, random, sys
 
def agent(rng, out):
    # coding-agent sessions: bursts of tool-loop turns, then a pause
    for s in range(40):
        t, prefix, static = 1_764_547_200 + s * 86_400, 30_000, 25_000
        for b in range(rng.randint(2, 5)):
            for _ in range(rng.randint(6, 15)):
                out.append({"chain": f"agent-{s}", "start": t,
                            "prefix": prefix, "static": static})
                t += rng.uniform(20, 120)
                prefix = min(prefix + rng.randint(1_500, 6_000), 400_000)
            u = rng.random()
            t += (rng.uniform(60, 240) if u < 0.5
                  else rng.uniform(360, 2_400) if u < 0.8
                  else rng.uniform(4_200, 10_800))
 
def chat(rng, out):
    # document Q&A: 80K stable document, short turns
    for s in range(200):
        t, prefix, static = 1_764_547_200 + s * 3_600, 82_000, 80_000
        for _ in range(rng.randint(2, 8)):
            out.append({"chain": f"chat-{s}", "start": t,
                        "prefix": prefix, "static": static})
            t += rng.uniform(30, 1_500)
            prefix += rng.randint(300, 1_200)
 
rng, rows = random.Random(7), []
{"agent": agent, "chat": chat}[sys.argv[1]](rng, rows)
for r in rows:
    print(json.dumps(r))
shell
python3 make_synthetic.py agent > agent.jsonl
python3 make_synthetic.py chat > chat.jsonl
python3 ttl_breakeven.py agent.jsonl
python3 ttl_breakeven.py chat.jsonl

01 / Discussion

No comment section here — all discussions happen on X.

Max Nardit@mnardit

02 / More articles