Context Engineering · 7 min read
Prompt caching and context layout: ordering prompts, tools and history so agents stay cheap and fast
Every major model API now caches the start of your prompt, but only if that start stays byte-for-byte identical. Here's how caching works at Anthropic, OpenAI and Google, how to lay out an agent's context to hit the cache, and the small mistakes that quietly break it.
An agent sends the model almost the same prompt again and again. The system prompt, the tool definitions and most of the conversation are identical from one step to the next. Only the newest tool result or user message is new. Without caching, you pay full price to have the model re-read all of it on every turn.
Prompt caching fixes this. The provider keeps the processed form of a prompt’s opening section, and if your next request starts with exactly the same tokens, it reuses that work. You pay less for those tokens and the response starts sooner.
There’s a catch, and it’s the whole point of this post: the cache only matches an identical prefix. One changed token near the top and everything after it is a miss. So caching is less a setting you switch on and more a way of laying out your context. (For related techniques, see our posts on context engineering and keeping tool results from flooding context.)
How the three big APIs do it
The details differ, but all three reward the same thing: a long, stable start to the prompt.
| Anthropic (Claude) | OpenAI | Google (Gemini) | |
|---|---|---|---|
| How it turns on | Explicit cache_control breakpoints, or one top-level cache_control for automatic caching |
Automatic on prompts above the minimum | Implicit caching on by default for Gemini 2.5 and newer; explicit cache objects also available |
| Minimum prompt | 512 to 4,096 tokens depending on model | 1,024 visible input tokens on current models | 2,048 to 4,096 tokens for implicit caching, depending on model |
| Lifetime | 5 minutes by default, refreshed on each hit; 1 hour optional | 30 minutes by default on current models, 12 hours optional | Explicit caches default to 1 hour, with storage billed for the time they live |
| Cost of a hit | 0.1× base input price (lower on some newer models) | 0.1× normal input rate on most current models | Reduced rate; implicit caching has no guaranteed saving |
| Cost of writing | 1.25× (5-minute) or 2× (1-hour) base input price | 1.25× (30-minute) or 2.5× (12-hour) on the Responses API | Explicit caches add storage cost |
A few points from the docs are worth knowing in more detail.
Anthropic builds the cache prefix in a fixed order: tools, then system, then messages. Each level builds on the one before, so a change to a tool definition invalidates everything after it. You can set up to four breakpoints. The cache is written only at a breakpoint, and Anthropic’s advice is to “place cache_control on the last block whose prefix is identical across the requests you want to share a cache”, not on the part that varies. When checking for a hit, the system looks back at most 20 blocks from each breakpoint. For long agent loops, automatic caching, which moves the breakpoint forward as the conversation grows, is the easier start. One more detail: a cache entry only becomes available once the first response starts, so firing many identical requests in parallel won’t share a cache.
OpenAI caches automatically, so there’s nothing to mark. Cache entries live on individual machines, and requests are routed partly by a hash of the start of the prompt. You can add a prompt_cache_key to steer similar requests to the same place. The docs suggest keeping traffic to about 15 requests per minute per key, and spreading heavier traffic across several keys with a stable mapping. A key improves the odds of a hit but doesn’t guarantee one. OpenAI’s Prompt Caching 201 cookbook (February 2026, written for models before GPT-5.6) reports one coding customer whose hit rate went from 60% to 87% after adopting cache keys. The same cookbook found cached requests were 7% faster at 1,024 tokens and 67% faster at more than 150,000 tokens, so the latency win grows with prompt length.
Google turns on implicit caching by default for Gemini 2.5 and newer models, but the docs are clear that it comes with “no cost saving guarantee”. If you need a guaranteed discount, explicit caching lets you create a cache object, set its lifetime and reference it in later requests. That version is in beta and, per the docs, not supported on the newest Gemini 4 models. Google’s tips are the same as everyone else’s: “Try putting large and common contents at the beginning of your prompt”, and send requests with similar prefixes close together in time.
A layout that caches well
The rule is simple: order your context from least to most likely to change.
- Tool definitions. Load the full set once and keep the names, descriptions, schemas and order fixed.
- System prompt. Instructions, persona and policies. No timestamps, request IDs or user names.
- Stable reference material. Product docs, a schema, few-shot examples, a long file the agent works on.
- Conversation history, append-only. Add new turns at the end. Don’t rewrite or reorder older ones.
- The new part. The latest user message, tool result, current date and per-request context.
Here’s what that looks like with the Anthropic Python SDK, with explicit breakpoints at the end of each stable layer:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model=MODEL, # whichever Claude model you run
max_tokens=1024,
tools=TOOLS, # same list, same order, every call
system=[
{"type": "text", "text": SYSTEM_PROMPT},
{
"type": "text",
"text": REFERENCE_DOCS,
"cache_control": {"type": "ephemeral"}, # breakpoint: tools + system
},
],
messages=history + [
# dynamic details go last, never in the system prompt
{"role": "user", "content": f"Today is {today}.\n\n{user_message}"}
],
)
u = response.usage
print(u.cache_creation_input_tokens, u.cache_read_input_tokens, u.input_tokens)
For a growing conversation, the simpler route is automatic caching: a single top-level cache_control field, and the system moves the breakpoint to the last cacheable block for you.
The mistakes that quietly break caching
None of these cause errors.
- A timestamp at the top. “Current time: 14:32:07” in the system prompt changes the prefix on every call. OpenAI’s cookbook calls out customers doing exactly this. Move the date to the end, and round it to the day if you can.
- Adding or removing tools mid-session. Tools come first in the prefix, so changing them invalidates the rest. OpenAI recommends keeping the tool list stable and using
tool_choiceorallowed_toolsto limit which tools can be called on a given turn. - Unstable serialisation. If your code builds JSON with keys in a different order, or templates whitespace differently, the tokens change even when the meaning doesn’t. Sort keys and keep templates fixed.
- Editing history. Truncating the oldest turns, summarising the middle, or rewriting an earlier message all change the prefix. OpenAI’s guide notes that compaction and truncation reset reuse. If you must, do it rarely and in large steps.
- Changing settings that sit in the prefix. Anthropic’s docs list changes such as
tool_choiceor adding images that invalidate the cache. OpenAI’s cookbook includes changed reasoning effort and changed output schemas in its troubleshooting list. - Prompts below the minimum. If the stable prefix is shorter than the model’s minimum, nothing is cached and no error is returned. Anthropic says this outright.
- Gaps longer than the lifetime. A five-minute cache does nothing for a user who comes back after ten. If your agent waits on humans or slow jobs, a longer lifetime may pay for itself despite the higher write price.
Measure your hit rate
Every API reports cached tokens in the usage object: cache_read_input_tokens and cache_creation_input_tokens on Anthropic, cached_tokens under the input token details on OpenAI, and the cached count in usage_metadata on Gemini. Log them on every call and track one number:
hit_rate = cached_tokens / total_input_tokens # per request, then averaged per session
If both the write and read counts are zero on Anthropic, the docs say the prompt wasn’t cached at all. A sudden drop in hit rate after a deploy almost always means something near the top of the prompt started changing.
Trade-offs
- Writes cost extra. On Anthropic and OpenAI, the first write costs more than a normal request. A prefix that’s used once is cheaper uncached. Caching pays when the same prefix is reused within its lifetime.
- Layout constrains design. Keeping tools fixed and history append-only rules out some tricks, such as loading tools dynamically per step or aggressively rewriting history. You may need to weigh cache savings against a smaller, more focused context.
- Hits aren’t guaranteed. OpenAI and Gemini’s implicit caching are best-effort, and routing or load can cause misses. Don’t build a budget that assumes 100%.
- Providers differ. Minimums, lifetimes and prices vary by provider and model, and they change. Check each provider’s current docs rather than assuming one set of numbers.
Where to start
- Log cache usage today. Add the cached-token fields to your traces and work out your current hit rate before changing anything.
- Find what varies at the top. Diff two consecutive prompts from the same session. Anything that changes before the newest turn is a cache-buster.
- Reorder into tools, system, stable reference, history, then new content. Move dates and IDs to the end.
- Freeze tools and serialisation. One fixed tool list, sorted JSON keys, fixed templates.
- Turn on explicit or automatic caching where your provider needs it, and pick a lifetime that matches how long your users and jobs actually pause.
- Re-check the hit rate and set an alert for when it drops.