Prompt caching

In one sentence

The provider keeps the computed KV state of a recently seen prompt prefix, so repeat calls skip that prefill: put static content first, variable content last, and cut repeated input cost by up to ~90–95%.

Analogy: Reading a 300-page brief once and then answering a stream of questions about it, instead of re-reading the whole brief before every single question.

The first call pays to compute and store the prefix; every call within the TTL that starts with the same bytes reuses it.

How it works

  • Every call starts with prefill, computing keys and values for each input token; identical prefixes repeat identical work.
  • A hit needs the exact same prefix, byte for byte from the first token.
  • So order the prompt: tools and system, then documents, then append-only history, then the new message.
  • Writes cost 1.25× base input on Anthropic, reads 0.1× (late 2026), so the first reuse breaks even.
  • Unlike semantic caching, the answer is generated fresh, so it can never serve a stale response.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your RAG prompt is laid out as: system prompt (2K tokens) → this query's retrieved chunks (6K) → 40K tokens of fixed policy documents → user question. Caching is enabled, yet input cost barely moved. Best fix?

Go deeper

Full explanation

Every call starts with prefill: computing attention keys and values (KV cache) for every input token. If 50k tokens of tools, system prompt and documents are identical across calls, that work is identical too. Prompt caching keeps that KV state on the provider's side and reuses it when a new request starts with the exact same prefix, byte for byte from the first token.

That one rule dictates the layout:

  1. Tools and system prompt (static)
  2. Reference documents and examples (static per session)
  3. Conversation history (append-only)
  4. The new user message (variable), last

Provider terms (as of late 2026):

  • Anthropic: opt-in cache_control, as one top-level field (auto-placed breakpoint) or up to 4 explicit breakpoints. Writes cost 1.25× base input with a 5-minute TTL refreshed on every hit, or 2× for 1 hour; reads cost 0.1× (0.05× or less on some newer models).
  • OpenAI: on by default from 1,024 tokens; check cached_tokens in usage. Older models charge no write fee and discount cached input 50–90%; GPT-5.6 and later bill writes at 1.25× (30-minute TTL) and reads at 0.1×.
  • Gemini: implicit caching by default (2.5+), plus explicit caches with a TTL and an hourly storage fee on supported models.
  • Self-hosted: vLLM automatic prefix caching, SGLang RadixAttention.

The answer is still generated fresh, so unlike Semantic caching it can never serve a stale response.

Code Cache a 50k-token handbook across questions
pythonCache a 50k-token handbook across questions
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"  # any current Claude model

HANDBOOK = open("hr_handbook.md").read()  # ~50k tokens, identical on every call

def ask(question: str) -> str:
    resp = client.messages.create(
        model=MODEL,
        max_tokens=1024,
        system=[
            {"type": "text", "text": "Answer HR questions using only the handbook."},
            # Breakpoint: everything up to and including this block is cached
            {"type": "text", "text": HANDBOOK, "cache_control": {"type": "ephemeral"}},
        ],
        # Variable content goes AFTER the cached prefix
        messages=[{"role": "user", "content": question}],
    )
    u = resp.usage  # verify hits instead of assuming them
    print(u.cache_creation_input_tokens, u.cache_read_input_tokens, u.input_tokens)
    return resp.content[0].text

ask("How many vacation days do I get?")  # write: 1.25x base input on 50k tokens
ask("Can I carry unused days over?")     # read: 0.05x on Sonnet 5.5, 0.1x on most

# OpenAI caches by default from 1,024 tokens; in Chat Completions check
# resp.usage.prompt_tokens_details.cached_tokens
Real example

An HR assistant sends a 2k-token system prompt plus a 50k-token handbook with every question, ~1,000 questions an hour, on a model priced at $3 per million input tokens. Uncached: 52k × $3/M ≈ $0.156 per call, ~$156 an hour. With the prefix cached and traffic keeping the 5-minute TTL warm, each call reads it at 0.1× for ~$0.016: ~$16 an hour plus a few ~$0.20 writes, roughly a 90% cut in input cost. Time to first token falls too, because the 52k-token prefill is skipped.

