LLM Caching: Semantic, Prompt and Response Layers
Every language model request re-pays for work that has already been done: re-reading a static system prompt, re-encoding the same retrieved passages, regenerating an answer to a question the product has seen a hundred times today. Caching attacks each of those layers, and the payoff is disproportionate because inference is billed per token and timed per millisecond â remove input tokens and you cut cost and latency together. The risk is equally disproportionate: a stale answer served confidently is worse than a slow correct one, so caching in this domain is a correctness decision dressed up as a performance one. This lesson covers the layers, the invalidation strategies that keep them honest, and the metrics that tell you whether any of it helped.
Three Caches, Three Different Questions
Confusing the layers produces designs that are either useless or dangerous. Each answers a different question about what makes two requests equivalent.
| Cache layer | Equivalence key | Typical saving | Staleness risk |
|---|---|---|---|
| Response cache | Exact prompt and parameters | Full latency and cost | High if underlying data changes |
| Prompt prefix cache | Shared leading tokens | Input tokens, time to first token | Low for static policy blocks |
| Semantic cache | Meaning of the question | Full cost on paraphrase hits | High â similar is not identical |
| Retrieved-context cache | Document id plus query | Embedding and search cost | Low, keyed to document version |
| Tool result cache | Tool name plus arguments | External call latency and load | Depends entirely on the tool |
Start from the right of the table only after the middle rows are solid. Prefix caching is nearly free to adopt and hard to get wrong; semantic caching is where teams lose user trust by serving an answer to a different question that happened to embed closely.
Exact Matching and Prefix Reuse
The simplest wins come from structure. Identical requests â retries, polling loops, repeated form submissions â should deduplicate by a hash of the rendered prompt plus model parameters. Longer prompts built from a static system policy, tool definitions and few-shot examples share a leading prefix, and providers that support prefix or prompt caching will discount those tokens automatically when the prefix matches byte for byte.
import hashlib
import json
import time
from dataclasses import dataclass
@dataclass
class CacheEntry:
value: str
created: float
hits: int = 0
class ResponseCache:
def __init__(self, ttl_seconds: float = 600, max_entries: int = 20_000):
self.ttl = ttl_seconds
self.max_entries = max_entries
self.store: dict[str, CacheEntry] = {}
self.hits = self.misses = 0
@staticmethod
def key(prompt: str, model: str, params: dict) -> str:
blob = json.dumps({"p": prompt, "m": model, "k": sorted(params.items())},
sort_keys=True, ensure_ascii=False)
return hashlib.sha256(blob.encode("utf-8")).hexdigest()
def get(self, key: str) -> str | None:
entry = self.store.get(key)
if entry is None:
self.misses += 1
return None
if time.time() - entry.created > self.ttl:
del self.store[key]
self.misses += 1
return None
entry.hits += 1
self.hits += 1
return entry.value
def put(self, key: str, value: str) -> None:
if len(self.store) >= self.max_entries:
oldest = min(self.store, key=lambda k: self.store[k].created)
del self.store[oldest]
self.store[key] = CacheEntry(value=value, created=time.time())
@property
def hit_rate(self) -> float:
total = self.hits + self.misses
return self.hits / total if total else 0.0
cache = ResponseCache(ttl_seconds=300)
k = ResponseCache.key("summarize incident INC-4471", "gpt-4o-mini", {"temperature": 0})
print(cache.get(k) or "MISS", cache.hit_rate)
Keep the parameter set in the key. Two calls with different temperatures or different tool configurations are different requests even when the prompt text matches, and collapsing them is a subtle bug that shows up as answers that change for no visible reason.
Semantic Caching, Carefully
Semantic caching is the attractive one: embed the request, look for a near neighbor, and serve the stored answer when similarity is high. It works beautifully on repetitive support traffic and fails on everything adjacent to it â currency and dates inside otherwise identical questions, different accounts asking the same phrasing about different data, and questions that differ by a single negation.
import numpy as np
class SemanticCache:
def __init__(self, embedder, index, threshold: float = 0.95):
self.embedder = embedder
self.index = index
self.threshold = threshold
def lookup(self, question: str) -> dict | None:
vector = self.embedder.encode(question)
hits = self.index.search(vector, k=1)
if not hits:
return None
best = hits[0]
if best.score < self.threshold:
return None
answer_meta = best.payload
if self._context_changed(question, answer_meta):
return None
return {"answer": answer_meta["answer"], "source_question": best.payload["question"],
"score": best.score}
@staticmethod
def _context_changed(question: str, meta: dict) -> bool:
entities = extract_entities(question)
bound = meta.get("bound_entities", [])
return bool(entities) and set(entities) != set(bound)
def store(self, question: str, answer: str, scope: dict) -> None:
self.index.upsert({
"vector": self.embedder.encode(question),
"payload": {"question": question, "answer": answer,
"bound_entities": list(extract_entities(question)), **scope},
})
sc = SemanticCache(embedder, index, threshold=0.96)
print(sc.lookup("what is the refund window for enterprise plans?"))
Three controls make this safe: a high threshold rather than a comfortable one, binding the cached answer to the entities present in the question so it cannot be reused across accounts, and keying the scope â tenant, locale, feature flags â into the payload so a hit is only a hit within the same context.
Invalidation Without Surprises
A cache is only as trustworthy as its eviction story, and time-based expiry alone is a compromise rather than a strategy. The useful pattern is to name what can change underneath an entry and key the cache to it. An answer grounded in three documents is invalidated when any of those documents changes version. An answer about a user's account expires with the account data snapshot it read. A generic explanation of a stable concept can live for weeks.
import time
from dataclasses import dataclass, field
@dataclass
class Dependency:
kind: str # document | account | config | none
identifier: str
version: str
@dataclass
class ScopedEntry:
answer: str
deps: list[Dependency]
created: float
hard_ttl: float = 900.0
tags: dict = field(default_factory=dict)
class DependencyAwareCache:
def __init__(self, registry):
self.entries: dict[str, ScopedEntry] = {}
self.registry = registry
def get(self, key: str, scope: dict) -> str | None:
entry = self.entries.get(key)
if entry is None:
return None
if time.time() - entry.created > entry.hard_ttl:
del self.entries[key]
return None
if any(entry.tags.get(k) != v for k, v in scope.items()):
return None
for dep in entry.deps:
if self.registry.version(dep.kind, dep.identifier) != dep.version:
del self.entries[key]
return None
return entry.answer
def put(self, key: str, answer: str, deps: list[Dependency], scope: dict) -> None:
self.entries[key] = ScopedEntry(answer=answer, deps=deps,
created=time.time(), tags=scope)
cache = DependencyAwareCache(registry)
cache.put("q-881", "Refunds clear in 5 business days",
[Dependency("document", "policy-refunds", "v7")],
{"tenant": "acme", "locale": "en"})
print(cache.get("q-881", {"tenant": "acme", "locale": "en"}))
Hard time-to-live caps remain as a backstop for anything you forgot to declare, but declared dependencies do the real work. When an entry expires for reasons the user cannot see, log which dependency invalidated it â repeated invalidation from one source usually means either a thrashing dependency or a cache key that is too specific to ever hit.
What to Measure on the Hit Path
Hit rate on its own rewards the wrong behavior: a very short time-to-live with a wide matching rule will show a respectable number while serving occasional nonsense. Track the pair instead â hit rate alongside a sampled correctness audit of hits, where a judge or human confirms that the cached answer would still be correct for the incoming request. Rising hit rate with falling audit scores is the signature of a cache that is quietly lying.
Latency percentiles tell you whether the cache is even in the right place. If hits still take four hundred milliseconds, the lookup itself is expensive â usually an embedding call or a remote index round trip â and the win is smaller than the dashboard suggests. On the cost side, record input tokens avoided and dollars saved per day, because that number is what justifies the engineering and what tells you which layer to build next.
Also watch for composition effects. A warm cache changes your traffic shape: fewer calls means fewer samples for monitoring, and cache hits on popular questions can mask a model regression that only appears on the cold path. Keep a small fraction of requests routed to live generation with results compared against the cache; divergence alerts you to drift on both sides at once.
When Not to Cache
Some workloads should bypass caching entirely. Highly personalized responses where the cost of a wrong hit exceeds any latency gain; long-running generative tasks where users expect fresh composition each time; adversarial or security-sensitive checks where an attacker could probe and pin a response; and anything where the underlying document changes faster than your invalidation can observe. Streaming first-token latency also benefits from staying live â a cache hit that blocks streaming for a lookup can feel slower than a generation that starts immediately.
A pragmatic default: exact-match caching on for everything, prefix caching wherever the provider supports it, semantic caching gated behind an audit trail and a high threshold, and a per-feature flag so any layer can be switched off the moment a support ticket smells like staleness.
Common Mistakes
Caching without declaring what the answer depends on
Fix: Attach dependencies and versions to every entry and invalidate on change
Using a low semantic similarity threshold
Fix: Raise it, bind answers to entities and scope, and audit sampled hits
Leaving model parameters out of the cache key
Fix: Key on prompt, model, parameters and scope together
Optimizing for hit rate alone
Fix: Pair hit rate with a correctness audit and latency percentiles
Applying one cache policy across all features
Fix: Flag each layer per feature so risky ones can be disabled instantly
Key Takeaways
- Response, prefix and semantic caches solve different problems â pick by equivalence
- Prefix and exact caching are the safe wins; semantic caching carries real correctness risk
- Bind cached answers to entities, tenant scope and document versions
- Measure hit rate with audit correctness and tokens avoided, never hit rate alone
- Keep a slice of traffic on live generation so drift cannot hide behind a warm cache