Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 2

Lab: Prompt and Response Caching

Replay the same traffic through four prompt layouts on a stand-in prefix cache and see why stable content must come first and how the cache lifetime interacts with gaps in traffic. Then build an exact-match response cache scoped by tenant and versions, and measure the hit rates and savings of both caches from their logs with pandas.

Contentsand lesson path

What you will learn

  • Apply prompt caching and response caching and measure their hit rates and savings.

01. Goal and setup

Two different caches cut model costs, and they are easy to confuse:

  • Prompt caching happens at the provider. When the beginning of a prompt (the prefix) is identical to one sent recently, the provider reuses the work it already did on it and bills those tokens at a much lower rate. The model still runs and still writes a fresh answer.
  • Response caching happens in your code. When a question has been answered before, under the same conditions, you return the stored answer and the model is not called at all.

In this lab you measure both. Prompt caching needs an API key to observe for real, so steps 1 and 2 use a small stand-in that follows the documented rules of Anthropic's prompt caching in simplified form; step 3 shows the same request against the real API. Steps 4 and 5 build the response cache and measure everything from logs.

You need: Python 3.12 or later and pandas (tested with pandas 3.1). Step 3 is optional and also needs the anthropic package and an API key. Token counts in the stand-in are words, and the prices in step 5 are example figures.

Project layout at the end of the lab
cache-lab/
├── fakeprovider.py     step 1: the stand-in prompt cache
├── prompts.py          step 1: filler prompt parts and a traffic replay
├── try_provider.py     step 1
├── step2_layouts.py    step 2: four prompt layouts, logged to logs/
├── real_call.py        step 3: optional, against the real API
├── response_cache.py   step 4: keys, expiry and normalisation
├── step4_replay.py     step 4
├── measure.py          step 5: hit rates and savings from the logs
└── logs/               written by steps 2 and 4
Terminal
mkdir cache-lab && cd cache-lab
python3 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install pandas

02. Step 1: A stand-in prompt cache

These are the rules the stand-in follows. They match Anthropic's documentation as of October 2026; check the current prompt caching page before you rely on any number.

  • The prompt is read in a fixed order: tools, then system, then messages. A breakpoint (cache_control on a content block) marks the end of a prefix to cache. You can set up to four.
  • A prefix is cached only if it reaches a minimum length, which depends on the model: 512 tokens on the newest models and up to 4,096 on some older ones. A shorter prefix is processed normally, with no error.
  • An entry lives for 5 minutes by default, and every hit restarts that clock. A 1-hour lifetime is available at a higher write price.
  • Writing to the cache costs more than normal input (1.25 times the base input price for the 5-minute lifetime, 2 times for 1 hour); reading costs much less (0.1 times for most models, and less on some of the newest).
  • Any change in a prefix, down to a single byte, means a different entry.
Python · fakeprovider.py
"""A stand-in for a provider's prompt cache, so the lab runs without an API key.

It follows the documented rules of Anthropic's prompt caching in simplified form:
the prefix up to a breakpoint is cached once it reaches a minimum length, a hit
refreshes the entry, and an unused entry expires after its lifetime. Tokens are words.
"""
import hashlib
from dataclasses import dataclass

MIN_CACHEABLE = 512  # tokens; the real minimum depends on the model
LIFETIMES = {"5m": 300, "1h": 3600}  # seconds


def ntokens(text: str) -> int:
    return len(text.split())  # stand-in: real code reads counts from the response


@dataclass
class Block:
    text: str
    cache: str | None = None  # "5m" or "1h" puts a breakpoint after this block


