How a semantic cache avoids paying for the same answer twice
Step 1 of 5
Query arrives
A user asks "how do I reset my password?". Personalised or user-specific requests skip the cache entirely.
Step 2 of 5
Exact match
The canonical prompt is hashed and looked up. An identical earlier request returns its stored answer instantly, with no model call.
Step 3 of 5
Semantic match
On an exact miss, the query is embedded and compared with recent cached queries. "How can I reset my password?" scores above the similarity threshold and reuses the answer.
Step 4 of 5
Call the model
If nothing is similar enough, the model generates a fresh answer. This is the slow, costly path the cache exists to avoid.
Step 5 of 5
Store
The new answer is saved with its hash, embedding, model and a TTL. Entries are versioned by prompt template and invalidated when the underlying data changes.
A cache that returns a near-miss answer is worse than no cache, so tune the similarity threshold carefully.
Problem
Many users ask similar questions. Re-generating identical or near-identical answers wastes money and adds latency.
Pattern
Cache LLM responses keyed by a hash of the canonical prompt. For semantic similarity, embed the query and match against cached queries above a similarity threshold.
Implementation
semantic_cache.py
~203 tokens
import hashlib
from dataclasses import dataclass
@dataclass
class CacheEntry:
query_hash: str
query_embedding: list[float]
response: str
model: str
created_at: float
def get_or_call(messages, model, similarity_threshold=0.95):
query = json.dumps(messages)
qhash = hashlib.sha256(query.encode()).read()
# Exact hit
if entry := cache.get(qhash):
return entry.response
# Semantic hit
qemb = embed(query)
for entry in cache.recent_entries(model, limit=50):
sim = cosine(qemb, entry.query_embedding)
if sim >= similarity_threshold:
return entry.response
# Miss — call the model
response = call_llm(messages, model)
cache.set(qhash, qemb, response, model)
return response
Trade-offs
Massive cost reduction on repeated queries
Semantic cache can return wrong answer on near-misses
Cache invalidation on prompt or data changes
Storage cost for embeddings
Production checklist
TTL per cache entry
Version cache by prompt template version
Invalidate on data ingestion changes
Log cache hit rate per endpoint
Bypass cache for personalised / user-specific data