A developer adds one line to the top of the system prompt: Current time: 10:42:17. The bot now knows the date. Every test passes. Next month the input bill is 17 times bigger, and no alert fired. No request failed, and no answer changed.
This post explains why one changing line at the top of a prompt switches prompt caching off. If you are new to prompt caching, read the first post in this series first. Then it lists twelve ways teams break the cache without knowing, with a fix for each, and six myths. The last part gives a prompt layout, two tests and one metric that catch the problem before the invoice does.
The change
The support bot has a large system prompt: rules, a refund policy, product facts and a few examples. It is about 20,000 tokens. The team marks it with cache_control, so the provider caches it. Then a customer asks "can I still return this?" and the bot does not know today's date. A developer fixes that:
const system = [
{
type: "text",
text: `Current time: ${new Date().toISOString()}\n\n${SUPPORT_PROMPT}`,
cache_control: { type: "ephemeral" },
},
];The fix works. The bot now answers date questions correctly. The code review is short, because the diff is one line.
What the bill did
The bot handles 100,000 requests a day. Each request sends the 20,000-token system prompt plus about 500 tokens of new conversation. This table counts input tokens only:
| Before the change | After the change | |
|---|---|---|
| System prompt (2,000M tokens a day) | Cache read at $0.20/M: $400 | Cache write at $5/M: $10,000 |
| New conversation text (50M tokens a day) | Full price at $4/M: $200 | Full price at $4/M: $200 |
| Input cost per day | $600 | $10,200 |
The prompt changes every second, so the provider never finds a match. Each request writes a new cache entry, and no later request reads it. The team pays the 1.25x write price for nothing, every time. That is worse than no caching at all, which costs $8,000 a day for the same tokens.
Output tokens do not change. If the bot writes 300 tokens per reply, output adds $600 a day in both cases. The total bill then goes from $1,200 to $10,800 a day, which is 9x. The input part alone is 17x.
Why nothing alerted
Caching has no error state. A miss returns the same answer as a hit. The latency rises a little, but not enough to cross an alert threshold. The only signal is in the usage object of each response, and most teams do not graph it.
It is worse than that. Many dashboards graph input_tokens. When the cache breaks, that number does not move. Problem 12 below explains why.
The short version
Before a model writes its first output token, it computes keys and values (the KV cache) for every input token. Prompt caching keeps that work after a request ends and reuses it on the next request. Each token's state depends on every token before it, so the provider can reuse saved state only for an exact prefix. If byte 40 changes, every token after byte 40 must be computed again. The first post in this series, Same Prompt, Second Request, 20x Cheaper, explains this in detail, with prices and break-even tables.
The Anthropic docs say: "Cache hits require 100 percent identical prompt segments." They also give the order in which the API builds the prompt: "Cache prefixes are created in the following order: tools, system, then messages."
The parts that matter for cost
The three large providers all use prefix matching. They differ in how you switch caching on and what it costs. These are the facts this post relies on, from the Anthropic docs unless the row says otherwise:
| Item | What it means |
|---|---|
| Breakpoint | You mark a block with cache_control. The API caches the prefix up to and including that block. You can set up to 4 breakpoints, or set one top-level cache_control to let the API place it. |
| Lifetime (TTL) | 5 minutes by default. Each cache read resets the timer at no cost. A 1-hour TTL is available. |
| Write price | 1.25x the input price for a 5-minute entry. 2x for a 1-hour entry. |
| Read price | 0.1x the input price on most models. 0.05x on Claude Opus 5.5 and Sonnet 5.5. |
| Minimum size | 512 tokens on the newest Claude models. 4,096 on Opus 4.6, Opus 4.5 and Haiku 4.5. A shorter prefix does not cache, and the API returns no error. |
| Scope | "Different organizations never share caches." On the Claude API, workspaces also have separate caches. |
| OpenAI | Caching is "enabled by default for supported OpenAI models". The OpenAI docs say: "Cache reuse requires the entire rendered prefix to match." |
| Google Gemini | "Implicit caching is enabled by default on all Gemini 2.5 and newer models", says the Gemini caching docs. The minimum is 4,096 tokens on Gemini 3.x. |
So the timestamp bug is not specific to one provider. Automatic caching on OpenAI and Gemini makes it harder to see, because nobody wrote a cache_control line that a reviewer could notice.
Where the numbers are
Every Claude response has three input counters in usage:
cache_read_input_tokens: tokens the API read from the cache.cache_creation_input_tokens: tokens the API wrote to a new cache entry.input_tokens: tokens after the last breakpoint, which the API neither read nor wrote.
The total prompt size is the sum of all three. OpenAI reports cached tokens in usage.input_tokens_details.cached_tokens. Gemini reports them in usage_metadata.cached_content_token_count on generateContent.
The timestamp is the best-known case. The other eleven follow the same rule: something early in the prompt changes, or the cache never gets a chance to work.
1. A timestamp or request ID in the system prompt
What happens. The prompt starts with the current time, a request ID, a trace ID or a random nonce. Every request has a new prefix. The cache hit rate is zero.
Why. The value sits before the large, stable part of the prompt. Everything after it becomes new bytes.
Fix. Remove values that the model does not need. Request IDs belong in headers and logs, not in the prompt. If the model needs the date, put it at the end. Use the newest user message, or a mid-conversation system message on models that support one. Round it to the day. A date changes once a day, and a time to the second changes on every request.
2. JSON that serializes in a different order
What happens. The prompt includes a JSON block, for example a customer profile or a config. Two requests for the same customer produce different bytes.
Why. JSON.stringify writes keys in insertion order. Two code paths that build the same object in a different order produce different text. In Python, iterating a set of strings can give a different order in each worker process, because string hashing changes per process.
Fix. Serialize with sorted keys. Sort lists that have no meaningful order. Build prompt text from one function, not from several code paths.
tool_use blocks.3. User data in the system prompt
What happens. The system prompt starts with "You are talking to Priya, a Gold customer in Pune." Each user gets a different prefix.
Why. The cache now works per user, not across users. A user who sends one message every ten minutes never gets a hit on a 5-minute cache. Each of their requests pays the write price.
Fix. Keep the system prompt the same for every user. Send user facts after it, in the first user message or a later system message. Then all users share one cached system prompt.
4. Feature flags that edit the prompt
What happens. Code adds sections to the system prompt when a flag is on: if (flags.newRefundPolicy) system += REFUND_V2. Five independent flags give up to 32 different prompts.
Why. Each combination is a separate prefix with its own cache. Traffic splits across them, and the small groups miss the 5-minute window. An A/B test on the prompt has the same effect.
Fix. Put the sections that every user shares first, with a breakpoint after them. Put the flag-specific sections after that breakpoint. Then a flag change invalidates only the part after it.
5. A tool list that changes
What happens. The agent loads tools per user, per plan or per connected MCP server. Or it adds and removes tools during a task.
Why. Tools come first in the prompt. The Anthropic docs show that a change to tool definitions invalidates the tools, system and messages caches. That is the whole prompt. If tools arrive from several servers, their order can also depend on which server answered first.
Fix. Use one fixed tool list for a conversation, sorted by name. If some tools must not run, refuse them in your tool handler, or tell the model in a message. Do not remove them from the list.
6. Editing the conversation history
What happens. To stay under a token limit, the app drops the oldest message on every turn. Or it rewrites an old tool result to make it shorter, or deletes a reminder it inserted earlier.
Why. Each of these changes the middle of the prompt. A sliding window that drops one message per turn changes the prefix on every turn, so the history never caches.
Fix. Make the conversation append-only. When it must get shorter, compact it in one large step: replace the old part with a summary once, then append again. One miss per compaction is cheap. One miss per turn is not.
7. Switching models in the middle of a conversation
What happens. A router sends easy turns to a small model and hard turns to a large one. Or a fallback moves traffic to a second model during an outage.
Why. Each model has its own cache. The KV state of one model is useless to another model. Each switch starts cold, and each switch back starts cold again.
Fix. Route per conversation, not per turn. Before you build a router, measure one model at a lower effort setting. One model keeps one cache. When you compare costs, include the cache misses that the router causes.
8. A prompt below the minimum size
What happens. The team adds cache_control to a 3,000-token prompt and sees no change in cost.
Why. Each model has a minimum cacheable length. On Claude, it is 512 tokens on the newest models and 4,096 tokens on Opus 4.6, Opus 4.5 and Haiku 4.5. Gemini 3.x needs 4,096. A shorter prefix does not cache, and the API returns no error. The minimum also changes between models, so a model upgrade can switch caching on or off with no code change.
Fix. After every model change, check cache_creation_input_tokens on the first request. If it is zero, the prefix is too short for that model.
9. Gaps longer than the TTL
What happens. An internal tool gets one request every 10 minutes at night. Each request writes the cache, and the entry expires before the next request.
Why. The default TTL is 5 minutes. At 1.25x per write and no reads, caching costs 25% more than no caching for that traffic.
Fix. Choose the TTL from the gap between requests that share a prefix. Under 5 minutes: keep the default. Between 5 and 60 minutes: use the 1-hour TTL, which costs 2x to write but survives the gap. Two or more reads in the hour pay for it. Over an hour: no TTL helps. Accept the miss or remove the breakpoint.
10. The same traffic split across workspaces
What happens. Each team or region uses its own API key in its own workspace. All of them send the same system prompt.
Why. On the Claude API, "caches are also isolated between workspaces." Four workspaces means four caches, each with a quarter of the traffic. Low-traffic workspaces miss the 5-minute window more often.
Fix. Send traffic that shares a prompt through one workspace, and track the cost per team with your own tags. Before you blame the prompt for a low hit rate, check which workspace each request used.
11. A breakpoint on content that never repeats
What happens. A classifier sends shared instructions followed by one unique document per request. The team turns on automatic caching. The bill goes up.
Why. Automatic caching places the breakpoint on the last cacheable block. Here, that block is the unique document. Each request writes a new entry at 1.25x, and no request ever reads one. In a chat, the next turn reads the entry. In one-shot requests, nothing does.
Fix. Put an explicit breakpoint at the end of the shared instructions, and none on the document. The sign of this problem is cache_creation_input_tokens above zero on every request while cache_read_input_tokens never covers the shared part.
12. A dashboard that watches the wrong number
What happens. The team graphs input_tokens per request. After the timestamp change, the graph does not move. The bill rises by 17x.
Why. input_tokens counts only the tokens after the last breakpoint. When the cache breaks, the system prompt tokens move from cache_read_input_tokens to cache_creation_input_tokens. They never appear in input_tokens. The graph looks healthy because it measures the wrong thing.
Fix. Graph the cache hit rate, defined below in Part 5, and the sum of all three counters. Alert when the hit rate drops.
Myth: "We turned caching on, so we are cached."
Reality. Turning it on is a request, not a result. Problems 1 to 11 all keep the setting on and the hit rate at zero. The only proof is cache_read_input_tokens above zero on real traffic.
Myth: "Any change to the prompt breaks the whole cache."
Reality. A change invalidates the cache only from that point onward. A new user message at the end costs nothing extra for the system prompt before it. That is why the fix for a timestamp is to move it, not to delete caching.
Myth: "The 1-hour TTL is always safer."
Reality. The 1-hour write costs 2x, compared with 1.25x for 5 minutes. A read resets the timer on both. With steady traffic every few seconds, a 5-minute entry stays warm all day, and the 1-hour TTL only doubles the write price.
Myth: "Caching only saves money."
Reality. It also cuts processing time, because the provider skips work it already did. On the Claude API, cache reads do not count against input-token rate limits on most models. A broken cache can show up first as 429 errors, not as a bill.
Myth: "Our provider caches automatically, so this does not apply to us."
Reality. OpenAI and Gemini cache automatically, but both match prefixes. The OpenAI docs say to put timestamps and user-specific content "at the end rather than the beginning." The Gemini docs say to "keep static fields at the top and volatile fields at the end." Automatic caching does not protect a prompt with a timestamp at the top.
Myth: "A cache miss is a performance problem, so the on-call team will see it."
Reality. A miss returns a correct answer with HTTP 200. On a long prompt, latency rises somewhat, but usually inside normal variation. Finance often sees it before engineering does.
Order the prompt by how often each part changes
All twelve problems have the same cure: the parts that change least go first, and the parts that change most go last. Put a breakpoint at each place where the rate of change goes up.
Here is the support bot again. The system prompt has no dynamic values. The date goes into the newest user message:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// Built once at startup. No dates, no user data, no flags.
const SYSTEM: Anthropic.TextBlockParam[] = [
{ type: "text", text: SUPPORT_PROMPT, cache_control: { type: "ephemeral" } },
];
// Tools in a fixed order, so the bytes never change.
const TOOLS = [...supportTools].sort((a, b) => a.name.localeCompare(b.name));
export async function reply(history: Anthropic.MessageParam[], userText: string) {
const today = new Date().toISOString().slice(0, 10); // "2026-12-01", changes once a day
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
tools: TOOLS,
system: SYSTEM,
cache_control: { type: "ephemeral" }, // automatic breakpoint on the history
messages: [
...history, // append only: never edit or drop old turns here
{
role: "user",
content: [
{ type: "text", text: `Today's date: ${today}` },
{ type: "text", text: userText },
],
},
],
});
recordCacheUsage(response.usage);
return response;
}The date is still in the prompt, so the model still answers date questions. Each earlier turn keeps the date from the day the user sent it. So the history does not change, and it stays cached.
Test 1: render the prompt twice and compare the bytes
This test costs nothing and makes no API calls. It builds the request twice, with the clock moved forward and the input objects built in a different key order. The cached part must be identical:
import { test } from "node:test";
import assert from "node:assert/strict";
test("tools and system prompt are byte-stable", () => {
const a = buildRequest(sampleUser, { now: new Date("2026-12-01T10:00:00Z") });
const b = buildRequest(reorderKeys(sampleUser), { now: new Date("2026-12-01T10:07:31Z") });
assert.equal(
JSON.stringify({ tools: a.tools, system: a.system }),
JSON.stringify({ tools: b.tools, system: b.system }),
);
});This catches problems 1 to 5 at review time. The timestamp change in Part 1 fails this test on the first run.
Test 2: a live canary that reads the cache
Test 1 cannot see problems in the API, such as a prefix below the minimum size. A small scheduled check can. It sends the same request twice and checks that the second one reads from the cache:
const first = await client.messages.create(buildRequest(sampleUser));
const second = await client.messages.create(buildRequest(sampleUser));
if (second.usage.cache_read_input_tokens === 0) {
throw new Error(
`No cache read. created=${second.usage.cache_creation_input_tokens} ` +
`input=${second.usage.input_tokens}`,
);
}This test calls the real API, so it costs money. Run it after each deploy and after each model change, not on every commit. Use a short max_tokens, because the test needs only the usage object.
The metric: cache hit rate
Compute it from each response and graph it next to cost:
function recordCacheUsage(u: Anthropic.Usage) {
const read = u.cache_read_input_tokens ?? 0;
const written = u.cache_creation_input_tokens ?? 0;
const total = read + written + u.input_tokens;
metrics.histogram("llm.cache_hit_rate", total ? read / total : 0);
metrics.count("llm.input_tokens_total", total); // not just input_tokens
}A healthy chat bot with a large stable prompt has a hit rate close to the share of the prompt that is stable. Set an alert for a sudden drop, for example 20 points below the 7-day average. A drop right after a deploy points to the change that caused it.
When the hit rate drops: find the first byte that changed
Log the full rendered request for two calls that should share a prefix. Then find where they first differ:
function firstDifference(a: string, b: string): string {
const n = Math.min(a.length, b.length);
let i = 0;
while (i < n && a[i] === b[i]) i++;
if (i === n && a.length === b.length) return "identical";
return `differs at ${i}:\n A: …${a.slice(Math.max(0, i - 40), i + 40)}\n B: …${b.slice(Math.max(0, i - 40), i + 40)}`;
}
console.log(firstDifference(JSON.stringify(reqA), JSON.stringify(reqB)));The output shows the text around the first difference. In the support bot, it prints Current time: 2026-12-01T10:42:17 on one side and a different time on the other. Every cause in Part 3 shows up this way, except for the size, TTL and workspace problems. For those, check the minimum size, the gap between requests, and the workspace of each request.
Checklist
- The system prompt has no time, date, request ID, user data or flag-specific text.
- Tools are in a fixed, sorted order, and the list does not change during a conversation.
- JSON in the prompt uses sorted keys.
- The conversation is append-only. Compaction happens in large steps, not one message per turn.
- One conversation uses one model.
- The cached prefix is above the minimum size for the model in use.
- The TTL matches the gap between requests.
- Traffic that shares a prompt uses one workspace.
- Breakpoints sit at the end of shared content, not on unique content.
- The dashboard shows the cache hit rate and the total of all three input counters.
- A byte-stability test runs in CI, and a live cache canary runs after each deploy.
The rule fits in one sentence: the cache matches the prompt only up to the first byte that changes, so put everything that changes at the end.
Sources
- Anthropic, Prompt caching: prefix order, invalidation table, TTLs, prices, minimum sizes, workspace isolation, usage fields.
- OpenAI, Prompt caching: automatic caching, exact prefix match, where to put timestamps.
- Google, Gemini context caching: implicit caching by default, field order, minimum sizes.
- Yichao "Peak" Ji, Context Engineering for AI Agents: Lessons from Building Manus (July 2025): the timestamp mistake, stable serialization, append-only context, fixed tool lists.