Ong Jun Xiong — Notes

Working notes on software, AI and building a career around both.

· 9 min read

Why the same prompt can cost more on the next request

How prefix caching actually bills, what silently breaks it, and a worked cost example across Claude Code, Codex, Cursor and the raw API.

AI systems#prompt-caching#cost#agents#inference

A changing Generated at {timestamp} line near the top of a system prompt can stop the rest of it from hitting the cache. The answers may look just as good, so a working application can hide a much more expensive request.

When I look at caching, I start with what changes between turns and where that change sits in the prompt.

The prefix has to match

A transformer's prefill computes key/value tensors for every input token. Prompt caching stores those tensors and reuses them when a new request starts with byte-identical text. OpenAI's cookbook puts the mechanism plainly: the model "reuses the cached tensors and only computes attention for the new tokens" (Prompt Caching 201).

The consequence is that a cache hit needs an exact prefix match, not a similar one, and not a fuzzy one. Change something near the start of a long prompt and the text after that change loses its matching prefix. There is no per-file, per-section, or per-document caching underneath. Anthropic's Claude Code docs say it in one sentence: "The match is exact, so a change anywhere in the prefix recomputes everything after it. There is no per-file or per-segment caching" (code.claude.com).

CACHE HIT · PREFIX BYTE-IDENTICAL1 · System 0.1x2 · Context 0.1x3 · History 0.1x4 · New turn writeCACHE MISS · ONE BYTE EDITED IN LAYER 21 · System 0.1x2 · Context full price3 · History full price4 · New turn full price
CACHE HIT · PREFIX BYTE-IDENTICAL1 · System 0.1x2 · Context 0.1x3 · History 0.1x4 · New turn writeCACHE MISS · ONE BYTE EDITED IN LAYER 21 · System 0.1x2 · Context full price3 · History full price4 · New turn full price
The API matches from token 0. An exact prefix hit is read at a tenth of the input price or less; an edit anywhere forces everything below it to be recomputed at full price.

That is why the ordering advice is not a style preference. Content must be laid out in descending order of stability:

  1. System prompt and tool definitions (change on deploy)
  2. Retrieved documents, repo context, few-shot examples (change per session)
  3. Conversation history (changes per turn)
  4. The user's actual question (changes per request)

Anything volatile placed above something stable destroys the cache for the stable thing. A timestamp that changes on every request can prevent reuse of everything after it.

Three vendors, three interfaces to the same idea

All three major APIs do prefix caching. They disagree about who places the breakpoint and who pays for the write. Checked 2026-10-20.

Anthropic OpenAI Google (Gemini)
How it turns on Explicit cache_control breakpoints, or one top-level auto breakpoint Implicit by default; explicit prompt_cache_breakpoint on GPT-5.6+ Implicit by default on 2.5+; explicit cache objects available (not on Gemini 4 Argon)
Breakpoints Max 4 per request Auto at end of latest eligible message (5.6+) n/a for implicit
Minimum prefix 512 tok (Opus and Sonnet 5.5, Opus 5, Fable 5 and 5.1), 1,024 (Opus 4.8, Sonnet 5), up to 4,096 (Opus 4.6, Haiku 4.5) 1,024 visible input tokens (GPT-5.6+); varies by request settings on earlier models 2,048 (Gemini 2.5), 4,096 (3.x and 4 Argon)
Read price 0.1x base input (0.05x on Opus and Sonnet 5.5; 0.025x on Fable and Mythos 5.1) 0.1x base input on GPT-5.6+ (0.05x on GPT-6.1 Sol) 0.1x base input (0.05x on Gemini 4 Argon)
Write price 1.25x (5m TTL), 2x (1h TTL) 1.25x (GPT-5.6+); no write charge on earlier models No write charge; hourly storage fee
TTL 5 min default, 1 hour opt-in 30 min default on 5.6+; in_memory (~5-10 min) or 24h on earlier Implicit is opportunistic; explicit caches have a TTL

