# Prompt caching in practice: the obvious cut that would have saved 4%

> The goal was to cut 20% of an AI agent's cost with a prompt router. Measuring showed about 4%, because 63% of the input already came from the cache, billed at 10% of the price.

Rodrigo Lucas · 2026-11-11 · https://rodrigolucas.dev/en/blog/prompt-caching-in-practice

---
The goal was to cut 20% of the cost of an AI agent I built. The plan had an entire stage for it, a prompt router with an intent classifier in front and smaller specialist prompts behind it. I measured before building. The math showed the cut would save about 4%, and the router was never built.

The idea started the usual way. The bill grows, someone opens the system prompt, sees thousands of tokens of instructions and tool definitions, and concludes that the way forward is to cut. But the provider bills at a 90% discount or more precisely the part of the prompt that repeats on every call, and trimming the fixed prompt was aiming at the part that was already cheap. That same week I found the opposite mistake in the same agent's spending cap, which charged the cache as new tokens and estimated twice what I was actually paying. Both mistakes came from not looking at how much of the input was already coming from the cache.

By **prefix** I mean the beginning of the request that repeats from one call to the next, that is, the tool definitions, the system prompt and, in a conversation, the previous messages. The providers' prompt cache works on that prefix, and only on it.

## What the cache stores

When a model processes a request, it computes internal states for each input token, in order. If the next request starts with exactly the same tokens, those states can be reused, and the provider charges less for the work it did not have to redo.

In practice, the word that matters is "exactly". Reuse holds from the first token up to the first different token, and from there on everything is recomputed and billed at full price. The three big providers document the same rule in different words.

- Anthropic builds the prefix in the order `tools`, `system`, `messages`, and says a change at one level invalidates that level and all the following ones. Changing a tool definition invalidates everything, and changing `tool_choice` invalidates only the messages. The segments must be 100% identical.
- OpenAI says reuse requires the whole rendered prefix, up to the breakpoint, to match, and recommends putting stable instructions and reference material first, and dynamic content (such as timestamps or user text) at the end.
- Google recommends, for Gemini, putting large and common content at the beginning of the prompt and sending requests with a similar prefix within a short time window.

All three also have a minimum size, and below it nothing is cached, with no error at all. At Anthropic it ranges from 512 to 4,096 tokens depending on the model, at OpenAI it is 1,024 visible tokens from GPT-5.6 on, and on Gemini it is 2,048 tokens on 2.5 Flash and 4,096 on the newer models. A system prompt that is too short never enters the cache, and the telemetry shows zero without complaining.

And all three bill cache reads at a large discount. The values below are from November 2026, according to the official pricing pages.

| Provider | Cache read (fraction of the input price) | Cache write | Activation |
|---|---|---|---|
| Anthropic | 0.1× on most models (0.05× or 0.025× on some) | 1.25× (5 min) or 2× (1 h) | explicit or automatic `cache_control` |
| OpenAI | 0.1× on GPT-5.6 and GPT-5.5 | 1.25× (30 min) or 2.5× (12 h) on GPT-5.6 | automatic |
| Google Gemini | 0.1× on 2.5 Flash and 3.x Flash; 0.05× on Gemini 4 | not listed on the pricing page | implicit, on by default from 2.5 on |

The table shows that a token that comes from the cache costs a tenth (or less) of a new token. Any cost decision that treats the two as equal is looking at the wrong number.

## The math I almost did not do

In the router's case, each agent step sent about 7.7 thousand input tokens, and about 4 thousand of those were the fixed prefix, which is the system prompt plus the tool definitions. The idea was to classify the message's intent and send only the relevant instructions and tools, cutting something like 1.6 thousand tokens from that prefix.

The naive reasoning said that 1.6 thousand out of 7.7 thousand is about 20% of the input, so about 20% savings, which matched the goal and was enough to start building.

But the telemetry showed that **63% of each step's input already came from Gemini's implicit cache**, billed at 10% of the price. And the fixed prefix was precisely the part that was in the cache, because it is the part that repeats identically on every call. In units of "price of one new token", the input of one step cost something like this.

```python
input_tokens = 7_700
cached = 0.63 * input_tokens         # ~4,850 tokens at 10%
new = input_tokens - cached          # ~2,850 tokens at 100%

input_cost = cached * 0.10 + new * 1.0   # ~3,335 units
cut = 1_600 * 0.10                        # the cut comes out of the cached part: 160 units

print(cut / input_cost)              # ~0.048 of the input
```