class FakeProvider:
    def __init__(self) -> None:
        self.expiry: dict[str, float] = {}  # prefix hash -> time it expires

    def create(self, blocks: list[Block], now: float, output_tokens: int = 150):
        digest, seen, points = hashlib.sha256(), 0, []
        for block in blocks:
            digest.update(block.text.encode() + b"\0")
            seen += ntokens(block.text)
            if block.cache and seen >= MIN_CACHEABLE:  # shorter: silently uncached
                points.append((digest.hexdigest(), seen, LIFETIMES[block.cache]))
        read = max((t for key, t, _ in points if self.expiry.get(key, 0) > now),
                   default=0)
        for key, _, life in points:  # hits are refreshed, misses are written
            self.expiry[key] = now + life
        written = max((t for _, t, _ in points), default=0) - read
        return {
            "input_tokens": seen - read - max(written, 0),
            "cache_creation_input_tokens": max(written, 0),
            "cache_read_input_tokens": read,
            "output_tokens": output_tokens,
        }

prompts.py holds filler of realistic size for Lumen's prompt parts and a replay of 80 requests: a busy morning with a request every 20 to 160 seconds, a 25-minute lull, and a quieter afternoon with gaps of one to eight minutes.

Python · prompts.py
"""Filler that stands in for Lumen's real prompt parts, sized in words."""
import random

TOOLS = " ".join(f"tool_{n}: look up an account field and return it as JSON."
                 for n in range(1, 41))  # 40 short tool definitions
INSTRUCTIONS = " ".join(f"Rule {n}: answer only from the passages and cite each one."
                        for n in range(1, 81))  # 80 rules
PASSAGES = [f"Passage {n}: " + "help centre text " * 40 for n in range(30)]
QUESTIONS = [
    "How do I reset my password?", "Can I change my billing date?",
    "Why was my card declined?", "How do I export my data?",
    "How do I add a teammate?", "What is the refund window?",
]


def traffic(seed: int = 3) -> list[tuple[float, str, list[str]]]:
    """(arrival second, question, three passages) for 80 requests: a busy
    morning, a 25-minute lull, then a quieter afternoon."""
    rng, now, out = random.Random(seed), 0.0, []
    for n in range(80):
        if n == 40:
            now += 1500
        else:
            now += rng.uniform(20, 160) if n < 40 else rng.uniform(60, 480)
        out.append((now, rng.choice(QUESTIONS), rng.sample(PASSAGES, 3)))
    return out
Python · try_provider.py
from fakeprovider import Block, FakeProvider
from prompts import INSTRUCTIONS, TOOLS

provider = FakeProvider()
short = [Block("You are Lumen's help-centre assistant. " * 50, "5m"), Block("Hi")]
full = [Block(TOOLS), Block(INSTRUCTIONS, "5m"), Block("How do I export my data?")]
for label, blocks, now in [
    ("short prefix", short, 0), ("short prefix again", short, 10),
    ("full prefix", full, 20), ("again, 100 s later", full, 120),
    ("again, 6 min after that", full, 480),
]:
    u = provider.create(blocks, now)
    print(f"{label:<24} uncached {u['input_tokens']:>4}"
          f"  write {u['cache_creation_input_tokens']:>4}"
          f"  read {u['cache_read_input_tokens']:>4}")
Terminal
python try_provider.py
Expected output
short prefix             uncached  251  write    0  read    0
short prefix again       uncached  251  write    0  read    0
full prefix              uncached    6  write 1320  read    0
again, 100 s later       uncached    6  write    0  read 1320
again, 6 min after that  uncached    6  write 1320  read    0

The 251-token prefix is below the minimum, so it is never cached, and nothing tells you so except the zeros in the usage. The full prefix is written once, read 100 seconds later, and written again when six minutes pass without a request.

03. Step 2: Stable content first

Now replay the same traffic through four layouts. no_cache sets no breakpoint. volatile_first puts the current time at the top of the system prompt, a common habit. The two stable_first layouts put tools and instructions first, set the breakpoint after them, and move everything that changes per request (the date, the passages and the question) after it. They differ only in the cache lifetime.

Python · step2_layouts.py
"""Replay the same traffic through four prompt layouts and log the usage."""
import json
from datetime import datetime, timedelta
from pathlib import Path

