Prompt caching and semantic caching
"Caching" in LLM systems means at least three different things, and mixing them up leads to bad decisions. Prefix caching (inside a serving engine) and prompt caching (the provider-facing version of it) reuse the KV cache computed for an identical prompt prefix, so the model still generates a fresh answer, just faster and cheaper. Semantic caching skips the model entirely by returning a stored answer to a similar earlier question. The first is almost always worth doing. The second is powerful but can return wrong answers if you are careless.
Why it matters
Modern LLM apps resend the same long prefix over and over: a large system prompt, tool definitions, a few-shot block, retrieved documents, or an agent's growing history. Without caching, every request pays to prefill all of it again. That costs money (input tokens) and time (TTFT grows with prompt length, see how inference works).
Semantic caching targets a different waste: many users asking essentially the same question (FAQ bots, support assistants, internal search). If the answer does not depend on who is asking, you can serve it in milliseconds without a model call.
How it works
Prefix and prompt caching
When a request's first N tokens exactly match tokens already in the KV cache, the engine reuses those K and V blocks and only prefills the new suffix. In vLLM this is automatic prefix caching on top of PagedAttention blocks; in SGLang it is RadixAttention, which keeps cached prefixes in a radix tree. Hosted providers expose the same idea as prompt caching:
- OpenAI caches automatically for eligible requests on recent models. Hits require an exact prefix match, and the docs describe optional parameters such as a cache key hint to improve routing to the same cache and a retention setting. Usage objects report cached tokens.
- Anthropic caching is explicit: you mark content blocks with
cache_control, and everything up to that breakpoint is cached. The default lifetime is short (minutes, refreshed on use) with a longer option available. Cache writes and cache reads are priced differently from normal input, so check the current pricing page rather than assuming.
The rule is the same everywhere: static first, dynamic last. Any change near the top of the prompt invalidates everything after it.
Rendering diagram…
Semantic caching
A semantic cache embeds the incoming query, searches a vector index of past queries, and if the nearest match is above a similarity threshold, returns the stored response. On a miss it calls the model and stores the new pair. Libraries such as GPTCache and managed services such as Redis LangCache implement this pattern; you can also build it on any vector store.
Rendering diagram…
Reference architecture
I layer them from cheapest to most dangerous:
- Exact response cache keyed on a hash of the normalised request (model, messages, parameters). Zero risk of wrong answers; useful for deterministic, repeated calls such as classification at temperature 0.
- Prompt or prefix caching at the provider or engine. Safe by construction because the model still generates the answer.
- Semantic cache for selected endpoints only, with metadata filters (tenant, locale, product version, document set) so a hit can only come from the same context.
For self-hosted engines with several replicas, prefix caching only helps if requests sharing a prefix land on the same replica. That is why KV-aware or session-sticky routing appears in large deployments (see serving engines).
Code
Anthropic-style explicit caching of a large, stable system block:
import anthropic
client = anthropic.Anthropic()
LONG_POLICY = open("support_policy.md").read()
resp = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=512,
system=[
{"type": "text", "text": "You are a support assistant."},
{"type": "text", "text": LONG_POLICY, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": "Can I get a refund after 45 days?"}],
)
u = resp.usage
print(u.cache_creation_input_tokens, u.cache_read_input_tokens, u.input_tokens)
A minimal semantic cache with a strict threshold and tenant filter:
import numpy as np
from openai import OpenAI
client = OpenAI()
store: list[dict] = [] # swap for a vector DB in production
THRESHOLD = 0.92
def embed(text: str) -> np.ndarray:
v = client.embeddings.create(model="text-embedding-3-small", input=text).data[0].embedding
v = np.array(v)
return v / np.linalg.norm(v)
def answer(tenant: str, question: str) -> str:
q = embed(question)
best = max((e for e in store if e["tenant"] == tenant),
key=lambda e: float(q @ e["vec"]), default=None)
if best is not None and float(q @ best["vec"]) >= THRESHOLD:
return best["answer"]
out = client.chat.completions.create(
model="gpt-4o-mini", messages=[{"role": "user", "content": question}]
).choices[0].message.content
store.append({"tenant": tenant, "vec": q, "answer": out})
return out
Trade-offs and pitfalls
- Timestamps kill prompt caches. Putting "Current time: ..." or a request id at the top of the system prompt makes every prefix unique. Move it to the end.
- Tool order matters. Reordering tool definitions between requests breaks the prefix. Serialise them deterministically.
- Check usage fields. Do not assume caching works. Log cached token counts per endpoint and alert when the hit rate drops after a prompt change.
- Semantic false positives are real. "How do I cancel my order" and "How do I cancel my subscription" can be very close in embedding space and need different answers. Tune the threshold on labelled pairs from your traffic and prefer precision over hit rate.
- Personalised or time-sensitive answers should not be semantically cached. Anything depending on user data, account state or fresh information needs filters, short TTLs, or no semantic cache at all.
- Invalidation. When the underlying documents or policy change, purge or version the semantic cache, or it will confidently serve stale answers.
- Privacy. A shared semantic cache can leak one user's answer to another. Scope by tenant at minimum.
Checklist
- Prompts are ordered static to dynamic, with deterministic tool serialisation.
- Prefix caching is enabled on my engine, or cache breakpoints are set for my provider.
- I monitor cached token ratios per endpoint.
- Exact-match caching is used for deterministic repeated calls.
- Semantic caching is limited to endpoints where answers are not personalised.
- Semantic cache entries carry tenant and version metadata plus a TTL.
- The similarity threshold was tuned on real labelled query pairs.