← All guides AI Release
RU Subscribe to @ai_releaseorg

Claude 5-Minute Prompt Cache vs GPT 30-Minute Cache: Configuring TTL and the Cost of Pauses

Updated: 02.12.2026 · AI Release · @ai_releaseorg
Claude 5-Minute Prompt Cache vs GPT 30-Minute Cache: Configuring TTL and the Cost of Pauses

TL;DR

What you will get

Quick start

export ANTHROPIC_API_KEY="sk-ant-..."
export OPENAI_API_KEY="sk-..."
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic openai
python3 cache_probe.py

Details and checks are in the steps below.

Requirements and setup

Illustration: Requirements and setup
Illustration: Requirements and setup

Step 1. Split the prompt into a frozen prefix and a volatile tail

What to do: create two files. system_prompt.txt holds everything that never changes between runs: role instructions, output format rules, and the JSON schema of your tools. The volatile parts stay in code and are appended after the frozen block: timestamps, user IDs, session IDs, and retrieved documents.

Why: prompt caching is a prefix match. Both providers hash the beginning of the request and reuse the stored computation only if every token up to the breakpoint is byte-identical. A generated timestamp on line 1 changes the hash, and every token after it becomes a cache miss.

How to check: count the tokens of the frozen block and compare it with the provider minimum.

# token_count.py
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
stable = open("system_prompt.txt", encoding="utf-8").read()
print(client.messages.count_tokens(
    model=os.environ["CLAUDE_MODEL"],
    system=[{"type": "text", "text": stable}],
    messages=[{"role": "user", "content": "ping"}],
).input_tokens)

Example: python3 token_count.py prints 8421. If it prints 410, the prefix is too short to be worth caching, and you should stop here: you would pay cache-write overhead for nothing.

For OpenAI the same rule applies with no code change: system message first, then the user turn. The provider caches automatically once the prompt crosses its minimum length; there is no breakpoint object to declare. Confirm the minimum length in the OpenAI prompt-caching documentation.

Step 2. Set the TTL on Claude, set the key on OpenAI

Illustration: Step 2. Set the TTL on Claude, set the key on OpenAI
Illustration: Step 2. Set the TTL on Claude, set the key on OpenAI

What to do: on Claude, attach cache_control to the last stable block and choose the TTL. On OpenAI, there is no TTL parameter. Instead, stabilize the ordering and pass a stable prompt_cache_key so requests from the same agent land on the same cache.

# cache_probe.py — Claude path
import os, time
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
STABLE = open("system_prompt.txt", encoding="utf-8").read()
assert len(STABLE) > 1000, "prefix looks empty or truncated"

def ask(question: str):
    return client.messages.create(
        model=os.environ["CLAUDE_MODEL"],
        max_tokens=256,
        system=[{"type": "text", "text": STABLE,
                 "cache_control": {"type": "ephemeral"}}],
        messages=[{"role": "user", "content": question}],
    )

for i in (1, 2):
    r = ask("List the three checks in the deployment policy.")
    print(i, "write=", r.usage.cache_creation_input_tokens,
             "read=",  r.usage.cache_read_input_tokens,
             "input=", r.usage.input_tokens)
    time.sleep(2)

Example of the output shape (numbers depend on your prompt):

1 write= 8421 read= 0 input= 39
2 write= 0 read= 8421 input= 39

write on the first call means the prefix was stored. read on the second call means it was served from cache and billed as cached input. If the second line still shows write=8421, the prefix changed between calls.

Why the TTL matters: the default ephemeral cache on Claude is measured in minutes (5 minutes by default). Any agent that pauses longer than that loses the cache and pays a full write on the next call. For longer pauses, Anthropic offers an extended 1-hour TTL as a beta, enabled by sending the beta header and setting "ttl": "1h" on the same cache_control object:

client = Anthropic(
    api_key=os.environ["ANTHROPIC_API_KEY"],
    default_headers={"anthropic-beta": "extended-cache-ttl-2025-04-11"},
)
system = [{"type": "text", "text": STABLE,
           "cache_control": {"type": "ephemeral", "ttl": "1h"}}]