That is less than 5% of the input cost and, adding output to the account, about 4% of the real cost per step. To get that, the router would add one more model call to every message (with its own cost and latency) and a new piece that can misclassify and send the question to the wrong specialist. For 4% it was not worth it, and the idea came out of the plan.

What bothers me about this story is that the decision was almost made by looking at the token count, which is the easiest metric to see and the least related to cost. The number that mattered, how many of those tokens already came from the cache, was in the response of every call, in a field nobody read.

## Separating cache from new input in the math

I found the opposite mistake in a more embarrassing way. The same agent had a monthly spending cap, which is a cost estimate per call, summed over the month, that blocks the chat when it passes the limit. The formula took the total input tokens and multiplied by the input price.

The problem is that the total input includes the tokens read from the cache, so the formula charged as new tokens what the provider billed at 10%. The estimate came out at about 2× the real spend, and the same evaluation run that the old formula priced at R$ 5.41 cost R$ 2.78 when recalculated with the discount. In practice, the cap would have blocked the chat with half the budget still available.

The fix is small.

```typescript
type Usage = { input: number; cacheRead: number; output: number };

function cost(usage: Usage, price: { input: number; cache: number; output: number }) {
  const fresh = usage.input - usage.cacheRead;
  return (
    fresh * price.input +
    usage.cacheRead * price.cache +
    usage.output * price.output
  ) / 1_000_000;
}
```

What makes this formula right or wrong is knowing whether your "total input" already contains the cache tokens or not, and on that the providers do not agree.

- At OpenAI, `input_tokens` includes everything. The documentation example shows `input_tokens: 12000`, `cached_tokens: 4000` and `cache_write_tokens: 7000`, and says only 1,000 are ordinary input (`12000 - 4000 - 7000`).
- At Anthropic it is the opposite, and `input_tokens` does not include cache tokens, only those after the last breakpoint. The total is `cache_read_input_tokens + cache_creation_input_tokens + input_tokens`.
- In Vercel's AI SDK, which I used on top of Gemini, `inputTokens` is described as the total number of input tokens, with a breakdown in `inputTokenDetails` (`noCacheTokens`, `cacheReadTokens`, `cacheWriteTokens`).

In other words, the same formula, copied from one provider to another, errs upward in one case and downward in the other. If you subtract the cache from an `input_tokens` that does not contain it, the cost comes out negative or too small, and if you do not subtract it from one that does, it comes out double. The only defense is a test with numbers from a real response from your provider, written before you trust the total.

There is one more consequence that catches many people. When you change the formula, recompute the old baseline with it before comparing, otherwise the "savings" that show up in the chart are just the math being fixed, with nothing you actually optimized.

## How to keep the prefix stable

If the discount only applies to the identical prefix, the engineering work is making sure it stays identical. In an assistant with a prefix of about 10 thousand tokens that I built earlier, this became three rules for assembling the prompt.

1. Tools in deterministic order. If the tool catalog is built from a map or a dynamic registry, the order can change from one request to the next with no real change. For the model it is the same catalog, but for the cache it is another prefix, and sorting by name solves it.
2. What changes rarely stays in the middle, and what always changes goes to the end. A per-user memory changes rarely, so it goes after the fixed instructions. Today's date changes every day (and a time, on every call), so it goes at the end, after everything that can be cached.
3. Nothing volatile at the start. A "Today is November 11, 14:32" on the first line of the system prompt invalidates the whole cache every minute.

In code, the assembly looks roughly like this.

```python
def build_prompt(user, registered_tools, now):
    tools = sorted(registered_tools, key=lambda t: t.name)  # stable order

    system = [
        FIXED_INSTRUCTIONS,             # same for everyone, always
        user_memory(user),              # changes rarely
        f"Today's date: {now:%Y-%m-%d}",  # changes every day, so it goes last
    ]
    return tools, "\n\n".join(system)
```

The error this structure prevents is silent, because nothing breaks when the prefix stops matching. The answer is still right, latency goes up a little and the bill grows with no alert. The only way to see it is to track the fraction of tokens read from the cache over time, and if it drops suddenly after a deploy, someone put something volatile at the start.

### The price of changing the tool catalog