from fakeprovider import Block, FakeProvider
from prompts import INSTRUCTIONS, TOOLS, traffic

START = datetime(2026, 10, 19, 9, 0)


def layout(name: str, now: float, question: str, passages: list[str]):
    clock = (START + timedelta(seconds=now)).isoformat(timespec="seconds")
    tail = Block("Today is 2026-10-19.\n" + "\n".join(passages) + "\n" + question)
    if name == "no_cache":
        return [Block(TOOLS), Block(INSTRUCTIONS), tail]
    if name == "volatile_first":  # the clock sits at the top of the system prompt
        return [Block(TOOLS), Block(f"Time: {clock}\n{INSTRUCTIONS}", "5m"), tail]
    ttl = "1h" if name == "stable_first_1h" else "5m"
    return [Block(TOOLS), Block(INSTRUCTIONS, ttl), tail]


Path("logs").mkdir(exist_ok=True)
for name in ["no_cache", "volatile_first", "stable_first_5m", "stable_first_1h"]:
    provider, rows = FakeProvider(), []
    for now, question, passages in traffic():
        usage = provider.create(layout(name, now, question, passages), now)
        rows.append({"layout": name, "t": round(now), **usage})
    with open(f"logs/prompt_{name}.jsonl", "w", encoding="utf-8") as f:
        f.writelines(json.dumps(row) + "\n" for row in rows)
    print(name)
    for i in (0, 1, 40):  # first request, second request, first after the lull
        r = rows[i]
        print(f"  #{i + 1:<2} t={r['t']:>5}s  uncached {r['input_tokens']:>4}"
              f"  write {r['cache_creation_input_tokens']:>4}"
              f"  read {r['cache_read_input_tokens']:>4}")
Terminal
python step2_layouts.py
Expected output
no_cache
  #1  t=   53s  uncached 1695  write    0  read    0
  #2  t=  158s  uncached 1694  write    0  read    0
  #41 t= 4874s  uncached 1694  write    0  read    0
volatile_first
  #1  t=   53s  uncached  375  write 1322  read    0
  #2  t=  158s  uncached  374  write 1322  read    0
  #41 t= 4874s  uncached  374  write 1322  read    0
stable_first_5m
  #1  t=   53s  uncached  375  write 1320  read    0
  #2  t=  158s  uncached  374  write    0  read 1320
  #41 t= 4874s  uncached  374  write 1320  read    0
stable_first_1h
  #1  t=   53s  uncached  375  write 1320  read    0
  #2  t=  158s  uncached  374  write    0  read 1320
  #41 t= 4874s  uncached  374  write    0  read 1320

volatile_first writes 1,322 tokens on every request and never reads them: the timestamp makes every prefix new, so you pay the write premium for nothing. The stable layouts read the prefix from the second request on. After the 25-minute lull, request 41 finds the 5-minute entry gone and writes it again, while the 1-hour entry is still there. Notice that the date stayed in the prompt; it only moved behind the breakpoint. The same applies to user names, request ids and anything else that varies per request, and to tool lists, which must be identical and in the same order every time.

04. Step 3: The same layout on the real API (optional)

With the Anthropic Python SDK, a breakpoint is a cache_control entry on a content block. The script reads the model id from the ANTHROPIC_MODEL environment variable (for example claude-sonnet-5-5) and the key from ANTHROPIC_API_KEY. Install the SDK with python -m pip install anthropic. As a shortcut, a top-level cache_control argument on messages.create() caches up to the last cacheable block automatically, and moves that point forward as a conversation grows.

Python · real_call.py
"""The stable-first layout against the real API. Needs ANTHROPIC_API_KEY."""
import os

import anthropic