Extended TTL is a beta feature: the header string is versioned and may change. Copy the current value from the prompt-caching page of the Anthropic docs, and treat a failure to enable it as a configuration error, not a cache miss.

OpenAI path:

from openai import OpenAI
client = OpenAI()
r = client.chat.completions.create(
    model=os.environ["OPENAI_MODEL"],
    prompt_cache_key="agent-support-v1",
    messages=[{"role": "system", "content": STABLE},
              {"role": "user", "content": "List the three checks."}],
)
print("cached=", r.usage.prompt_tokens_details.cached_tokens,
      "total=", r.usage.prompt_tokens)

How to check: python3 cache_probe.py must show a non-zero read counter on the second call (Claude) or a non-zero cached value (OpenAI), with identical input between the two calls. If both counters stay at zero, go to Troubleshooting.

Turning TTL on again for every subagent multiplies the written tokens. If your agent has several roles, read Claude Code for Teams: Setting Up Subagents and a Shared AI Superagent first and give every subagent the same frozen prefix, so they share one cache entry instead of creating five.

Step 3. Survive a pause: TTL choice or keepalive ping

Illustration: Step 3. Survive a pause: TTL choice or keepalive ping
Illustration: Step 3. Survive a pause: TTL choice or keepalive ping

What to do: decide what your agent does between bursts of work, then pick one of two strategies.

SituationClaudeOpenAI
Pauses under the default TTLDefault ephemeral cache, no extra workProvider-managed cache, no extra work
Pauses of tens of minutesExtended 1-hour TTL (`"ttl": "1h"`)Keep the prefix byte-identical; retention is provider-side and not configurable
Pauses of hours or daysAccept a cache write on resumeAccept a cache write on resume
Counter to watch`cache_read_input_tokens``prompt_tokens_details.cached_tokens`

If the extended TTL is unavailable on your account, use a keepalive: a minimal request every 4 minutes that reads the prefix before the default TTL expires.

# keepalive.py — one cheap read of the cached prefix
*/4 * * * * cd /opt/agent && .venv/bin/python keepalive.py >> cache.log 2>&1

Why this works: each keepalive call is a cache read of the prefix instead of a cache write of the whole prompt, and it restarts the retention clock. The arithmetic is what decides the strategy: a 40-minute pause means about 10 cheap reads versus one full write plus a slow first response. Do that comparison with your own token counts and current prices, not with a rule of thumb from a blog post.

How to check:

grep -c "read= 0" cache.log        # keepalive runs that missed the cache
tail -n 5 cache.log

Success looks like read= carrying your prefix size on every line after the first, and write= 0. A write= 8421 line appearing mid-log means the cache expired between pings, so shorten the interval.

If your agent also runs the browser and background jobs, the same cost-control mechanics are described in How to Install and Configure Opencode v2: Agent Browser, Background Subagents and Model Cost Control; the TTL and prefix rules transfer unchanged.

Troubleshooting

Problem. The request fails as soon as you add cache_control

Problem. The cache never gets read, and both counters stay at zero

python3 -c "import json,hashlib;print(hashlib.sha256(open('system_prompt.txt','rb').read()).hexdigest())"

Run it before both calls. If the two hashes differ, the prefix changed and the cache correctly missed. Freeze the file and re-run cache_probe.py.

Problem. The first call after a pause is slow and bills a full write

Summary and next steps

Freeze the prefix, mark its end with a cache breakpoint, and choose a TTL or keepalive that matches how long your agent actually idles. Next, add a check that fails the deploy if cache_read_input_tokens drops to zero on the second call in staging.

FAQ

Does a cache hit make the response faster, or only cheaper?

It avoids recomputing the prefix, so the first token usually arrives earlier. Measure both calls with time python3 cache_probe.py on your own hardware before quoting a latency figure.

Can I set the TTL on OpenAI like I do on Claude?

