Prompt caching lets an LLM provider reuse the already-processed prefix of your prompt (system instructions, tool definitions, long documents, earlier conversation turns), so repeated requests cost less and return their first token sooner. OpenAI and Google cache automatically once a prompt passes a minimum length; Anthropic caches when you mark the prompt with cache_control. On every provider, cached input tokens are billed at a small fraction of the normal input price. The catch is the same everywhere: the prefix must match byte for byte, so prompt structure decides whether you save money or not.
This guide compares how caching works on the Anthropic, OpenAI, and Gemini APIs as documented in November 2026, with runnable Python for each, the usage fields that prove a cache hit, and the mistakes that silently break it.
How prompt caching works
Before generating output, a transformer model computes internal key/value (KV) state for every input token. OpenAI's caching guide puts it plainly: caching reuses the KV state for a shared prompt prefix; it stores the computed tensors, not your text.
Three consequences follow, and they apply to all three providers:
- Only prefixes are cached. A cache entry covers everything from the start of the prompt up to a breakpoint. Change one byte early and every entry after it misses.
- Order matters. Anthropic renders requests as
tools→system→messages, and its docs note that changing tool definitions invalidates the entire cache. Stable content must come first. - There is a minimum size. Prompts shorter than the provider's threshold are processed normally, with no error.
Provider comparison at a glance
| Anthropic (Claude) | OpenAI | Google Gemini | |
|---|---|---|---|
| How it is enabled | Opt-in: cache_control on a block, or one top-level cache_control for automatic placement |
Automatic; explicit breakpoints available on GPT-5.6 and later | Implicit caching automatic on Gemini 2.5 and newer; explicit cache objects on Gemini 3.x and 2.5 only |
| Minimum cacheable prefix | 512 tokens on current models (Opus 5.5, Sonnet 5.5, Haiku 5.5); up to 4,096 on some older models | 1,024 tokens on GPT-5.6 and later | 4,096 tokens on Gemini 4, 3.8 Flash, 3.6 Flash, 3.1 Pro Preview; 2,048 on Gemini 2.5 |
| Lifetime | 5 minutes default, refreshed free on each hit; optional 1 hour | 30 minutes default; optional 12 hours (Responses API) on GPT-5.6+ | Implicit: managed by Google; explicit: TTL you set, default 1 hour |
| Write premium | 1.25x input (5 min), 2x (1 hour) | 1.25x (30 min), 2.5x (12 hours) on GPT-5.6+ | Explicit caches add hourly storage charges |
| Cache-read price | 0.1x input; 0.05x on Opus 5.5 and Sonnet 5.5 | 0.1x input; 0.05x on GPT-6.1 Sol and Terra | Model-specific; for example 0.05x on Gemini 4 Hydrogen, 0.1x on Gemini 3.8 Flash |
| Usage field for hits | usage.cache_read_input_tokens |
usage.input_tokens_details.cached_tokens |
usage.total_cached_tokens (Interactions API) or usage_metadata.cached_content_token_count (generateContent) |
Sources for every row are linked in the provider sections below. Prices and multipliers change; always confirm on the pricing pages before you build a budget around them.
Anthropic: explicit control with cache_control
Claude caching is opt-in, which makes it the most predictable of the three. You mark where the reusable prefix ends, and the prompt caching docs define the rest:
- Up to 4 breakpoints per request.
- A top-level
cache_controlfield turns on automatic caching: the API places the breakpoint on the last cacheable block and moves it forward as a conversation grows. It uses one of the four slots. - Default lifetime is 5 minutes, refreshed at no cost every time the entry is read.
"ttl": "1h"buys a one-hour lifetime at a higher write price. - The lifetime is measured from the start of the request, so a response that takes four minutes to stream leaves about one minute for the next request.
Anthropic pricing (per million tokens)
These are the first-party rates from the docs for the current model generation:
| Model | Base input | 5-min cache write | 1-hour cache write | Cache hit | Output |
|---|---|---|---|---|---|
| Claude Opus 5.5 | $4 | $5 | $8 | $0.20 | $20 |
| Claude Sonnet 5.5 | $2 | $2.50 | $4 | $0.10 | $10 |
| Claude Haiku 5.5 (prompts up to 100K tokens) | $0.10 | $0.125 | $0.20 | $0.01 | $0.50 |
Opus 5.5 and Sonnet 5.5 cache hits are priced at 0.05x of base input; other models use 0.1x.
Python example
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
with open("handbook.md", encoding="utf-8") as f:
HANDBOOK = f.read() # large, stable reference text
def ask(question: str) -> str:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
system=[
{"type": "text", "text": "Answer questions using only the employee handbook below."},
{
"type": "text",
"text": HANDBOOK,
"cache_control": {"type": "ephemeral"}, # cache everything up to here
},
],
messages=[{"role": "user", "content": question}],
)
u = response.usage
print(
f"cache write={u.cache_creation_input_tokens} "
f"cache read={u.cache_read_input_tokens} "
f"uncached={u.input_tokens}"
)
return "".join(b.text for b in response.content if b.type == "text")
print(ask("How many vacation days do new hires get?"))
print(ask("What is the remote work policy?")) # should report a cache read
On the first call, cache_creation_input_tokens should be roughly the size of the system prompt. On the second call within five minutes, those tokens move to cache_read_input_tokens. The docs give the identity total input = cache_read_input_tokens + cache_creation_input_tokens + input_tokens.
For multi-turn chat, the simplest option is the top-level form: add cache_control={"type": "ephemeral"} as a keyword argument to messages.create() and the API keeps the breakpoint on the latest turn for you. Use explicit block-level markers when the end of your prompt is unique per request (a one-off question after shared context); otherwise the automatic breakpoint lands after the unique part, and you pay the write premium on content that is never read back.
What breaks a Claude cache
The docs list invalidators by level. Changing tool definitions invalidates everything. Changing tool_choice, adding or removing images, or changing thinking parameters invalidates the message-level cache. Toggling web search, citations, or the speed setting invalidates system and message caches. Caches are also isolated per workspace on the Claude API, so the same prompt sent from two workspaces writes two entries.
OpenAI: automatic, with explicit breakpoints on newer models
On OpenAI, the prompt caching guide says caching "is enabled by default for supported OpenAI models." You do not add anything to get basic hits. What you control depends on the model generation:
- GPT-5.6 and later: 1,024-token minimum. By default OpenAI places one implicit breakpoint at the end of the latest eligible message. You can add explicit breakpoints with a
prompt_cache_breakpointfield on content blocks, setprompt_cache_options.modeto"explicit"to use only yours, and choose attlof"30m"(default) or"12h"(Responses API). The SDK's type documentation says each request can write up to four breakpoints and matching considers the latest 80. - Earlier models: caching uses
prompt_cache_retentionwithin_memoryor24h, and the minimum depends on request settings.
Pricing on GPT-5.6+ follows the same shape as Anthropic: the guide lists cache reads at 0.1x ordinary input (0.05x for GPT-6.1 Sol and Terra) and cache writes at 1.25x for the 30-minute lifetime and 2.5x for 12 hours. For example, the GPT-6 Astra model page lists $10 input, $1 cached input, and $12.50 cache writes per million tokens.
Python example (Responses API)
This uses openai 3.51.0, whose responses.create() accepts prompt_cache_key, prompt_cache_options, and per-block prompt_cache_breakpoint:
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY
with open("handbook.md", encoding="utf-8") as f:
HANDBOOK = f.read()
def ask(question: str) -> str:
response = client.responses.create(
model="gpt-6-astra",
input=[
{
"role": "developer",
"content": [
{
"type": "input_text",
"text": "Answer questions using only this handbook:\n\n" + HANDBOOK,
"prompt_cache_breakpoint": {"mode": "explicit"},
}
],
},
{"role": "user", "content": question},
],
prompt_cache_key="handbook-v3", # stable key for requests sharing this prefix
)
details = response.usage.input_tokens_details
print(f"cached={details.cached_tokens} written={details.cache_write_tokens} "
f"total input={response.usage.input_tokens}")
return response.output_text
print(ask("How many vacation days do new hires get?"))
print(ask("What is the remote work policy?"))
Two details from the guide that matter in production:
- Top-level
instructionscannot hold a breakpoint. Put reusable instructions in aninput_textblock inside a developer message, as above. - Routing has limits. Cached state lives on individual machines, and the guide advises keeping traffic to roughly 15 requests per minute per
prompt_cache_key, partitioning busier traffic across several keys with a stable mapping. Cached tokens still count toward your tokens-per-minute rate limit.
Ordinary (uncached, unwritten) input is input_tokens - cached_tokens - cache_write_tokens.
Gemini: implicit by default, explicit cache objects on older models
Google's context caching docs describe two mechanisms, and which one you can use depends on API and model.
Implicit caching is on by default for Gemini 2.5 and newer, with no configuration and, in Google's words, "no cost saving guarantee." It works with the Interactions API (now Google's recommended default) and with generateContent. Minimums are 4,096 tokens for Gemini 4 Carbon, Argon, and Hydrogen, Gemini 3.8 Flash, 3.6 Flash, and 3.1 Pro Preview, and 2,048 for Gemini 2.5 Flash and Pro. One Gemini 4 detail affects agent loops: the full previous request is cached only if the new request adds at least 2,050 tokens; smaller additions re-process the last 2,050 tokens at the standard rate.
Explicit caching creates a named cache object with a TTL (default one hour) that you reference in later calls. It guarantees the discount but adds an hourly storage charge, is in beta under v1beta, works only through generateContent, and is not supported on Gemini 4 models.
Discounts are per model on the pricing page. Gemini 4 Hydrogen lists $1.50 input and $0.075 for cached tokens. Gemini 3.8 Flash lists $0.75 input, $0.075 cached, and $0.50 per million tokens per hour of explicit-cache storage through December 31, 2026, with all three doubling from January 1, 2027.
Python example: implicit caching with the Interactions API
from google import genai
client = genai.Client() # reads GEMINI_API_KEY
with open("handbook.md", encoding="utf-8") as f:
HANDBOOK = f.read()
for question in ["How many vacation days do new hires get?", "What is the remote work policy?"]:
interaction = client.interactions.create(
model="gemini-4-hydrogen",
system_instruction="Answer questions using only this handbook:\n\n" + HANDBOOK,
input=question,
)
print("cached tokens:", interaction.usage.total_cached_tokens)
print(interaction.output_text)
Python example: explicit cache with generateContent
from google import genai
from google.genai import types
client = genai.Client(http_options={"api_version": "v1beta"})
model = "gemini-3.8-flash" # explicit caching is not available on Gemini 4
with open("handbook.md", encoding="utf-8") as f:
HANDBOOK = f.read()
cache = client.caches.create(
model=model,
config=types.CreateCachedContentConfig(
display_name="employee-handbook-v3",
system_instruction="Answer questions using only the handbook provided.",
contents=[HANDBOOK],
ttl="3600s",
),
)
response = client.models.generate_content(
model=model,
contents="How many vacation days do new hires get?",
config=types.GenerateContentConfig(cached_content=cache.name),
)
print("cached tokens:", response.usage_metadata.cached_content_token_count)
print(response.text)
client.caches.delete(name=cache.name) # stop paying storage when you are done
Note from the docs: implicit caching does not apply to a request that uses an explicit cache; extra input sent alongside it is billed at the standard rate. You can extend a cache with client.caches.update() by setting a new ttl or expire_time.
A worked cost example
Assume a 50,000-token system prompt (a product manual) on Claude Opus 5.5, queried 100 times with requests arriving less than five minutes apart. Counting only the shared prefix, at the published rates:
| Scenario | Calculation | Cost |
|---|---|---|
| No caching | 100 × 50,000 × $4/M | $20.00 |
| 5-minute cache | 1 write: 50,000 × $5/M = $0.25; 99 reads: 4.95M × $0.20/M = $0.99 | $1.24 |
The per-request question and output tokens cost the same in both scenarios, so the saving on the shared prefix is the whole story. The same arithmetic shows when caching loses money: a 5-minute write that is never read costs 1.25x of what you would have paid uncached. With Anthropic's standard 0.1x read price, one write plus one read (1.35x) already beats two uncached requests (2x).
Structuring prompts for a high hit rate
The rules below appear, in different words, in all three providers' docs:
- Stable first, volatile last. System instructions, tool definitions, few-shot examples, and reference documents go at the top. Timestamps, user IDs, retrieved snippets, and the question go at the end.
- Never put a timestamp or request ID in the system prompt. It makes every prefix unique. Inject the current date in the final user message if the model needs it.
- Keep tool lists deterministic. Same tools, same order, same schemas on every call. Serialize JSON with sorted keys. OpenAI recommends restricting tools with
tool_choiceorallowed_toolsinstead of removing them, and the MCP 2026-07-28 specification now asks servers to returntools/listin a deterministic order for exactly this reason. - Append, do not rewrite. In multi-turn conversations, add new turns at the end. Summarizing or truncating earlier turns resets reuse from that point.
- Watch the minimum. A 900-token system prompt caches on current Claude models (512 minimum) but not on GPT-5.6+ (1,024) or Gemini 4 (4,096).
- Measure. Log the cached-token field on every response. If it reads zero on repeated calls, something in the prefix is changing.
Model choice also matters: caches are per model. Routing the same conversation across several models, a common pattern behind an LLM gateway like LiteLLM or Portkey, means each model builds its own cache.
Prompt caching vs semantic caching
They solve different problems and stack well together.
| Prompt caching | Semantic caching | |
|---|---|---|
| Where it runs | Inside the provider's inference stack | In your application or gateway |
| What it reuses | Computed KV state for a shared prompt prefix | A previously generated answer |
| Match rule | Exact prefix match | Embedding similarity between requests |
| Model still runs? | Yes, on the uncached suffix | No, on a hit the model is skipped |
| Risk | None to output quality | Can return a stale or subtly wrong answer if the similarity threshold is loose |
Use prompt caching whenever you have a large shared prefix; it never changes answers. Add semantic caching for high-volume, repetitive questions where returning a stored answer is acceptable. Our roundup of semantic caching tools compares the options, and reasoning token optimization covers the output side of the bill, which prompt caching does not touch.
Frequently Asked Questions
Does prompt caching change the model's output?
No. All three providers reuse computation for an identical prefix; the model processes the remaining tokens and generates output exactly as it would without caching. That is the key difference from semantic caching, which can return a stored answer.
Is OpenAI prompt caching automatic?
Yes. OpenAI's guide says caching is enabled by default on supported models. On GPT-5.6 and later you can add explicit breakpoints with prompt_cache_breakpoint, choose a 30-minute or 12-hour lifetime, and use prompt_cache_key to improve routing and track usage per customer.
How long does a Claude prompt cache last?
Five minutes by default, and each cache hit refreshes the timer at no extra cost. You can request a one-hour lifetime with "ttl": "1h", which costs 2x base input for the write instead of 1.25x. The lifetime counts from the start of the request, so long generations eat into it.
What is the minimum prompt size for caching?
It depends on the provider and model: 512 tokens on current Claude models (older ones need 1,024 to 4,096), 1,024 tokens on OpenAI GPT-5.6 and later, and 2,048 to 4,096 tokens on Gemini depending on the model. Shorter prompts are processed normally without an error.
Why am I not getting cache hits?
The most common causes are something dynamic in the prefix (a timestamp, UUID, or unsorted JSON), a tool list that changes between calls, requests spaced further apart than the cache lifetime, a prompt below the minimum length, or requests split across workspaces, organizations, or models. Check the provider's cached-token usage field to confirm.
Can I use Gemini explicit caching with Gemini 4?
No. Google's docs state explicit caching is not supported for Gemini 4 models or in the Interactions API. Gemini 4 uses implicit caching, which is automatic. Explicit cache objects remain available for Gemini 3.x and 2.5 models through generateContent.
Conclusion
Prompt caching is the cheapest optimization in LLM engineering: no quality trade-off, often a large cut in input cost, and lower time to first token. The providers differ in control (Anthropic is opt-in and explicit, OpenAI and Gemini are automatic with optional knobs), in minimum prompt sizes, and in lifetimes, but the discipline is identical: put stable content first, keep it byte-identical, and verify hits through the usage fields. Start by logging cached tokens on your current traffic. If the number is near zero, fixing prompt structure is likely the highest-return change you can make this week.
Want to test prompt variants or count tokens while you restructure? Try the free AI tools on Butlermind Hub.