from prompts import INSTRUCTIONS

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
for question in ["How do I reset my password?", "What is the refund window?"]:
    response = client.messages.create(
        model=os.environ["ANTHROPIC_MODEL"],  # for example claude-sonnet-5-5
        max_tokens=16000,  # one cap for thinking and answer text together
        system=[{
            "type": "text",
            "text": INSTRUCTIONS,
            "cache_control": {"type": "ephemeral"},  # or {..., "ttl": "1h"}
        }],
        messages=[{"role": "user", "content": f"Today is 2026-10-19.\n{question}"}],
    )
    u = response.usage
    print(f"uncached {u.input_tokens}  write {u.cache_creation_input_tokens}"
          f"  read {u.cache_read_input_tokens}  output {u.output_tokens}")
Illustrative output (needs a key; not run here; counts vary by model)
uncached 21  write 1046  read 0  output 96
uncached 20  write 0  read 1046  output 71

If read stays 0 on the second call, something in the prefix changed, or the prefix is below the model's minimum. Caches are also separate per organisation, and on the Claude API per workspace, so traffic split across workspaces warms separate caches. OpenAI also caches prompt prefixes by default and reports the hits in usage.input_tokens_details.cached_tokens. On GPT-5.6 and later models (the GPT-6 family included), it places a breakpoint itself at the end of the latest eligible message, such as the last user message; you can add your own with prompt_cache_breakpoint, or use only yours by setting prompt_cache_options.mode to explicit. There the minimum prefix is 1,024 tokens, and a cache write costs 1.25× the uncached input rate for the default 30-minute lifetime (reported in cache_write_tokens), so a prefix that changes on every call pays a premium on OpenAI too. The layout rule is identical for both: stable first, variable last.

05. Step 4: An exact-match response cache

A response cache returns a stored answer when the same question arrives again. "The same" must include everything that shapes the answer, or the cache serves wrong answers:

  • the tenant, so that one customer never receives an answer built from another customer's documents;
  • the prompt version, the index version and the model, so that a new prompt, a re-indexed help centre or a model change does not keep serving old answers;
  • the question, normalised (Unicode form, case, punctuation, spacing) so that trivial variants hit the same entry.

The entry also gets a lifetime, here one hour, as a backstop for changes the key cannot see. Questions whose answers depend on the user's own data skip the cache entirely.

Python · response_cache.py
"""An exact-match response cache with scoped keys and expiry."""
import hashlib
import json
import re
import unicodedata


def normalise(question: str) -> str:
    text = unicodedata.normalize("NFKC", question).casefold()
    text = re.sub(r"[^\w\s]", " ", text)  # punctuation does not change these answers
    return " ".join(text.split())


def cache_key(tenant: str, question: str, *, prompt_version: str,
              index_version: str, model: str, normalised: bool = True) -> str:
    parts = {
        "tenant": tenant,  # never share answers across tenants
        "question": normalise(question) if normalised else question,
        "prompt": prompt_version,  # a new prompt must not serve old answers
        "index": index_version,  # nor must a re-indexed help centre
        "model": model,
    }
    return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()


class ResponseCache:
    def __init__(self, ttl_seconds: float) -> None:
        self.ttl = ttl_seconds
        self.store: dict[str, tuple[float, str]] = {}  # key -> (expires at, answer)

    def get(self, key: str, now: float) -> str | None:
        expires, answer = self.store.get(key, (0.0, ""))
        if expires > now:
            return answer
        self.store.pop(key, None)  # expired or absent
        return None

    def put(self, key: str, answer: str, now: float) -> None:
        self.store[key] = (now + self.ttl, answer)

The replay sends 600 questions over six hours from two tenants: a quarter need account data and bypass the cache, nearly half are one-off questions, and the rest are frequently asked questions with small variations in wording. Halfway through, the help centre is re-indexed. The same traffic runs twice, once keyed on the raw text and once on the normalised text.

Python · step4_replay.py
"""Replay six hours of questions through the response cache and log every request."""
import json
import random

from response_cache import ResponseCache, cache_key

FAQ = ["How do I reset my password?", "how do i reset my password",
       "How do I reset my password ?", "What is the refund window?",
       "what's the refund window", "How do I export my data?",
       "Can I change my billing date?", "How do I add a teammate?"]