Sources: Anthropic pricing, Anthropic prompt caching, OpenAI prompt caching, Gemini caching, Gemini pricing.

0.00.10.20.30.40.50.60.70.80.91.01.11.21.31.41.51.61.71.81.92.0multiple of base input rateCache write, 1h TTLCache write, short TTLCache read2.0x1.25x1.25x0.1x0.1x0.1xAnthropicGoogleOpenAIWhat a cached input token costs, as a multiple of the base rateStandard rates. Dashed line is uncached input at 1.0x. Google has no write bar: it charges no write premium and billshourly storage instead. OpenAI models before GPT-5.6 also had no write charge.
0.00.10.20.30.40.50.60.70.80.91.01.11.21.31.41.51.61.71.81.92.0multiple of base input rateCache write, 1h TTLCache write, short TTLCache read2.0x1.25x1.25x0.1x0.1x0.1xAnthropicGoogleOpenAIWhat a cached input token costs, as a multiple of the base rateStandard rates. Dashed line is uncached input at 1.0x. Google has no write bar: it charges no write premium and billshourly storage instead. OpenAI models before GPT-5.6 also had no write charge.
0.01.02.00.51.5multiple of base input rate2.0x1.25x1.25x0.1x0.1x0.1xCache write, 1h TTLCache write, short TTLCache write, short TTLCache readCache readCache readAnthropicGoogleOpenAIWhat a cached input token costs,as a multiple of the base rateStandard rates. Dashed line is uncached input at1.0x. Google has no write bar: it charges nowrite premium and bills hourly storage instead.OpenAI models before GPT-5.6 also had no writecharge.
0.01.02.00.51.5multiple of base input rate2.0x1.25x1.25x0.1x0.1x0.1xCache write, 1h TTLCache write, short TTLCache write, short TTLCache readCache readCache readAnthropicGoogleOpenAIWhat a cached input token costs,as a multiple of the base rateStandard rates. Dashed line is uncached input at1.0x. Google has no write bar: it charges nowrite premium and bills hourly storage instead.OpenAI models before GPT-5.6 also had no writecharge.
Every provider's standard read rate is a tenth of base input; the newest flagships read cheaper still (0.05x on Claude Opus and Sonnet 5.5, GPT-6.1 Sol and Gemini 4 Argon; 0.025x on Claude Fable and Mythos 5.1). They disagree only about what a write costs.Sources: Anthropic pricing and prompt-caching docs; OpenAI prompt caching (GPT-5.6+); Gemini caching and pricing. Checked 2026-10-20.

Two differences actually change how you write code.

Google bills storage, not writes. Gemini's context caching charges the cached rate at 10% of input plus a per-hour storage fee, e.g. $1.00 per million tokens per hour on Gemini 3.5 Flash-Lite as of 2026-10-20. That inverts the calculus: on Anthropic and OpenAI you worry about paying the write premium too often, on Google you worry about paying rent on a cache nobody reads.

OpenAI has a routing problem the others don't expose. On models before GPT-5.6, cache hits require your request to land on a machine that holds the prefix, so OpenAI gives you prompt_cache_key to pin related requests together. Their cookbook reports one customer going from 60% to 87% hit rate by setting it, and warns that a single prefix+key combination saturates at roughly 15 requests per minute before traffic spills to other machines and misses. For high-QPS traffic, I would check routing and hit rates before changing the prompt. From GPT-5.6, OpenAI routes cache traffic itself and says the key is no longer needed for hits (checked 2026-10-20), so this now applies to the older models.

The arithmetic

Take a plausible agent loop on Claude Opus 5 at the published rates ($5/MTok input, $0.50/MTok cache read, $6.25/MTok 5-minute cache write, $25/MTok output — pricing page, checked 2026-10-20):

  • 30,000-token stable prefix: system prompt, tool definitions, project context
  • 20 turns, each appending ~2,000 tokens of tool results and user input
  • 500 output tokens per turn

