Module 7 · AI infrastructureLesson 83 of 886 minAdvanced
Semantic caching
A semantic cache reuses an LLM's answer when a new question means the same thing as an old one, even if the words differ.
Watch which questions are served from the cache. Lower the similarity threshold and see the router question get the password answer.
LLM calls are slow (often seconds) and cost money per token. Many applications get the same questions over and over in different words. A normal cache keyed on the exact text would almost never hit.
How a semantic cache works
- Embed each incoming question.
- Search the cache (a small vector index) for the most similar earlier question.
- If the similarity is above a threshold, return the stored answer: a hit.
- Otherwise call the LLM, return its answer, and store the question embedding with the answer.
Choosing the threshold
- High (say 0.95): only near-identical questions hit. Safe, fewer savings.
- Low (say 0.8): more hits, but questions that look alike yet mean different things ("reset my password" vs "reset my router") may get wrong answers.
Tune it on real traffic, and check a sample of hits by hand.
Use it carefully
- Scope the cache: answers that depend on the user (their orders, their account) must not be shared across users. Include the user or tenant in the cache key, or don't cache those.
- Expire entries when the underlying facts change (prices, policies), with TTLs or invalidation like any cache.
- Combine with an exact-match cache in front, which is cheaper still.
- Works best for FAQ-style, high-repetition traffic; open-ended creative chat rarely repeats.
Related: prompt and prefix caching
Model providers and serving engines also cache the computation for repeated prompt prefixes (like a long system prompt), making repeated calls cheaper and faster even when answers aren't reused.