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

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kesh-promptov-claude-5-minut-ili-gpt-30-minut-kak-nastr_en.html

## TL;DR

- 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
- 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.

## What you will get

- `cache_probe.py`: a script that sends the same request twice and prints the cache write, cache read, and plain input counters, so you can tell in one line whether a cache hit occurred.
- `system_prompt.txt` plus a rule for splitting the prompt into a frozen prefix and a volatile tail, with the exact fields to place on each side.
- A working long-pause configuration: a 1-hour cache on Claude (where the beta is enabled for your account) or a keepalive cron job, plus the equivalent ordering fix for OpenAI.

## Quick start

```bash
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](https://ai-release.org/guides/img/kesh-promptov-claude-5-minut-ili-gpt-30-minut-kak-nastr-en-1.jpg?v=1796222495)


- 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 fields have been added over time.
- Two API keys with billing enabled. Caching does not work on a key without quota.
- A prompt whose stable part is large enough to be cacheable at all. Both providers have a minimum cacheable length; check the current number for your model in the provider's prompt-caching documentation rather than assuming.
- Know where the prices are. Every price figure moves, so read cached-input pricing from the provider's pricing page on the day you deploy. This guide never quotes a number for that reason.

## 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.

```python
# 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](https://ai-release.org/guides/img/kesh-promptov-claude-5-minut-ili-gpt-30-minut-kak-nastr-en-2.jpg?v=1796222500)


**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.

```python
# 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):

```text
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:

```python
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:**

```python
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](https://ai-release.org/guides/claude-code-dlya-komandy-kak-nastroit-subagentov-i-obsc.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide) 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](https://ai-release.org/guides/img/kesh-promptov-claude-5-minut-ili-gpt-30-minut-kak-nastr-en-3.jpg?v=1796222506)


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

| Situation | Claude | OpenAI |
|---|---|---|
| Pauses under the default TTL | Default ephemeral cache, no extra work | Provider-managed cache, no extra work |
| Pauses of tens of minutes | Extended 1-hour TTL (`"ttl": "1h"`) | Keep the prefix byte-identical; retention is provider-side and not configurable |
| Pauses of hours or days | Accept a cache write on resume | Accept 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.

```bash
# 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:**

```bash
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](https://ai-release.org/guides/kak-ustanovit-i-nastroit-opencode-v2-brauzer-dlya-agent.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide); the TTL and prefix rules transfer unchanged.

## Troubleshooting

**Problem. The request fails as soon as you add `cache_control`**

- Error: `cache_control cannot be set for empty text content blocks`
- Cause: `system_prompt.txt` was not found or was empty, so the block you marked as cacheable contains no text. This usually happens when the working directory of the cron job differs from the directory you tested in.
- Solution: run `wc -c system_prompt.txt` and confirm it is not `0`. Add the guard `assert len(STABLE) > 1000` to the script, and use absolute paths in cron: `/opt/agent/system_prompt.txt`.

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

- Log line: `2 write= 0 read= 0 input= 8421`
- Cause: the prefix is not byte-identical between calls. The three usual culprits are a generated timestamp placed above the frozen block, tool schemas built from a Python `dict` whose key order changes at runtime, and a prefix below the provider's minimum cacheable length.
- Solution: move the timestamp and any session ID below the cached block, and serialize the schemas deterministically:

```bash
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**

- Log line: `write= 8421 read= 0` after a six-minute idle gap
- Cause: the default ephemeral TTL expired while the agent was waiting for a human. On OpenAI the retention window is provider-managed, so the same symptom appears without any configuration change on your side.
- Solution: on Claude, switch that prefix to `"ttl": "1h"` with the beta header and re-run the probe; then trigger the pause again and confirm `read=` is non-zero. On OpenAI, accept the write on resume or keep the agent warm with a short request every few minutes. Compare the two costs against your own pause pattern before choosing.

## 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.

- [ ] `system_prompt.txt` is frozen and hashed in the deploy script
- [ ] `cache_probe.py` shows `read=` non-zero on the second call
- [ ] TTL or keepalive interval matches the longest real pause in your logs
- [ ] Cached-input pricing re-checked on the provider page before go-live
