akash@sharma:~/blogs$ cat prompt-caching.md

How prompt caching cuts LLM costs, and why it silently misses

What providers store between calls, four experiments on the Claude API, and where caching pays off

Every time you call an LLM, the provider recomputes the model’s internal state for your whole prompt, even a 4,700-token system prompt it processed a few seconds ago. Prompt caching stores that state and reuses it. In my experiments, reading a prompt from cache cut its input cost by 90%, and the whole call cost 65% less.

Getting those hits was the hard part. Turning caching on is one line, but in one of my experiments a new question on an identical, just-cached system prompt read zero tokens from cache, with no error. This post explains what is actually cached, then walks through four small experiments (11 API calls, $0.0053 in total) that show when it works and when it silently doesn’t.

Request 1: nothing saved yet System prompt (on-call runbook) · 4,678 tokens Question 1 Prefill runs on every token; K and V up to ▼ are saved (billed 1.25×). Request 2, seconds later: same opening, new question Same 4,678 tokens, read from cache Question 2 Only the 27-token question is new. Stored K and V load at 0.1×.
  • read from cache (0.1×)
  • written to cache (1.25×)
  • sent fresh (1×)
The pattern this post builds up to: an explicit marker ▼ at the end of the part that stays the same.

What actually gets cached

A transformer processes your prompt in a step called prefill. Every token passes through every layer of the model. In each layer’s attention step, the model computes two vectors of numbers (activations) for that token: a key (K) and a value (V). Every later token, including each token of the answer, looks back at those keys and values to decide what to pay attention to. One key and one value per token, per layer: that collection is the KV cache.

Normally the KV cache is thrown away when the response ends. Prompt caching keeps the K and V tensors for a prefix of your prompt in the provider’s memory for a few minutes. A later request that starts with the same tokens loads them and runs prefill only on the new tokens. The answer is unchanged, because the model would have computed exactly the same numbers again.

Prompt tokens → t1K VK VK VK Vt2K VK VK VK Vt3K VK VK VK Vt4K VK VK VK Vt5K VK VK VK Vt6K VK VK VK Vt7K VK VK VK Vt8K VK VK VK Vt9K VK VK VK Vt10K VK VK VK Vq1K VK VK VK Vq2K VK VK VK Vq3K VK VK VK Vlayer 1layer 2layer 3layer N prefix: K and V loaded from cache, not recomputed new tokens: computed now
  • stored key and value vectors (reused)
  • computed in this request
Every cell is two vectors of numbers. The new tokens (and later the answer) attend back to all the stored K and V in every layer, exactly as if the prefix had just been computed.

Why it has to be an exact prefix. Attention is causal: a token’s K and V depend on that token and every token before it, never on tokens after it. So the stored numbers for token 500 are valid only if tokens 1 to 500 are identical. Change token 3, and the K and V of every later token change too. Experiment 2 below shows this happening.

How big it is. Anthropic doesn’t publish Claude’s architecture, so here is an open model for scale. Llama 3 70B has 80 layers and stores 8 key-value heads of 128 numbers per layer: 2 × 80 × 8 × 128 = 163,840 numbers per token, about 320 KB at 16-bit precision. My 4,700-token runbook would need about 1.5 GB of KV cache on a model that size. That explains the pricing. Keeping it costs memory, so entries are short-lived and writing costs a bit extra. Loading stored numbers is far cheaper than recomputing them through every layer, so reading costs a tenth.

According to Anthropic’s docs, your prompt text isn’t stored: the KV representations and a cryptographic hash of the prefix are held in memory and deleted after the entry expires.

Turning it on takes one line:

client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=400,
    cache_control={"type": "ephemeral"},   # automatic caching
    system=LONG_RUNBOOK,
    messages=[{"role": "user", "content": question}],
)

Three rules from the docs

Every result below follows from these (Claude prompt caching docs):

  1. It’s a prefix match, in a fixed order: tools → system prompt → messages. A hit needs every token from the very start up to a marker to be identical.
  2. Saving only happens at a marker (a “breakpoint”, set with cache_control). One request saves one entry per marker, keyed by a hash of everything up to that point. Nothing is saved anywhere else.
  3. Lookups only find what an earlier request saved. The API checks for an entry at the request’s marker, then steps back block by block (up to 20). It’s looking for a place where a previous request put a marker, not for text that happens to match.

