Lesson 70.1 · 1 of 5 · 4 min read · Reviewed 24 Nov 2026
Response, semantic and prompt caches
By the end, you can
- Compare response, semantic and prompt caches.
- Pick the right cache for a workload.
“Caching” means three different things in AI systems. They save different costs and carry different risks.
request --> [response cache] hit? return stored answer
--> [semantic cache] similar enough? return stored answer
--> [prompt cache] reuse work on the shared prefix
--> model generates a fresh answer
| Cache | Key | Saves | Risk |
|---|---|---|---|
| Response | Exact request (hash) | Whole call | Stale answers; leaking one user’s answer to another |
| Semantic | Embedding of the question | Whole call | Wrong answer for a question that only looks similar |
| Prompt | Exact prefix of the prompt | Most input cost and some latency | Low; answers are still generated fresh |
When each fits
- Response cache: deterministic jobs with repeated inputs, such as labelling the same product description, or a public FAQ answer.
- Semantic cacheSemantic cache: A cache that returns a stored answer when a new question is similar in meaning to an earlier one.: high-volume public questions where a near-duplicate answer is acceptable. Use a strict similarity threshold and never across private data.
- Prompt cache: almost always worth it when a long system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation., tool list, document or conversation history repeats across calls.
Privacy
Response and semantic caches must include the user or tenant in the key when answers depend on private data. Otherwise one customer can receive another’s answer.
On other providers
Prompt cachingPrompt caching: Reusing the processed form of a repeated prompt prefix across requests, which cuts cost and latency. works differently by provider. OpenAI caches long prompt prefixes automatically and bills cached input at a discount. Gemini has implicit caching on recent models plus explicit context caches you create with a time to live. Claude uses cache breakpointsCache breakpoint: A cache_control marker that ends the part of the prompt to be cached. you place. In every case the rule from 99.5 holds: only an identical prefix can hit.
Key points
- A response cache returns a stored answer for an identical request; no model call at all.
- A semantic cache returns a stored answer for a similar request, matched by embeddings; useful but risky.
- A prompt cache reuses the model's work on a repeated prompt prefix; the model still answers fresh.
Layer three caches before the model
See which requests each cache layer answers, and why the semantic cache must be scoped.
You will have: An ask() function that checks a response cache, a tenant-scoped semantic cache, then the model with a cached prefix.
Steps
- Run the starter: every request reaches the model.
- Add the exact-match response cache check, using the normalised question.
- Add the semantic cache check, matching only within the same tenant.
- Run again and read which layer answered each request.
- Remove the tenant check and see which answer would leak across tenants.
Done when
- Model calls drop to 4 of 8.
- globex never receives an answer cached for acme.
- The prompt cache line shows the shared prefix reused on later model calls.
Open in the Playground No API key needed.
Starter code (Python)
# Layer a response cache, a scoped semantic cache and a prompt cache in front of a (fake) model.
import math
import re
PREFIX_TOKENS = 6000 # system prompt + tools, identical on every call
calls = {"model": 0, "prefix_cached": 0}
response_cache, semantic_cache = {}, []
def normalise(q):
return re.sub(r"\s+", " ", q.strip().lower().rstrip("?!. "))
def vec(text):
words = re.findall(r"[a-z]+", text.lower())
return {w: words.count(w) for w in set(words)}
def cosine(a, b):
dot = sum(a[w] * b.get(w, 0) for w in a)
return dot / ((math.sqrt(sum(x * x for x in a.values())) * math.sqrt(sum(x * x for x in b.values()))) or 1)
def model(question):
calls["model"] += 1
if calls["model"] > 1:
calls["prefix_cached"] += 1 # the shared prefix was cached by the first call
return f"answer to '{question}'"
def ask(tenant, question):
key = (tenant, normalise(question))
v = vec(question)
# TODO 1: return ("response cache", answer) when key is already in response_cache
# TODO 2: return ("semantic cache", answer) for a close match (cosine >= 0.75) from the SAME tenant
ans = model(question)
response_cache[key] = ans
semantic_cache.append((tenant, v, ans))
return "model", ans
REQUESTS = [
("acme", "What are your opening hours?"),
("acme", "what are your opening hours"),
("acme", "What are the opening hours?"),
("globex", "What are your opening hours?"),
("acme", "How do I reset my password?"),
("acme", "How do I reset my password?"),
("globex", "How can I change my delivery address?"),
("acme", "how do i reset my password"),
]
for tenant, q in REQUESTS:
layer, _ = ask(tenant, q)
print(f"{tenant:<7} {q:<42} -> {layer}")
print(f"model calls: {calls['model']} of {len(REQUESTS)}")
print(f"prompt cache: prefix reused on {calls['prefix_cached']} calls, about {calls['prefix_cached'] * PREFIX_TOKENS:,} tokens read from cache")
Show a solution
# Layer a response cache, a scoped semantic cache and a prompt cache in front of a (fake) model.
import math
import re
PREFIX_TOKENS = 6000 # system prompt + tools, identical on every call
calls = {"model": 0, "prefix_cached": 0}
response_cache, semantic_cache = {}, []
def normalise(q):
return re.sub(r"\s+", " ", q.strip().lower().rstrip("?!. "))
def vec(text):
words = re.findall(r"[a-z]+", text.lower())
return {w: words.count(w) for w in set(words)}
def cosine(a, b):
dot = sum(a[w] * b.get(w, 0) for w in a)
return dot / ((math.sqrt(sum(x * x for x in a.values())) * math.sqrt(sum(x * x for x in b.values()))) or 1)
def model(question):
calls["model"] += 1
if calls["model"] > 1:
calls["prefix_cached"] += 1 # the shared prefix was cached by the first call
return f"answer to '{question}'"
def ask(tenant, question):
key = (tenant, normalise(question))
if key in response_cache:
return "response cache", response_cache[key]
v = vec(question)
for t, qv, ans in semantic_cache:
if t == tenant and cosine(v, qv) >= 0.75: # scoped to the same tenant
return "semantic cache", ans
ans = model(question)
response_cache[key] = ans
semantic_cache.append((tenant, v, ans))
return "model", ans
REQUESTS = [
("acme", "What are your opening hours?"),
("acme", "what are your opening hours"),
("acme", "What are the opening hours?"),
("globex", "What are your opening hours?"),
("acme", "How do I reset my password?"),
("acme", "How do I reset my password?"),
("globex", "How can I change my delivery address?"),
("acme", "how do i reset my password"),
]
for tenant, q in REQUESTS:
layer, _ = ask(tenant, q)
print(f"{tenant:<7} {q:<42} -> {layer}")
print(f"model calls: {calls['model']} of {len(REQUESTS)}")
print(f"prompt cache: prefix reused on {calls['prefix_cached']} calls, about {calls['prefix_cached'] * PREFIX_TOKENS:,} tokens read from cache")
Do it Measure a prompt cache in the Playground in the Playground. No API key needed.