Every turn resends everything before it, so total input across the session is 980,000 tokens either way. What differs is the rate each token is billed at.

Tokens Rate Cost
No caching 980,000 uncached $5.00 $4.90
Cached — reads 912,000 $0.50 $0.456
Cached — writes 68,000 $6.25 $0.425
Cached total $0.88

That's 5.6x on input for a session that ran identical text through the model. Output cost ($0.25) is unchanged by caching, so the session total moves from $5.15 to $1.13.

The 5.6x isn't the ceiling. Because Opus 5 reads bill at exactly one tenth of base input, the asymptote is 10x, approached as the stable prefix grows relative to per-turn additions. A 100-turn session against a 100K-token repo context gets much closer to it than this example does. On Claude Opus 5.5, which reads at 0.05x ($4 input, $0.20 read, $5 write as of 2026-10-20), the same session's input falls from $3.92 to $0.52, 7.5x, and the asymptote is 20x. I would track both the share of input served from cache and what those reads cost. The worked example shows why those percentages can be very different.

A model switch on turn 11. Same session, but you switch models on turn 11. The turn-11 request has 50,000 tokens of history and none of it hits, so it writes 50,000 tokens at $6.25/MTok = $0.31 for one turn, against $0.037 for a healthy turn 11. That single keystroke costs 8.5x a normal turn, and the session's input bill rises from $0.88 to $1.16, up 31%.

0.01.02.03.04.05.00.51.52.53.54.5input cost, USDNo cachingCached, one model switchCached, prefix intact$4.90$1.16$0.88Input cost for the same 980,000-token modelled session$5 input, $0.50 cache read, $6.25 5-minute cache write per MTok. The model switch happens at turn 11. Modelled tokencounts, not a measurement. Output cost excluded.
0.01.02.03.04.05.00.51.52.53.54.5input cost, USDNo cachingCached, one model switchCached, prefix intact$4.90$1.16$0.88Input cost for the same 980,000-token modelled session$5 input, $0.50 cache read, $6.25 5-minute cache write per MTok. The model switch happens at turn 11. Modelled tokencounts, not a measurement. Output cost excluded.
012345input cost, USD$4.90$1.16$0.88No cachingCached, one model switchCached, prefix intactInput cost for the same980,000-token modelled session$5 input, $0.50 cache read, $6.25 5-minute cachewrite per MTok. The model switch happens at turn11. Modelled token counts, not a measurement.Output cost excluded.
012345input cost, USD$4.90$1.16$0.88No cachingCached, one model switchCached, prefix intactInput cost for the same980,000-token modelled session$5 input, $0.50 cache read, $6.25 5-minute cachewrite per MTok. The model switch happens at turn11. Modelled token counts, not a measurement.Output cost excluded.
Caching cuts input cost 5.6x on this workload. One model switch mid-session claws back a third of the saving.Source: my arithmetic over Anthropic's published Claude Opus 5 rates, checked 2026-10-20.

(These are arithmetic on published prices, not measurements from my own logs. The token counts are a modelled workload.)

What each harness does with your history

Every harness resends the full conversation on every turn. They differ in how carefully they preserve the prefix while doing it.

Claude Code is the most explicit about this, and its docs are worth reading even if you use something else. It orders each request system prompt → project context → conversation, and publishes the full list of what invalidates each layer. The non-obvious entries, as of October 2026:

  • /model changes the cache key, not the prompt text, and so does /effort on most models. Switching either re-reads the entire history with zero hits. The exception: on Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1, through an API key or a subscription, an effort change keeps the cache.
  • Editing CLAUDE.md mid-session does not invalidate the cache, because it also doesn't apply. It's loaded once at session start and takes effect on the next /clear, /compact, or restart.
  • Skills, slash commands, /recap and plan mode all append as messages, so they're cache-safe by construction.
  • /rewind truncates back to a prefix that is already cached; /compact builds a new one. Given the choice, rewind.
  • Cache scope is effectively per-machine and per-directory, because the system prompt embeds the working directory, platform and shell. Two git worktrees of the same repo do not share a cache.

