Search Tutorials
--Ads--Caching Strategies for RAG
Embedding caches, retrieval caches, semantic answer caches and prompt caching.
Caching is the cheapest way to make a RAG system faster and less expensive. Different parts of the pipeline call for different caches, and each comes with a correctness risk: serving a stale or wrong answer. This lesson covers the five cache layers, from safest to riskiest.
The cache layers
| Layer | Key | Saves | Risk |
|---|---|---|---|
| Embedding cache | Model + text hash | Embedding time and cost | None (deterministic) |
| Prompt caching (provider side) | Exact prompt prefix | LLM input cost and latency | None (handled by the API) |
| Retrieval cache | Normalised query + filters + index version | Search and rerank time | Low: stale until the index version changes |
| Exact answer cache | Normalised question + user permissions + index version | Everything | Medium: answers may need personal context |
| Semantic answer cache | Question embedding (similarity threshold) | Everything, for paraphrases | High: similar questions can need different answers |
The embedding cache is covered in Embedding Cost, Latency and Batching and prompt caching in Prompt Caching for RAG. This lesson implements the other three.
Include the index version in every key
Retrieval and answer caches must be invalidated when documents change. Instead of deleting entries, include an index version (for example, a counter or timestamp updated by every sync) in the cache key. After a re-index, old entries are simply never hit again and expire naturally.
Retrieval cache
import hashlib
import json
import time
import re
def normalise(q: str) -> str:
return re.sub(r"\s+", " ", q.lower()).strip(" ?!.")
class TTLCache:
"""A tiny in-process cache. Use Redis or Memcached when you run several servers."""
def __init__(self, ttl_seconds: int = 3600, max_items: int = 10_000):
self.ttl, self.max_items, self.data = ttl_seconds, max_items, {}
def get(self, key: str):
item = self.data.get(key)
if item and item[0] > time.time():
return item[1]
self.data.pop(key, None)
return None
def set(self, key: str, value) -> None:
if len(self.data) >= self.max_items:
self.data.pop(next(iter(self.data))) # drop the oldest entry
self.data[key] = (time.time() + self.ttl, value)
def make_key(*parts) -> str:
return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()
retrieval_cache = TTLCache(ttl_seconds=6 * 3600)
def cached_search(retriever, query: str, k: int, filters: dict, index_version: str):
key = make_key("search", normalise(query), k, filters, index_version)
hits = retrieval_cache.get(key)
if hits is None:
hits = retriever.search(query, k=k)
retrieval_cache.set(key, hits)
return hits
Exact answer cache
Many systems receive the same questions over and over ("How do I reset my password?"). Caching complete answers for identical normalised questions is safe as long as the key includes everything that can change the answer: the permission scope of the user, the index version and the prompt version.
answer_cache = TTLCache(ttl_seconds=24 * 3600)
def cached_answer(question: str, user_scope: str, index_version: str, prompt_version: str, compute):
key = make_key("answer", normalise(question), user_scope, index_version, prompt_version)
answer = answer_cache.get(key)
if answer is None:
answer = compute(question)
answer_cache.set(key, answer)
return answer
Do not cache answers in conversations, where the same words can mean different things depending on earlier turns, or for questions about the user's own data.
Semantic answer cache
A semantic cache returns a stored answer when a new question is similar enough to a previous one ("How do I reset my password?" vs "password reset steps?"). It raises hit rates but can be dangerously wrong: "Can contractors work from home?" and "Can employees work from home?" are very similar sentences with different answers.
import numpy as np
from rag_helpers import embed
class SemanticCache:
def __init__(self, threshold: float = 0.95):
self.threshold = threshold
self.vectors: list[np.ndarray] = []
self.entries: list[dict] = []
def lookup(self, question: str, scope: str, index_version: str) -> str | None:
if not self.vectors:
return None
q = embed(question, query=True)[0]
sims = np.vstack(self.vectors) @ q
for i in np.argsort(-sims):
if sims[i] < self.threshold:
break
e = self.entries[i]
if e["scope"] == scope and e["index_version"] == index_version:
return e["answer"]
return None
def store(self, question: str, answer: str, scope: str, index_version: str) -> None:
self.vectors.append(embed(question, query=True)[0])
self.entries.append({"question": question, "answer": answer,
"scope": scope, "index_version": index_version})
If you use one, set a high threshold, restrict it to a curated set of frequent questions, and log every semantic hit together with both questions so you can audit them.
Measure the hit rate
Log hits and misses for each layer. A cache with a 2% hit rate adds complexity for little gain; one with a 40% hit rate on a high-traffic assistant can cut LLM costs dramatically.
Key takeaways
- Cache at several layers: embeddings, provider prompt caching, retrieval results and answers.
- Put the index version, permission scope and prompt version in every key instead of deleting entries.
- Exact answer caches are safe for frequent standalone questions; never for conversational turns.
- Semantic caches are risky; use high thresholds, narrow scopes and audit logs.