What is prompt caching, and how do you use it well?

Learning path, stage 2 of 5: Prompting and model features · question 8 of 10

Prompt caching lets the provider reuse the processed state of a prompt prefix that repeats across requests: a long system prompt, tool definitions, a big document, earlier chat turns. Cached input tokens cost a fraction of the normal price and cut time-to-first-token, often by a lot for long prompts.

How it works

  • It's a prefix match. Everything up to a cache breakpoint must be byte-for-byte identical.
  • The order is usually tools → system → messages. Change any byte early on and everything after it misses the cache.
  • Entries expire after a TTL (5 minutes by default, or 1 hour). On the Claude API a cache write costs 1.25× normal input (2× for the 1-hour TTL), and a cache read costs 0.1×, so a prefix pays off from the second request.

Getting a high hit rate

  • Put stable content first and changing content last: the user's question, timestamps, IDs.
  • Don't put new Date() or request IDs in the system prompt.
  • Keep the tool list and its order fixed, and serialise JSON deterministically.
  • For chats, move the breakpoint forward each turn so the whole history up to that point stays cached.
  • Measure it: check cache_read_input_tokens in the usage data. If it stays at 0, something in the prefix is changing.

Sources

Code example

tsx
1// Cache a large, stable document; only the question changes per request.
2import Anthropic from "@anthropic-ai/sdk";
3
4const client = new Anthropic();
5
6export async function askHandbook(handbook: string, question: string) {
7 const res = await client.messages.create({
8 model: "claude-opus-5-5",
9 max_tokens: 1024,
10 system: [
11 { type: "text", text: "Answer questions using the employee handbook below." },
12 { type: "text", text: handbook, cache_control: { type: "ephemeral" } }, // breakpoint
13 ],
14 messages: [{ role: "user", content: question }], // changes every time: after the breakpoint
15 });
16
17 console.log({
18 written: res.usage.cache_creation_input_tokens, // first call
19 read: res.usage.cache_read_input_tokens, // later calls: should be > 0
20 uncached: res.usage.input_tokens,
21 });
22 return res;
23}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app