TTL is configurable there via promptCacheTtl / CLAUDE_CODE_PROMPT_CACHE_TTL, and on an API key the main conversation defaults to 5 minutes rather than the 1 hour a subscription gets.

Codex CLI takes the append-only route and pins prompt_cache_key to the thread, so turns in one session route to the same cached prefix. A third-party writeup measured 80-90% hit rates and 40-55% input cost reduction across sessions, and notes that /compact resets the cache because the prefix changes. Treat those as one person's numbers, not vendor-published ones. The actionable part is verifiable from OpenAI's own docs: dynamic content in AGENTS.md (generated line counts, timestamps) sits in the prefix and breaks it, and MCP servers connecting mid-session change the tool list.

Cursor passes provider caching through and bills you for both halves. Its pricing docs show a per-model Input / Cache write / Cache read table at the provider's list rates: for Anthropic models, cache writes at 1.25x and reads at Anthropic's rate, 5% on Opus and Sonnet 5.5 as of 2026-10-20. You have far less control here: Cursor owns the system prompt, decides what rules and MCP descriptions go into the prefix, and decides when to trim context. The lever you do have is not attaching and detaching things mid-conversation.

Raw API is the only place you control all of it, and the only place you can get it badly wrong. If you're building your own loop, the two things that matter more than breakpoint placement are keeping the system prompt frozen and serializing tool definitions deterministically (sort_keys=True, no set iteration).

Changes that can break reuse

Prefix drift from injected state. A date, a user ID, a feature flag, a "you have N credits remaining" line. Anything interpolated into the system prompt is at position 0 and costs you the entire prompt. On Claude Opus 5 and Opus 4.8, and on the 5.5 models and Fable 5.1 as of October 2026, there's a clean fix: append {"role": "system", "content": "..."} to messages[] instead of editing top-level system. It sits after the cached history and invalidates nothing.

Non-deterministic serialization. json.dumps() without sort_keys, iterating a set, a library that reorders keys between versions. The prompt is logically identical and byte-different, which is the only thing the cache cares about.

Compaction and context editing. Both rewrite history, which by definition destroys the conversation-layer prefix. The turn after compaction is cheap, since the new history is short. The expensive one is compaction itself when it runs cold: Anthropic notes that a mid-session /compact reads your prefix from cache and costs a fraction of what the context size suggests, but after a break longer than the TTL there's nothing to read and the summarization request reprocesses the full history uncached.

Expiry mid-session. The TTL clock runs from the start of the request. A four-minute generation leaves about one minute of a five-minute entry. Agent loops with long tool calls or slow human review drift past the window without anyone noticing, and every re-warm is a full write.

Parallel fan-out. N identical requests fired simultaneously all miss, because an entry only becomes readable once the first response starts streaming. Send one, wait for first token, then fire the rest.

Resuming an old session after an upgrade. New harness version means a new system prompt, which means the entire resumed history sits behind a different prefix. The first turn back into a long conversation can be the most expensive request you send all week.

What I would log

Log cache_read_input_tokens and cache_creation_input_tokens on every response and alert when the ratio inverts. In a healthy loop, reads grow turn over turn and writes stay roughly the size of the last exchange. If creation is near the full conversation size on every request, something upstream is rewriting your prefix.

For a cache-eligible request, I would also check whether repeating it produces cache reads. A miss needs investigation: the prefix may have changed, or the entry may have expired or landed on another machine. Successful responses alone cannot tell you whether caching works.

If you're structuring the prefix itself, context engineering for coding agents is the other half of this problem: what goes in the window at all, before you worry about what order it's in.

Published 29 August 2026, last revised 20 October 2026. Revised in place rather than reposted — the date above is the one that matters.

Markdown source for this article: /raw/prompt-caching-across-harnesses.md