No. OpenAI caches automatically and the retention window is provider-side; you influence hits only by keeping the prefix byte-identical and by passing a stable prompt_cache_key. Check the current documentation for the exact retention behavior.

Should I put the conversation history inside the cached block?

Cache only the part that repeats. History grows with every turn, so mark the system prompt and tool schemas as cacheable and let the growing history sit after the breakpoint.

Is caching worth it for a 300-token system prompt?

Usually not. Below the provider's minimum cacheable length nothing is stored, and on Claude a cache write is billed above normal input. Confirm the minimum in the docs and skip caching for short prompts.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Time to complete: 15–20 minutes in total. The Claude path (setting the TTL yourself) takes about 5 minutes; the OpenAI path takes about 30 because the cache is provider-managed and you can only measure it, not configure it. Difficulty: Intermediate

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is required?
Linux or macOS with a POSIX shell; Windows works through WSL2 with the same commands.; Python 3.10 or newer: python3 --version must print 3.10 or higher.; The anthropic and openai SDKs installed in an isolated virtualenv. Pin them in requirements.txt and read the SDK changelog before upgrading, because cache-related… → details (AR-GUIDE-KESHPROMPT-003)
How to do it?
Step 1. Split the prompt into a frozen prefix and a volatile tail → Step 2. Set the TTL on Claude, set the key on OpenAI → Step 3. Survive a pause: TTL choice or keepalive ping → details (AR-GUIDE-KESHPROMPT-004)
Which topics does it cover?
prompt caching TTL, кэш промптов Claude или GPT, сколько стоит кэширование промптов → details (AR-GUIDE-KESHPROMPT-002)
What are the key points?
Time to complete: 15–20 minutes in total. The Claude path (setting the TTL yourself) takes about 5 minutes; the OpenAI path takes about 30 because the cache is provider-managed and you can only measure it, not configure it. Difficulty: Intermediate → details (AR-GUIDE-KESHPROMPT-007)

3. Key facts

  1. Time to complete: 15–20 minutes in total. The Claude path (setting the TTL yourself) takes about 5 minutes; the OpenAI path takes about 30 because the cache is provider-managed and you can only measure it, not configure it. — evidence; status: заявление источника.
  2. Difficulty: Intermediate — evidence; status: заявление источника.
  3. You need: Python 3.10+, the anthropic and openai SDKs, an ANTHROPIC_API_KEY and an OPENAI_API_KEY, a stable prompt prefix of a few thousand tokens, and shell access to the machine that runs your agent. — evidence; status: заявление источника.
  4. Linux or macOS with a POSIX shell; Windows works through WSL2 with the same commands. — evidence; status: заявление источника.
  5. Python 3.10 or newer: python3 --version must print 3.10 or higher. — evidence; status: заявление источника.
  6. The anthropic and openai SDKs installed in an isolated virtualenv. Pin them in requirements.txt and read the SDK changelog before upgrading, because cache-related fields have been added over time. — evidence; status: заявление источника.

4. Entities

EntityTypeRole
prompt caching TTLтема/инструментупоминается в заголовке, TL;DR или разделах гайда
кэш промптов Claude или GPTтема/инструментупоминается в заголовке, TL;DR или разделах гайда
сколько стоит кэширование промптовтема/инструментупоминается в заголовке, TL;DR или разделах гайда
Windowsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Linuxплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
macOSплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Pythonплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
OpenAIкомпанияупоминается в заголовке, TL;DR или разделах гайда
Anthropicкомпанияупоминается в заголовке, TL;DR или разделах гайда
Claudeтема/инструментупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → Claude 5-Minute Prompt Cache vs GPT 30-Minute Cache: Configuring TTL and the Cost of Pauses (AR-GUIDE-KESHPROMPT-001).
  • Guide — includes step → Step 1. Split the prompt into a frozen prefix and a volatile tail (AR-GUIDE-KESHPROMPT-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
No external links——

Cite as: AI Release. Кэш промптов Claude (5 минут) или GPT (30 минут): как настроить TTL и не переплачивать за паузы в работе агента. ai-release.org.