Learning path: Prompt and Context Engineering · Step 5 of 8
Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
A shop help desk sends the same 1,373-token policy with every question. Keep that start byte-for-byte identical, mark it for caching, and the second call's input drops from $0.005608 to $0.000391. One timestamp at the top breaks it.
What you will learn
- Explain how a provider reuses the longest identical start of a request
- Order a prompt as fixed text first and changing text last, and see one timestamp break the cache
- Mark a system prompt with cache_control and read the cache fields in usage
- Price a cache write and a cache hit, and tell a prompt cache from an answer cache
Before you start
- LLM Tokens, Context Windows and Cost
- The Claude Messages API: Your First Call
A small thing quietly eats your budget: sending the same text again and again. Our example is the help desk of an online shop. Every question goes to the model with the same long shop policy attached. The idea of this article is simple: pay for that policy once.
Every question carries the whole policy
The model remembers nothing between calls, so every question travels with the full policy. Here are five questions in one chat, with what each request sent:
| Question | Input tokens sent, running total | Of which the same policy |
|---|---|---|
| 1. Where is order 1002? | 1,378 | 1,373 |
| 2. How do returns work? | 2,780 | 2,746 |
| 3. What is the warranty? | 4,212 | 4,119 |
| 4. Can I exchange an item? | 5,675 | 5,492 |
| 5. How long do refunds take? | 7,169 | 6,865 |
After five questions we've sent about 7,200 tokens, and almost 6,900 of them are the same policy. That's 96%. Most of every request is the same text, and that is the waste we're going after. (Where those tokens come from, and how the bill grows with them, is in LLM Tokens, Context Windows and Cost.)
A new assistant and the policy pack
A new assistant joins the shop and gets a thick policy pack on day one. The first customer asks where order 1002 is. The assistant reads the whole pack, then the question. That takes a while. The second customer asks something else. The pack is already read, so only the question gets read. Much quicker. Then somebody edits one word on page one. The assistant's notes are out of date, so it's back to reading everything.
In model language: the pack is the system prompt, "already read" means cached tokens, and an edited page one is a cache miss. Reading the pack is the costly part. Reading the question is not.
The stable start sits in one place
In the app, the pack is built once, in help_desk.py:
# The stable part of every request: the same bytes every time, so the provider can cache it.
# Nothing that changes per request (a time, a request id, the question) goes in here.
SYSTEM = ("You are the help desk of an online shop. Answer from the shop policy below and the customer's files. "
"The customer may attach photos or documents (receipts, invoices, letters, screenshots): read them.\n\n"
+ POLICY_PATH.read_text(encoding="utf-8"))
It reads policy.md and adds it on: 5,490 characters, or about 1,373 tokens. Read the comment above it. Same bytes every time. Nothing that changes per request goes in here: no time, no request id, and not the question. Those all go later. That sameness is what lets the provider cache it.
The provider matches from the start
How does the provider know it has seen this before? It compares your request from the very start. Two calls both begin with the same SYSTEM text. After that, the second one carries the earlier chat and a new question.
A test model that keeps the books
The app also has a test model that needs no API key but keeps cache books the way a provider does. Inside its stream method:
key = hashlib.sha256(system.encode()).hexdigest()
prefix = estimate(system)
rest = estimate(" ".join(m["content"] for m in messages) + " ".join(f.text for f in files))
rest += IMAGE_TOKENS * sum(f.is_image for f in files)
hit = key in self.cached
self.cached.add(key)
out = estimate(text)
yield Reply(self.model, rest, prefix if hit else 0, 0 if hit else prefix, out, out * THINKING)
It takes a fingerprint of the system prompt and asks: is this fingerprint already in the cache? On the first call it isn't, so it goes in and 1,373 tokens count as written. On the second call it's found and the same 1,373 count as cached. The meter under each answer shows it:
test-model · in 1378 · out 19 + 38 reasoning · 972 ms
test-model · in 29 + 1373 cached · out 25 + 50 reasoning · 1538 ms [cache hit]
One small difference: the test model checks the whole system prompt, while Claude, OpenAI and Gemini match the longest identical start.
Break it: one timestamp at the top
Somebody adds a "helpful" line to the top of the system prompt: the current time. Then the same idea with the time moved to the end, after the question.
The run of the app with the test model shows both cases:
--- broken
call 1: in 5 cached 0 written 1379 input $0.006915 (no cache $0.005536)
call 2: in 29 cached 0 written 1379 input $0.007011 (no cache $0.005632)
call 3: in 59 cached 0 written 1379 input $0.007131 (no cache $0.005752)
--- fixed
call 1: in 10 cached 0 written 1373 input $0.006905 (no cache $0.005532)
call 2: in 39 cached 1373 written 0 input $0.000431 (no cache $0.005648)
call 3: in 74 cached 1373 written 0 input $0.000571 (no cache $0.005788)
With the time at the top, the start never matches: cached 0, 0, 0, and every call writes all 1,379 tokens again. That is worse than no cache at all, because writing costs more than plain input. Move the time to the end and calls two and three read 1,373 tokens from the cache.
The input bill
The cache changes the input side of the bill, so that's the side we price. The prices used here were Anthropic's for Claude Opus 5.5 at the time of the lecture, per million tokens: input $4, cache write $5, cache read $0.20. Prices change, so check the provider's pricing page.
--- main
call 1: in 5 cached 0 written 1373 input $0.006885 (no cache $0.005512)
call 2: in 29 cached 1373 written 0 input $0.000391 (no cache $0.005608)
call 3: in 59 cached 1373 written 0 input $0.000511 (no cache $0.005728)
call 4: in 90 cached 1373 written 0 input $0.000635 (no cache $0.005852)
call 5: in 121 cached 1373 written 0 input $0.000759 (no cache $0.005976)
| Case | Input cost |
|---|---|
| Call 2 with no cache (all 1,402 tokens at $4) | $0.005608, about half a cent |
| Call 1, writes the policy (1,373 at $5) | $0.006885, about 0.7 cents |
| Call 2, a cache hit (1,373 at $0.20) | $0.000391, about 14 times cheaper |
| Five calls, no cache | $0.028676 |
| Five calls, with the cache | $0.009179 |
Almost three cents without the cache, under one cent with it. The first call pays a little more, and every call after it pays a fraction.
Less to read before the first word
There's a second benefit: speed. On a first call, the model reads the whole policy before it writes a single word. On a cache hit, the policy is already read, so the first word comes sooner. There are no seconds to quote here, because the providers only say that cache hits answer faster. Less to read, a faster start.
Switching it on for Claude
Here is the smallest version, a standalone script. The system prompt goes in as one text block with cache_control next to it, the marker that says "cache everything up to here":
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
POLICY = open("policy.md").read() # long, same every call
def ask(question: str) -> str:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system=[{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral"}, # cache up to here
}],
messages=[{"role": "user", "content": question}], # last
)
usage = response.usage
print("written to cache:", usage.cache_creation_input_tokens)
print("read from cache: ", usage.cache_read_input_tokens)
print("normal input: ", usage.input_tokens)
return response.content[0].text
ask("Where is order 1002?") # call 1: writes the cache
ask("How do returns work?") # call 2: reads it
Put your key in the environment as ANTHROPIC_API_KEY=your-key-here; never in the code. The question comes in messages, after the system prompt, because the changing part always goes last. Then the usage tells you what happened: cache_creation_input_tokens is what was written to the cache, and cache_read_input_tokens is what came from it. In the help desk app, the Claude provider passes the system prompt the same way and fills these two fields into the same Reply the test model uses.
Three providers, one number
| Provider | How it switches on | Where the count comes back |
|---|---|---|
| Claude | You mark what to cache with cache_control | cache_read_input_tokens |
| OpenAI | On its own, for prompts of 1,024 tokens or more | cached_tokens in the prompt token details |
| Gemini | Automatic ("implicit caching") for long prompts that repeat | cached_content_token_count |
Different switches, but in the app they all end up in one number, tokens_cached, which the meter shows.
The cache runs out
A cache doesn't last forever. Claude keeps it for about five minutes by default. A question that arrives inside those five minutes is a cache hit (1,373 cached tokens), and the hit starts the five minutes again. Let the time run out and the policy is gone: the next question shows cached 0 and writes all 1,373 again, at the higher price.
--- cache expired
call 1: in 5 cached 0 written 1373
Each provider documents its own lifetime. A cached start lasts a few minutes, and each hit renews it.
The second question, step by step
- The page sends the question and the chat so far to the service.
- The service adds the
SYSTEMtext, the same bytes in the same place every time, and passes it on. - The provider looks at the start and finds it in its cache: 1,373 tokens.
- The reply comes back with its usage, and the page shows
in 29 + 1373 cachedwith a cache hit badge.
Notice that the page never asks for the cache. The start is the same, so it simply hits.
Prompt cache or answer cache
People often mix this up with an answer cache.
| No cache | Prompt cache | Answer cache | |
|---|---|---|---|
| What is reused | Nothing | The identical start | The whole answer |
| Who does it | - | The provider | Your app |
| Input, one later call | $0.005608 | $0.000391 | No model call |
| Breaks when | - | The start changes | A new question, or a stale answer |
A prompt cache needs only a stable start. An answer cache only helps with exact repeats, and its answers can go stale. The two work together. Caching for AI Apps covers the answer cache and the other layers, and what has to go in each cache key.
Recap
| Rule | Why |
|---|---|
| Keep the start identical | The provider reuses the longest identical start |
| Fixed text first | Instructions and the policy |
| Changing text last | The time, the chat and the question |
| First call writes, a bit more | $0.006885 vs $0.005512 with no cache |
| Later calls read, a fraction | $0.000391 vs $0.005608 |
| Watch the meter | Cached tokens show whether it hit |
| About five minutes | Each hit renews it |
Try it yourself: run the two-question script against your own long system prompt and see what the three counters print on each call. Then put the current time at the top of the system prompt and run it again.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.