CALL = {"input_tokens": 374, "cache_read_input_tokens": 1320, "output_tokens": 150}

rows = []
for normalised in (False, True):  # the same traffic, keyed two ways
    rng, cache = random.Random(11), ResponseCache(ttl_seconds=3600)
    for n in range(600):  # one request every 36 seconds for six hours
        now = 36.0 * n
        tenant = rng.choice(["acme", "birch"])
        roll = rng.random()
        if roll < 0.25:  # needs this user's account data: never cached
            question, personal = "Why was my last invoice higher?", True
        elif roll < 0.70:  # long tail: asked once
            question, personal = f"Question about topic {n}?", False
        else:
            question, personal = rng.choice(FAQ), False
        key = cache_key(tenant, question, prompt_version="p7", model="large",
                        index_version="idx-41" if now < 3 * 3600 else "idx-42",
                        normalised=normalised)
        if personal:
            outcome, usage = "bypass", CALL
        elif cache.get(key, now) is not None:
            outcome, usage = "hit", {}
        else:
            outcome, usage = "miss", CALL
            cache.put(key, "(answer text)", now)
        rows.append({"key": "normalised" if normalised else "raw", "t": now,
                     "tenant": tenant, "outcome": outcome, **usage})

with open("logs/response_cache.jsonl", "w", encoding="utf-8") as f:
    f.writelines(json.dumps(row) + "\n" for row in rows)
print(f"logged {len(rows)} requests")
for key in ("raw", "normalised"):
    hits = sum(r["outcome"] == "hit" for r in rows if r["key"] == key)
    print(f"{key:>10}: {hits} hits")
Terminal
python step4_replay.py
Expected output
logged 1200 requests
       raw: 105 hits
normalised: 123 hits

You will also meet semantic caching: embed the question and return a stored answer when a past question is similar enough. It raises the hit rate, and it is risky. "Can I get a refund within 30 days?" and "Can I get a refund after 30 days?" sit very close together as vectors and need opposite answers; numbers, negations, plan names and product versions all behave like this. If you try it, keep every scoping field of the exact key, allow it only for answers that contain no personal data, choose the similarity threshold on labelled pairs of questions, log the similarity of every hit, and measure the wrong-answer rate with an evaluation before it serves users.

06. Step 5: Measure hit rates and savings from the logs

Measure from what was logged, as you would in production, not from the code that produced it. For the prompt cache, report the share of requests that read from the cache, the share of prompt tokens served from it, and the cost against the no_cache layout. For the response cache, report hits, bypasses and the money that hits avoided.

Python · measure.py
"""Hit rates and savings of both caches, measured from the logs alone."""
import glob

import pandas as pd

# US dollars per million tokens: example figures, not a quote. Pass in your own.
PRICES = {"input_tokens": 2.00, "cache_creation_input_tokens": 2.50,
          "cache_read_input_tokens": 0.20, "output_tokens": 10.00}


def priced(df: pd.DataFrame) -> pd.DataFrame:
    df = df.reindex(columns=[*df.columns.difference(PRICES), *PRICES]).fillna(0)
    df["cost"] = sum(df[col] * price for col, price in PRICES.items()) / 1e6
    return df


prompt = priced(pd.concat(pd.read_json(p, lines=True)
                          for p in sorted(glob.glob("logs/prompt_*.jsonl"))))
prompt["hit"] = prompt["cache_read_input_tokens"] > 0
prompt["prompt_tokens"] = prompt[list(PRICES)[:3]].sum(axis=1)
by_layout = prompt.groupby("layout", sort=False).agg(
    hit_rate=("hit", "mean"), read_tokens=("cache_read_input_tokens", "sum"),
    prompt_tokens=("prompt_tokens", "sum"), cost=("cost", "sum"),
)
by_layout["cached_share"] = by_layout.pop("read_tokens") / by_layout.pop(
    "prompt_tokens")