Trade-offs +3 · −3

+ You gain

  • Up to ~90–95% off repeated input tokens and a large time-to-first-token cut on long prefixes.
  • Zero quality risk: the output is still generated fresh from the full prompt.
  • Makes long system prompts, many-shot examples and document-in-context designs affordable.

− You pay

  • Only exact prefixes hit: one changed byte early in the prompt invalidates everything after it.
  • Short TTLs: sparse or bursty traffic misses the cache and pays the write premium.
  • Provider-specific mechanics (breakpoints, TTLs, minimum lengths, pricing) leak into your prompt layout.

Use it when

Any workload that resends a long, stable prefix: agents with big system prompts and tool lists, multi-turn chat, document Q&A, many-shot prompts, batch jobs over one shared context.

Avoid it when

Prompts under the model's minimum cacheable length, or prefixes unique to each call; where writes are billed (Anthropic, OpenAI GPT-5.6+), a prefix not reused within the TTL just pays the 25% write premium.

Numbers to know 5
  • Anthropic (late 2026): cache write 1.25× base input (5-minute TTL) or 2× (1-hour TTL); cache read 0.1×, or 0.05× on Opus and Sonnet 5.5.
  • Break-even with a 1.25× write and 0.1× read is the first reuse: two calls cost ~1.35× instead of 2×.
  • OpenAI (late 2026): on by default from 1,024 tokens; older models discount cached input 50–90% with no write fee; GPT-5.6+ charge 1.25× to write and 0.1× to read.
  • Anthropic's 2024 launch benchmark: a 100k-token cached prompt cut time to first token from 11.5 s to 2.4 s and cost by 90%.
  • Minimum cacheable prefix depends on the model: 512–4,096 tokens on Claude, 1,024 on OpenAI, 2,048–4,096 for Gemini implicit caching. Shorter prompts never cache.
Common pitfalls 4
  • A timestamp, request ID or user name at the top of the system prompt: every call is a new prefix and the hit rate drops to ~0%.
  • Non-deterministic serialization: tools or JSON keys emitted in a different order per call silently break the prefix.
  • Placing per-query RAG chunks before the stable instructions instead of after them.
  • Never reading the cache fields in the usage response, so nobody notices the hit rate is zero.
Interview questions 3

Answer out loud first, then reveal.

You enabled prompt caching but the hit rate is near zero. What do you check?Show answer

First the usage fields, cache reads versus writes per call, then I diff two consecutive raw requests byte by byte. The usual culprits: something dynamic near the top (a timestamp, user ID or request ID in the system prompt), tools or JSON keys serialized in a different order, a prefix below the model's minimum, or traffic too sparse for a 5-minute TTL. The fixes are about layout: static first, variable last, deterministic serialization, and the 1-hour TTL if gaps between calls are long.

How is prompt caching different from semantic caching?Show answer

Prompt caching reuses computation: the provider skips prefill for an identical prefix, but the model still generates a fresh answer from the full prompt, so quality is unchanged. Semantic caching reuses an answer: if a new query embeds close to an old one, you return the stored response and skip the model entirely. That's far cheaper but can serve a wrong or stale answer to a subtly different question. I turn on prompt caching everywhere and add semantic caching only for high-repeat, low-risk queries.

How does prompt caching change the long-context vs RAG decision?Show answer

It shrinks the cost gap for static corpora. Stuffing 150k tokens costs ~$0.45 per query at $3 per million input tokens; cached, ~$0.045, which is within ~3× of a 5k-token RAG prompt. So for a small corpus that is identical for every user and queried often enough to keep the cache warm, I'll often skip the retrieval stack. It doesn't help when the corpus changes constantly, differs per user for access control, or exceeds the window.