---
title: "Prompt Caching Examples: 9 Setups With Code and Cost Math"
description: "Prompt caching examples for Anthropic, OpenAI and Gemini: copyable request code, current cache prices and how many cache hits each setup needs to pay off."
canonical: https://vynaris.com/blog/prompt-caching-examples
author: "Dhrumil Barot"
author_bio: "Dhrumil is an AI inference and LLM infrastructure expert. Dhrumil built Vynaris to make model access, routing and pricing simple and transparent for developers."
published: 2026-11-13
updated: 2026-11-13
---

# Prompt Caching Examples: 9 Setups With Code and Cost Math

Published 2026-11-13 · By [Dhrumil Barot](https://vynaris.com/about#founder), Founder

Prompt caching examples for Anthropic, OpenAI and Gemini: copyable request code, current cache prices and how many cache hits each setup needs to pay off.

**TL;DR:** OpenAI and Gemini cache prompt prefixes automatically; Anthropic needs one `cache_control` field. On current models a cache write costs 1.25x normal input (2x to 2.5x for long lifetimes) and a read costs 0.05x to 0.1x, so a 5- or 30-minute cache pays off after one hit and a 1-hour or 12-hour cache after two. The nine examples below are copyable requests with prices checked on 2026-11-13.

These prompt caching examples cover the setups people actually ship: a support bot with a long system prompt, an agent with many tools, a multi-turn chat, an LLM judge, a document Q&A, and a cost check that reads the usage fields. Each one names the model, shows the request, and prices one cache write against one cache read. The rule under all of them is the same: put the content that never changes first, and the content that changes on every request last. A cache hit needs the prefix to match exactly, token for token, up to the breakpoint.

![A cache hit needs an identical prefix: stable content first, changing content after the breakpoint](https://cdn.sanity.io/images/u1qdn8dx/production/50de4e33c7a8e115991066bb534ac8c48d2c69e7-1344x326.png?w=1440&fit=max&auto=format)

*Everything before the breakpoint must be byte-identical across requests.*

## Which provider charges what for prompt caching?

Prompt caching is billed as a premium on the first write and a deep discount on every read. These are the rates the examples use, from the [Anthropic pricing page](https://platform.claude.com/docs/en/about-claude/pricing), [OpenAI API pricing](https://developers.openai.com/api/docs/pricing) and [Gemini API pricing](https://aistudio.google.com/docs/pricing) on 2026-11-13:

| Provider and model | Input per 1M | Cache write per 1M | Cache read per 1M | Minimum prefix | Reads to break even |
| --- | --- | --- | --- | --- | --- |
| Anthropic Claude Sonnet 5.5, 5 min | $2.00 | $2.50 (1.25x) | $0.10 (0.05x) | 512 tokens | 1 |
| Anthropic Claude Haiku 5.5, 1 hour | $0.10 | $0.20 (2x) | $0.01 (0.1x) | 512 tokens | 2 |
| OpenAI gpt-6.1-terra, 30 min | $1.00 | $1.25 (1.25x) | $0.05 (0.05x) | 1,024 tokens | 1 |
| OpenAI gpt-6.1-terra, 12 hours | $1.00 | $2.50 (2.5x) | $0.05 (0.05x) | 1,024 tokens | 2 |
| Google Gemini 4 Carbon, implicit | $2.00 | none | $0.10 (0.05x) | 4,096 tokens | 0 (no premium) |
| Google Gemini 3.8 Flash, explicit | $0.75 | storage $0.50 per hour | $0.075 (0.1x) | 4,096 tokens | about 1 per hour |

The break-even column comes from one formula. With a write multiplier `w` and a read multiplier `r`, caching beats no caching once the reads `k` satisfy `k >= (w - 1) / (1 - r)`. For a 1.25x write and 0.1x read that is 0.25 / 0.9 = 0.28, so one read. For a 2.5x write and 0.05x read it is 1.5 / 0.95 = 1.58, so two reads. Anthropic's pricing page states the same result: one read for 5-minute caches, two for 1-hour caches. Our [prompt caching break-even analysis](https://vynaris.com/blog/prompt-caching-break-even-2026) works through hit rates in more depth.

Note the Gemini dates. Gemini 4 Carbon's $2.00 input and $0.10 cache rate apply through 2026-11-30; from 2026-12-01 they are $4.00 and $0.20. Gemini 3.8 Flash's rates double on 2027-01-01.

## 1. Anthropic: cache a long system prompt with one field

Use this for a support bot or any app whose system prompt is long and identical on every request. Automatic caching puts the breakpoint on the last cacheable block for you.

```python
import anthropic

client = anthropic.Anthropic()
SYSTEM = open("support_policy.md").read()  # about 6,000 tokens, never edited per request

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=500,
    cache_control={"type": "ephemeral"},  # automatic caching, 5-minute TTL
    system=SYSTEM,
    messages=[{"role": "user", "content": "Can I return an opened item?"}],
)
print(response.usage.cache_creation_input_tokens, response.usage.cache_read_input_tokens)
```

What it shows: the first call reports about 6,000 `cache_creation_input_tokens`; calls within the next 5 minutes report them as `cache_read_input_tokens`. Each hit refreshes the 5-minute timer at no charge, per Anthropic's [prompt caching docs](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).

Cost on Claude Sonnet 5.5: the write is 6,000 × $2.50 / 1M = $0.015, each read is 6,000 × $0.10 / 1M = $0.0006, and the uncached prefix would be $0.012 every time. Over 100 requests that keep the cache warm, the prefix costs $0.015 + 99 × $0.0006 = $0.0744 instead of $1.20, which is 94% less.

How to adapt it: keep dates, user names and session IDs out of `SYSTEM`. Put them in the user message.

## 2. Anthropic: cache tools and system for an hour, let the chat cache itself

Use this for an agent with a large tool list that gets traffic in bursts more than 5 minutes apart. An explicit 1-hour breakpoint covers the stable part; automatic caching follows the conversation.

```python
response = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=800,
    cache_control={"type": "ephemeral"},  # automatic, 5 min, for the conversation
    tools=TOOLS,  # 40 tool definitions, unchanged between requests
    system=[{
        "type": "text",
        "text": AGENT_INSTRUCTIONS,
        "cache_control": {"type": "ephemeral", "ttl": "1h"},  # tools + system, 1 hour
    }],
    messages=conversation,
)
```

What it shows: two cache layers. The 1-hour entry must come before any 5-minute entry; Anthropic requires longer TTLs first. Because the cache order is tools, then system, then messages, the breakpoint on the system block covers the tools too.

Cost on Claude Haiku 5.5 for a 20,000-token tools-plus-system prefix: the 1-hour write is 20,000 × $0.20 / 1M = $0.004, each read $0.0002, uncached $0.002. Two reads inside the hour pay for the write.

How to adapt it: never edit a tool description between requests. Changing any tool definition invalidates the tools, system and message caches together.

## 3. Anthropic: keep a long conversation hitting the cache

Use this for chats and agent loops that grow past 20 content blocks per turn. Anthropic looks back at most 20 blocks from a breakpoint for an earlier cache entry, so a turn that adds many tool results can miss.

```python
def with_breakpoints(messages):
    # Keep the automatic breakpoint at the end; add one explicit breakpoint
    # on the last block of the previous turn so the lookback always finds it.
    prev = messages[-2]["content"][-1]
    prev["cache_control"] = {"type": "ephemeral"}
    return messages

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1000,
    cache_control={"type": "ephemeral"},
    system=SYSTEM,
    tools=TOOLS,
    messages=with_breakpoints(conversation),
)
```

What it shows: the documented failure case. Turn 2 has 15 blocks and hits turn 1's entry at block 10. Turn 3 jumps to 35 blocks, the lookback checks blocks 35 to 16, misses the entry at block 15, and you pay a full write. A second breakpoint near the previous turn's end fixes it.

How to adapt it: you get 4 breakpoint slots per request, and automatic caching uses one. Asking for 4 explicit breakpoints plus automatic caching returns a 400 error.

![Anthropic's 20-block lookback misses an entry 20 or more blocks back](https://cdn.sanity.io/images/u1qdn8dx/production/7dc26bf54b19da0516d9e5adee73ccd2ba591876-1344x410.png?w=1440&fit=max&auto=format)

*Add a second breakpoint near the previous turn's end.*

## 4. OpenAI: implicit caching with nothing to configure

Use this when you call a GPT-5.6 or later model through the Responses API and want the default behaviour. OpenAI's [prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching) says caching is on by default, with a breakpoint at the end of the latest eligible message.

```python
from openai import OpenAI

client = OpenAI()
response = client.responses.create(
    model="gpt-6.1-terra",
    input=[
        {"role": "developer", "content": PRODUCT_CATALOG},  # about 10,000 tokens, stable
        {"role": "user", "content": "Which plan includes SSO?"},
    ],
)
details = response.usage.input_tokens_details
print(details.cached_tokens, details.cache_write_tokens)
```

What it shows: implicit caching is not free on new models. On GPT-5.6 and later, the first request bills the prefix as a cache write at 1.25x. GPT-5.5 and earlier had no write charge.

Cost on gpt-6.1-terra: write 10,000 × $1.25 / 1M = $0.0125, read 10,000 × $0.05 / 1M = $0.0005, uncached $0.01. One read covers the write premium.

How to adapt it: the prefix must be at least 1,024 visible tokens. Changing `model`, `tools`, `parallel_tool_calls`, `text.format`, `reasoning.effort`, `text.verbosity` or `context_management` changes the prefix and can cost you the hit.

## 5. OpenAI: explicit-only breakpoint for an LLM judge

Use this when every request shares a long rubric but ends with content you will never see again. In explicit-only mode, anything after your last breakpoint is billed as plain input with no write charge.

```json
{
  "model": "gpt-6.1-terra",
  "prompt_cache_options": { "mode": "explicit" },
  "input": [
    {
      "role": "developer",
      "content": [
        {
          "type": "input_text",
          "text": "Grading rubric and 12 labeled examples (about 3,000 tokens)...",
          "prompt_cache_breakpoint": { "mode": "explicit" }
        }
      ]
    },
    { "role": "user", "content": "Conversation to grade..." }
  ]
}
```

What it shows: the judge pattern from OpenAI's own guide, where an example deployment reported about a 70% token cache-hit rate. In implicit mode the breakpoint would land on the user message and you would pay to write every graded conversation to the cache.

Cost on gpt-6.1-terra: each read of the 3,000-token rubric is $0.00015 instead of $0.003. Top-level `instructions` cannot hold a breakpoint, so the rubric goes in a developer message as above.

## 6. OpenAI: a 12-hour cache for reference material, 30 minutes for the session

Use this when a large reference document is used all day but each user session is short. Set a 30-minute default and override the shared block to 12 hours.

```json
{
  "model": "gpt-6.1-terra",
  "prompt_cache_options": { "mode": "explicit", "ttl": "30m" },
  "input": [
    {
      "role": "developer",
      "content": [{
        "type": "input_text",
        "text": "Full API reference (about 50,000 tokens)...",
        "prompt_cache_breakpoint": { "mode": "explicit", "ttl": "12h" }
      }]
    },
    {
      "role": "user",
      "content": [
        { "type": "input_text", "text": "Session context...", "prompt_cache_breakpoint": { "mode": "explicit" } },
        { "type": "input_text", "text": "Current question..." }
      ]
    }
  ]
}
```

What it shows: mixed lifetimes in one request, with up to four cache writes allowed. The 12-hour write costs 2.5x input; reads cost the same at either lifetime.

Cost on gpt-6.1-terra: the 12-hour write is 50,000 × $2.50 / 1M = $0.125, each read $0.0025, uncached $0.05. With 200 reads in a day, the reference costs $0.125 + 200 × $0.0025 = $0.625 instead of 201 × $0.05 = $10.05.

How to adapt it: to cut first-request latency, send the shared block once at startup with `"prompt_cache_options": {"prewarm": true}`. The prewarm is billed as a cache write.

## 7. Gemini: implicit caching on Gemini 4

Use this for document Q&A on Gemini 4 models, which support implicit caching only. There is nothing to switch on, and no write premium, but also no guaranteed hit, according to Google's [context caching docs](https://aistudio.google.com/docs/caching).

```python
from google import genai

client = genai.Client()
manual = open("product_manual.txt").read()  # about 100,000 tokens

response = client.models.generate_content(
    model="gemini-4-carbon",
    contents=[manual, "What does the warranty cover?"],  # big, stable content first
)
print(response.usage_metadata)
```

What it shows: the prefix must be at least 4,096 tokens, and requests with the same prefix should arrive close together. In multi-turn and agent loops on Gemini 4, the previous request is cached only when the new one adds at least 2,050 tokens.

Cost on Gemini 4 Carbon through 2026-11-30: a hit on the 100,000-token manual costs 100,000 × $0.10 / 1M = $0.01 instead of $0.20. From 2026-12-01 both numbers double.

## 8. Gemini: an explicit cache with a TTL on Gemini 3.8 Flash

Use this when you need guaranteed savings on a large file and can predict how long it will be in use. Explicit caching is in beta, works on Gemini 3 and 2.5 models, and is not available for Gemini 4.

```python
from google import genai
from google.genai import types

client = genai.Client(http_options={"api_version": "v1beta"})
doc = client.files.upload(file="contract_bundle.pdf")  # about 200,000 tokens

cache = client.caches.create(
    model="gemini-3.8-flash",
    config=types.CreateCachedContentConfig(
        system_instruction="You answer questions about these contracts.",
        contents=[doc],
        ttl="3600s",  # defaults to 1 hour if omitted
    ),
)
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="List every termination clause.",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.usage_metadata)
```

What it shows: Gemini bills explicit caches on cached token count plus storage time, not on a write multiplier.

Cost on Gemini 3.8 Flash through 2026-12-31: storage is 0.2M × $0.50 = $0.10 an hour; a read is 200,000 × $0.075 / 1M = $0.015 instead of $0.15. Each read saves $0.135, so one read an hour covers the storage. Delete the cache, or set a short TTL, when the job ends.

## 9. Any provider: check the real cost from the usage fields

Use this in logging or tests, so you know your cache is hitting before the invoice tells you. The field names differ by provider.

```python
def anthropic_input_cost(u, base, write_mult=1.25, read_mult=0.1):
    # u = response.usage; base = input price per 1M tokens
    return (u.input_tokens * base
            + u.cache_creation_input_tokens * base * write_mult
            + u.cache_read_input_tokens * base * read_mult) / 1_000_000

def openai_input_cost(u, base, cached, write_mult=1.25):
    # u = response.usage; cached = cached-input price per 1M
    d = u.input_tokens_details
    plain = u.input_tokens - d.cached_tokens - d.cache_write_tokens
    return (plain * base + d.cached_tokens * cached
            + d.cache_write_tokens * base * write_mult) / 1_000_000
```

What it shows: Anthropic's `input_tokens` counts only the tokens after the last breakpoint, so total input is the sum of the three fields. OpenAI's `input_tokens` is the total, so you subtract cached and written tokens. If both Anthropic cache fields are 0, the prefix was probably under the minimum; Anthropic returns no error in that case. Pass `read_mult=0.05` for Claude Sonnet 5.5 and Opus 5.5.

![Where each provider reports cache reads and writes in the response](https://cdn.sanity.io/images/u1qdn8dx/production/ea95a18bfc0fc386fb32932c6858e7d99e58befb-1344x410.png?w=1440&fit=max&auto=format)

*Log these per request and alert when the read share drops.*

Once you know your hit rate, put it into cost per task. The [Vynaris cost calculator](https://vynaris.com/calculator) prices a task with cached and uncached input across models, and our [LLM API cost spreadsheet template](https://vynaris.com/blog/llm-api-cost-spreadsheet-template) has a column for cached tokens if you prefer a sheet. If you route between providers, note that a cache is per provider and per model: switching a conversation to another model starts a new cache, which Vynaris accounts for when it picks the cheapest model per request.

## What breaks a cache hit?

A cache hit breaks when anything before the breakpoint changes, even by one token. This part of IBM Technology's explainer shows why order matters:

Video: [What is Prompt Caching? Optimize LLM Latency with AI Transformers](https://www.youtube.com/watch?v=u57EnkQaUTY&t=370s) (IBM Technology)

Martin Keen explains prefix matching: the cache compares a prompt token by token from the start and stops at the first difference. He shows why static content (instructions, a manual, few-shot examples) must come before the user's question, and how putting the question first makes every request miss.

- [6:15](https://www.youtube.com/watch?v=u57EnkQaUTY&t=375s) Prefix matching compares tokens from the start
- [6:48](https://www.youtube.com/watch?v=u57EnkQaUTY&t=408s) A prompt with static content first and the question last
- [7:19](https://www.youtube.com/watch?v=u57EnkQaUTY&t=439s) A new question reuses the cached static content
- [7:38](https://www.youtube.com/watch?v=u57EnkQaUTY&t=458s) Putting dynamic content first breaks the cache

The common causes in practice:

- **A timestamp or request ID in the system prompt.** Every request writes a new entry and never reads one.
- **Edited tool definitions.** On Anthropic this invalidates tools, system and messages. On OpenAI, keep the `tools` list stable and restrict calls with `allowed_tools` or `tool_choice: "none"` instead of removing tools.
- **Toggled settings.** Anthropic's web search and citations toggles change the system prompt; changing `tool_choice` or adding images invalidates the message cache. On OpenAI, `reasoning.effort` and `text.verbosity` are part of the prefix.
- **Rewritten history.** Summarizing or truncating earlier turns changes the prefix from that point on.
- **Expired TTL.** 5 minutes on Anthropic by default, a 30-minute minimum on OpenAI GPT-5.6 and later.
- **High traffic on OpenAI.** Caches live on individual machines, and traffic above about 15 requests per minute can overflow to a machine that does not hold your cache.
- **Below the minimum.** 512 tokens on Claude Sonnet 5.5, 1,024 on GPT-5.6 and later, 4,096 on Gemini 4.

## Which example should I use?

| Situation | Example | Provider setting |
| --- | --- | --- |
| Long, fixed system prompt | 1 | Anthropic top-level cache_control |
| Big tool list, bursty traffic | 2 | Anthropic ttl: "1h" on system |
| Long agent conversations | 3 | Second Anthropic breakpoint |
| GPT model, default behaviour | 4 | Nothing; check cached_tokens |
| Shared rubric, unique tail | 5 | OpenAI explicit-only mode |
| Reference doc used all day | 6 | OpenAI ttl: "12h" breakpoint |
| Large doc on Gemini 4 | 7 | Implicit; doc first |
| Large file, guaranteed savings | 8 | Gemini explicit cache with TTL |
| Proving it works | 9 | Usage-field cost check |

The tradeoff: caching is not free insurance. If your prefix changes on most requests, or traffic is too sparse to hit within the TTL, every request pays the write premium and you spend 25% more on input with a 5- or 30-minute cache (100% more with Anthropic's 1-hour write, 150% more with OpenAI's 12-hour write) than with no caching at all. Measure the hit rate first, as in example 9.

## FAQ

### How do I enable prompt caching on Anthropic?

Add `cache_control={"type": "ephemeral"}` at the top level of a Messages API request for automatic caching, or put `cache_control` on a specific content block for an explicit breakpoint. Add `"ttl": "1h"` for a 1-hour cache at 2x input. The prefix must be at least 512 tokens on Claude Sonnet 5.5, Opus 5.5 and Haiku 5.5. See [Claude API pricing](https://vynaris.com/blog/claude-api-pricing) for all rates.

### Is OpenAI prompt caching automatic?

Yes. It is on by default for supported models, with no code change. On GPT-5.6 and later you can control breakpoints with `prompt_cache_options` and `prompt_cache_breakpoint`, and the first request pays a 1.25x cache-write rate for the default 30-minute lifetime.

### How many cache hits until caching pays off?

One read for a 1.25x write (Anthropic 5-minute, OpenAI 30-minute). Two reads for a 2x or 2.5x write (Anthropic 1-hour, OpenAI 12-hour). The formula is `reads >= (write multiplier - 1) / (1 - read multiplier)`. Gemini's implicit cache has no write premium, so any hit saves.

### Does prompt caching reduce output costs?

No. Caching only discounts input tokens before the breakpoint. Output tokens, including reasoning tokens, are billed at the normal output rate.

### Can I share a cache between models or providers?

No. Caches are per model and per provider, and OpenAI caches are not shared across organizations or regions. Switching a conversation to another model means a new cache write.

## About the author

[Dhrumil Barot](https://vynaris.com/about#founder), Founder. Dhrumil is an AI inference and LLM infrastructure expert. Dhrumil built Vynaris to make model access, routing and pricing simple and transparent for developers. [LinkedIn](https://www.linkedin.com/in/bdhrumil) · [X](https://x.com/fyidhrumil)