The same assistant had a mechanism to unlock tools depending on context, and in certain turns a different subset of tools was available. It makes sense for safety and focus, but it has a cost that only shows up in the cache math. Changing the catalog changes the start of the prefix, and in those turns the cache breaks entirely. Anthropic's documentation says explicitly that changing tool definitions invalidates tools, system and messages.

OpenAI documents a way out, which is to keep the definitions, ordering and schemas and use `tool_choice` to restrict what the model can call, instead of removing tools. At Anthropic, changing `tool_choice` also costs, but it only invalidates the messages, and the tools and system prefix still holds. In both cases the principle is the same, **restricting is cheaper than removing**.

## When the cache costs more

The cache has a cost of its own, and two details change the math, the **write cost** and the **lifetime**.

At Anthropic, writing to the cache costs 1.25× the input price with a 5-minute lifetime, or 2× with 1 hour. On GPT-5.6, OpenAI started listing writes at 1.25× (30 minutes) or 2.5× (12 hours). If a prefix is written and never read again within its lifetime, you paid more than you would have without a cache. In an agent with sparse traffic (one message every half hour), the short cache expires between calls, and every message pays the write again.

As for the lifetime, at Anthropic the 5-minute cache is refreshed at no cost on each use, and the time is counted from the start of the request. At OpenAI, models before GPT-5.6 keep the in-memory cache for around 5 to 10 minutes of inactivity, up to one hour. On GPT-5.6 the default is 30 minutes, with a 12-hour option. Google does not document a lifetime for the implicit cache and only recommends sending the similar prefix within a short window.

For agent loops on Gemini 4 there is one more rule. The whole previous request only enters the cache if the new one adds at least 2,050 tokens, and smaller additions reprocess the last 2,050 tokens at full price. In an agent that takes many short steps (a tool call, a small result, another call), part of the input that looked cached is not.

Knowing that the cache is on tells you little, so it is better to ask what fraction of the input is read from the cache and how much you are paying in writes. Both answers are in the usage object of every response.

## When trimming the prompt still pays off

The 4% belongs to this agent, which had 63% of the input cached and a cut that came entirely out of the cached part, and that is why the cut barely changed anything. In an agent with a short prefix, below the cacheable minimum, or with traffic so sparse that the cache expires between calls, trimming the prompt can save for real. Measuring first does not forbid cutting, it only shows whether the cut hits the expensive part.

There are also other reasons for a smaller prompt. Fewer instructions can mean less model confusion, and a router can improve quality even without saving money. But then the success criterion is different and has to be written as such, without being sold as savings.

Stabilizing the prefix also constrains the design. Putting the date at the end, keeping tools that will not be used in the catalog and avoiding personalization at the start of the prompt are choices that sometimes fight with what would be most natural to write. It is worth accepting the constraint where the prefix is large and repeated, and ignoring it where it is not.

Finally, vendor prices change. The numbers in the table are from November 2026, and some already have a set date to change. The shape of the math (cache at a fraction of the price, writes at a surcharge) is more stable than the numbers. Usage fields also change name and meaning across providers and versions, and what protects the formula is the test with a real response, because reading the documentation once is not enough.

## Where I would start

If I picked up another agent with a growing bill today, the first step would be a chart of the fraction of input read from the cache per day, next to the deploy dates. The field comes in every response (`cache_read_input_tokens`, `cached_tokens` or `cacheReadTokens`, depending on the provider) and costs one log line. With it you can tell in minutes whether a prompt cut targets the expensive part or the cheap one, and a drop after a deploy shows up as the cost bug it is, even with no test broken. The cost formula comes right after, with a test built from a real response from the provider, and with the old baseline recomputed before any comparison.

What this case does not answer is how much the Gemini 4 rule of 2,050 tokens eats from the cache in an agent loop with short steps. I have not measured it yet, and it is the kind of number that only shows up by running it.

## References

Pages accessed in November 2026.

- [Anthropic: Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
- [OpenAI: Prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching)
- [OpenAI: Pricing](https://developers.openai.com/api/docs/pricing)
- [Google: Gemini API, Context caching](https://aistudio.google.com/docs/caching)
- [Google: Gemini API, Pricing](https://aistudio.google.com/docs/pricing)
- [Vercel AI SDK: generateText (usage object)](https://ai-sdk.dev/docs/reference/ai-sdk-core/generate-text)