by_layout["saving"] = 1 - by_layout["cost"] / by_layout.loc["no_cache", "cost"]
print("prompt cache, 80 requests per layout")
print(by_layout.round(3).to_string())

responses = priced(pd.read_json("logs/response_cache.jsonl", lines=True))
call_cost = responses.loc[responses["outcome"] != "hit", "cost"].mean()
by_key = responses.groupby("key", sort=False).agg(
    requests=("outcome", "size"), cost=("cost", "sum"),
    hit_rate=("outcome", lambda o: (o == "hit").mean()),
    bypass=("outcome", lambda o: (o == "bypass").mean()),
)
by_key["saved"] = by_key["hit_rate"] * by_key["requests"] * call_cost
print("\nresponse cache, 600 requests per key scheme")
print(by_key.round(3).to_string())
Terminal
python measure.py
Expected output
prompt cache, 80 requests per layout
                 hit_rate   cost  cached_share  saving
layout                                                
no_cache            0.000  0.391         0.000   0.000
stable_first_1h     0.988  0.204         0.769   0.478
stable_first_5m     0.725  0.268         0.565   0.315
volatile_first      0.000  0.444         0.000  -0.136

response cache, 600 requests per key scheme
            requests   cost  hit_rate  bypass  saved
key                                                 
raw              600  1.243     0.175   0.237  0.264
normalised       600  1.198     0.205   0.237  0.309

Three results are worth remembering:

  1. A broken layout costs more than no caching. volatile_first pays the write premium on every request: 14% more than no_cache.
  2. The lifetime has to fit the gaps. In the afternoon many requests arrive more than five minutes apart, so the 5-minute entry keeps expiring; the 1-hour lifetime reads on 79 of 80 requests and saves 48% instead of 32%, despite its dearer writes. With steady traffic the default lifetime would be enough, because every hit restarts the clock.
  3. A response cache saves in proportion to repetition. Normalising the key raised the hit rate from 17.5% to 20.5% of all requests (27% of the cacheable ones) and avoided about a fifth of the model spend. Whether that is worth a cache depends on how often your users really repeat themselves, which only your logs can tell you.

07. Check your understanding

Practice check · 3 questions

Caches in practice

Use what you measured in this lab. Each question has one best answer.

Q1. Requests that share a 3,000-token prefix arrive exactly 8 minutes apart. The cache lifetime is 5 minutes and writes cost 1.25 times the input price. Compared with no caching, what does the prefix cost?
Q2. The help centre is re-indexed with a corrected refund policy, but for the next hour the response cache keeps returning the old refund answer. Which part of the key was missing?
Q3. You set a breakpoint after a 300-token system prompt on a model whose minimum cacheable prefix is 512 tokens. What does the usage block show on the second identical request?
Practice only: not graded, not saved, not evidence.

08. Apply it: stretch tasks

  1. Your RAG API. Reorder your prompt so that tools and instructions come first with a breakpoint after them, run your evaluation set twice within five minutes, and confirm from the logged usage that the second run reads the prefix. Report cost per 1,000 queries against the baseline from lesson 2.
  2. A second breakpoint. Many questions retrieve the same top passages. Sort the passages by id, add a breakpoint after them, and measure with the stand-in whether the extra writes pay for themselves in step2_layouts.py.
  3. A pre-warm. For bursty traffic, send one request at the start of each burst and compare the cost with the 1-hour lifetime. Anthropic documents a max_tokens: 0 request for exactly this; read the prompt caching page for its limits.

09. Review prompt

Without looking back:

  1. What is the difference between prompt caching and response caching, and which one still calls the model?
  2. Why did volatile_first cost more than sending no breakpoint at all?
  3. How do you choose between the 5-minute and the 1-hour lifetime, and which numbers in a log tell you that the choice is wrong?
  4. Which fields belong in a response-cache key, and why is semantic caching riskier than exact matching?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check