Plus the practical details: entries live 5 minutes, and each hit restarts the clock for free. Haiku 5.5 won’t cache anything under 512 tokens, and it doesn’t raise an error about it. Writing costs 1.25× the normal input price; reading costs 0.1×.

The setup

A small Python script against the raw Claude API (claude-haiku-5-5, no framework). The system prompt was a realistic 4,683-token runbook for on-call engineers: eight services, seven checks each. The first question was “An alert fires daily at 02:00 UTC on checkout-api. What do I check first?” The code and the raw output of every run are in 08_prompt_caching.py.

Caveat up front: one model, one day, eleven calls. The numbers illustrate the mechanics; they are not a benchmark.

Experiment 1: the same prompt, twice

I sent the identical request twice without caching, then twice with it.

A1 · no caching
$0.000616
B1 · first cached
$0.000765
B2 · cache read
$0.000214
  • input at full price
  • input written to cache
  • input read from cache
  • output (never discounted)
Cost per call, measured. The first cached call costs more than no caching at all (the 1.25× write); the second costs about a third. The premium is earned back on the first reuse.

Without cache_control, the response had no cache fields at all. With it, call 1 wrote 4,707 tokens and call 2 read 4,707. Input cost fell from $0.000471 to $0.000048: exactly 90% less, matching the 0.1× read price.

What surprised me was where the money went next. Once the input was cached, output made up about 78% of the bill. Caching shrinks the input side so much that output becomes the real cost. After caching, the next saving is shorter answers, not more caching.

Speed didn’t change in any way I could see: about 1.1 s to the first token either way. Prefill for 4,700 tokens takes only about 30 ms (I measured prefill at roughly 150k tokens/s in an earlier step); most of the wait was the model thinking, which caching doesn’t touch. The latency win shows up with prompts of tens or hundreds of thousands of tokens.

Experiment 2: change one line at the top

The runbook started with a version line, Runbook version: 3f9a…. I changed only that line and sent the same question again.

Before (B2) v 3f9a rest of the runbook (identical) question After (C1) changed rest of the runbook (identical text, different prefix) question one line changed here… …so everything after it misses: 0 read, 4,702 rewritten
A version stamp, a timestamp, a user's name or a request ID near the top of a prompt has the same effect: no cache hit, ever.

A complete miss. The other 99.9% of the prompt was byte-for-byte the same, but the K and V of every token after the change were different, so nothing matched. This is why the order stable first, changing last matters so much.

(I put a random stamp first on purpose, so that rerunning the script within 5 minutes wouldn’t read the last run’s cache. The trick that keeps an experiment clean is exactly the mistake that ruins caching in production.)

Experiment 3: the surprise

Same 4,683-token system prompt that the previous request had just cached, automatic caching on, but a different question: “payments-worker latency doubled after lunch. Where do I start?”

Guess first. The system prompt was saved seconds ago. How many tokens will be read from cache?

Automatic caching: the marker goes on the last block B1 System prompt Question 1 entry saved here D1 System prompt (same as above) Question 2 nothing was ever saved at "system prompt only": read 0, write 4,699 Explicit marker on the system prompt F1 System prompt Question 1 35 fresh F2 System prompt, read from cache: 4,678 tokens Question 2 27 fresh
  • read from cache (0.1×)
  • written to cache (1.25×)
  • sent fresh (1×)
With automatic caching, B1's only entry sits at the end of “system + question 1”. A different question never produces that hash, and the step-back lookup finds nothing at the end of the system prompt because no request ever put a marker there.

Zero. A complete miss: 4,699 tokens written again. Then I moved the marker by hand onto the system prompt, and a different question read all 4,678 system-prompt tokens from cache. Only the question (27 tokens) was sent fresh.

This was the most useful finding of the day. Automatic caching helps within one conversation. It does not help separate questions that share a system prompt. If your app answers lots of independent questions on the same instructions (a support bot, a classifier, an extraction pipeline), put an explicit marker on the last block that stays the same:

system=[{
    "type": "text",
    "text": LONG_RUNBOOK,
    "cache_control": {"type": "ephemeral"},   # marker on the stable part
}],
messages=[{"role": "user", "content": question}],   # changes every time

Experiment 4: a three-turn conversation

Now the case automatic caching was built for: a growing chat, where every turn resends the whole history.

Turn 1 system + Q1 · 4,707 read read experiment 1's entry Turn 2 system + Q1 · 4,707 read +414 written Turn 3 system + Q1 + answer 1 + Q2 · 5,121 read +372 4,707 + 414 = 5,121: each turn reads exactly what the previous turn saved.
Bars drawn to scale. The cached part grows with the conversation; the fresh part is only the latest reply plus the new question.

The chain held. Each turn read the previous turn’s prefix and wrote only the new reply plus the next question. One bonus: turn 1 was byte-for-byte identical to experiment 1’s request, so it read experiment 1’s entry. A cache isn’t tied to one chat or session; any request with the same prefix, in the same workspace, can use it.

What I learned

  1. Caching fails silently, so check the usage fields. Total prompt = input_tokens + cache_creation_input_tokens + cache_read_input_tokens, and input_tokens only counts what comes after the last marker. Track cache hit rate = cache read ÷ total prompt tokens.
  2. Order the prompt from stable to volatile: tools, instructions, reference material, history, new message. Timestamps, names and IDs go last.
  3. Put a marker on the last block that stays the same. Automatic caching suits chats; independent questions on a shared prompt need an explicit marker.
  4. The write premium pays for itself on the first reuse (1.25 + 0.1 = 1.35, versus 2.0 for two uncached calls). After that, output is most of the bill.
  5. Expect a speed gain only with long prompts. At 4.7k tokens I saw none.

For a real-world reference point, I read the log of one of my long Claude Code sessions: a 95% cache hit rate on a ~32k-token fixed prefix (system prompt plus tool definitions), while resending ~170k tokens per call late in the session. It missed only after idle gaps of more than an hour. At that hit rate, input costs roughly a seventh of what it would without caching.

Where prompt caching pays off

The pattern behind every good use: a large chunk of prompt that’s identical across many requests that arrive close together. Lay the prompt out for it:

ToolsInstructionsReference docs, examplesexplicit markerConversation historyautomaticNew message shared by every user and chat: cache itper chat: grows each turn changes rarelychanges on every request
Markers after the parts that are shared and stable; automatic caching for a growing conversation. Anything personal or time-stamped goes at the end.
  • Customer support bots. Cache tools, policies and help-centre articles (often 10k–50k tokens) with an explicit marker after the docs, and use automatic caching for the chat. Expect one rewrite whenever the docs change.
  • Coding agents. The system prompt and tool definitions plus a growing transcript of file reads and edits. Every agent step resends the history with a few new blocks, so automatic caching does most of the work (the 95% above).
  • Chat with a document. A contract, paper, manual or meeting transcript, with a marker right after the document. Use the 1-hour lifetime if people pause to read between questions.
  • Extraction and classification at scale. A long schema, labelling guide and 20+ worked examples, with a marker on the system prompt (the fix from experiment 3). Send one request first, then fan out. Many examples become cheap: each extra example costs a tenth of what it would.
  • Evals and LLM-as-judge. The same rubric and reference answers across thousands of items. Run in waves that stay within the lifetime, or use the 1-hour lifetime.
  • Multi-tenant SaaS. Shared product instructions first, per-customer config after, with a marker after each. Never put tenant details above the shared part.
  • RAG. Cache the fixed instructions, and put retrieved chunks after the marker, since they change per query.

When it won’t help: prompts under the minimum size, prompts personalised near the top, traffic too sparse to come back within 5 minutes, and bills that are mostly output. And requests sent in parallel to a cold cache all miss, because an entry exists only once the first response has started: send one request first, then the rest.

References

Measured with claude-haiku-5-5 on the Claude API, 5 December 2026, at $0.10 per million input tokens and $0.50 per million output. Prices and behaviour change quickly; check the current docs before relying on any number here.