Calling a large language model (LLM) is relatively slow and relatively expensive. Each request may take hundreds of milliseconds to several seconds, and each one consumes tokens that cost money. Yet in many real applications the same or very similar questions arrive again and again: a documentation assistant fielding the same onboarding query, a support bot answering the same product question, a classification pipeline seeing repeated inputs. Caching is the technique of storing the result of an expensive operation so that future identical or similar requests can be served from the store instead of recomputed. For LLM workloads it can cut cost and latency substantially — if you understand its two main flavours and their trade-offs.
This article explains exact-match caching and semantic caching, how each decides whether a stored answer may be reused, the risks involved, and how to invalidate a cache so it does not serve stale or wrong results.
What a cache stores
At its core a cache is a key-value store with an eviction policy. You compute a key from the request, look it up, and either find a stored value (a cache hit, served instantly) or not (a cache miss, requiring the real computation, whose result you then store for next time). The hit rate — the fraction of requests served from cache — determines how much you save. The entire design problem is deciding when two requests should be considered "the same" for the purpose of reusing a result. The two approaches answer that question very differently.
Exact-match caching
Exact-match caching treats two requests as identical only if their inputs are byte-for-byte the same. You build a deterministic key from the parts of the request that affect the output, hash it, and use that as the lookup key. For an LLM call the relevant parts typically include the model name, the full prompt or message list, and any parameters that change the output such as temperature and max tokens.
import hashlib
import json
def cache_key(model, messages, params):
Canonicalise so logically identical requests hash identically:
Fixed key order, no incidental whitespace differences.
payload = {
"model": model,
"messages": messages,
"params": {k: params[k] for k in sorted(params)},
}
blob = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return "llm:" + hashlib.sha256(blob.encode("utf-8")).hexdigest()
The subtlety is canonicalisation. If your key is sensitive to incidental differences — a trailing space, a different ordering of JSON fields, a reordered set of parameters — then logically identical requests produce different keys and miss the cache. Sorting keys, trimming whitespace, and normalising the payload before hashing all raise the hit rate. Conversely, you must include everything that genuinely changes the output; omit the temperature and you might serve a deterministic cached answer for a request that asked for a creative, high-temperature one.
Exact-match caching has excellent properties: it is simple, fast, and correct by construction. A hit means the inputs were truly identical, so the stored answer is exactly what the model would have returned. Its weakness is brittleness. Natural language is endlessly variable. "What is your refund policy?" and "How do refunds work?" mean the same thing but share almost no characters, so exact-match caching treats them as entirely different and caches them separately. For free-form user input, hit rates can be disappointingly low.
Semantic caching
Semantic caching aims to fix that brittleness by matching on meaning rather than exact text. Instead of hashing the prompt, it converts the prompt into an embedding — a numeric vector that represents its meaning — and stores that vector alongside the answer. For a new request, it embeds the incoming prompt and searches for stored vectors that are close to it in vector space. Closeness is usually measured with cosine similarity. If the nearest stored prompt is similar enough — above a chosen threshold — its cached answer is reused.
The payoff is a much higher potential hit rate on natural-language workloads, because paraphrases and reworded questions can now hit the same cache entry. "How do refunds work?" can retrieve the answer originally computed for "What is your refund policy?" The mechanism is essentially a nearest-neighbour search over embeddings, often backed by a vector database for efficiency at scale.
But semantic caching trades correctness-by-construction for a tunable judgement call, and that introduces real risk. The similarity threshold is the critical dial:
- Set it too low (loose matching) and the cache returns answers for questions that are related but not actually equivalent. "How do I cancel my subscription?" might wrongly retrieve the answer to "How do I upgrade my subscription?" — a false positive that serves a confidently wrong answer.
- Set it too high (strict matching) and only near-identical phrasings hit, eroding the advantage over exact-match caching.
Because a semantic hit is a judgement that two different texts mean the same thing, it can be wrong in ways an exact-match hit never can. That makes semantic caching well suited to tolerant use cases — FAQ-style answers, suggestions, non-critical lookups — and risky for cases where a subtly different question demands a genuinely different answer. Many teams combine the approaches: check the exact-match cache first for a guaranteed-correct fast path, and fall back to semantic matching for the long tail of paraphrases.
Invalidation: the hard part
There is an old joke that the two hardest problems in computing are naming things, cache invalidation, and off-by-one errors. Invalidation — deciding when a stored answer is no longer valid and must be discarded — is genuinely the hardest part of caching, and it matters acutely for LLMs because the underlying truth can change.
Suppose your refund policy changes. Every cached answer about refunds is now stale and potentially harmful, yet the cache has no idea the world moved. Common invalidation strategies include:
Time-to-live (TTL): each entry expires after a set duration. Simple and robust; the trade-off is that a short TTL lowers hit rates while a long one risks serving stale answers for longer.
Explicit invalidation: when source data changes, actively delete or mark affected entries. Precise but requires wiring your content updates to your cache.
Versioned keys: include a version or content hash of the underlying knowledge in the cache key, so that updating the source naturally produces new keys and orphans the old entries.
A further LLM-specific consideration is what you must not cache. Prompts containing personal or sensitive data need careful handling, and responses that are meant to be fresh each time — anything personalised or time-dependent — should bypass the cache entirely. Deciding what is cacheable is as much a correctness and privacy decision as a performance one.
Measuring whether a cache is worth it
A cache is not free. It adds a lookup on every request, consumes storage, and — for semantic caching — spends an embedding computation and a vector search before it even knows whether it has a hit. Whether it pays off depends on the arithmetic of your particular workload, and it is worth doing that arithmetic rather than assuming a cache always helps.
The headline metric is the hit rate: the fraction of requests served from the store. A cache with a 5 percent hit rate on a workload of mostly unique prompts may cost more in overhead than it saves. A cache with a 60 percent hit rate on a repetitive FAQ workload can slash both the bill and the average latency. Alongside the hit rate, watch the cost of a miss: for semantic caching, every miss still paid for an embedding and a search, so a low hit rate is doubly wasteful. It also helps to track the staleness rate — how often the cache served an answer that your invalidation strategy should have removed — because that number is the honest measure of the correctness risk you are carrying. A cache that saves money but occasionally serves a wrong or outdated answer may be a bad trade for a high-stakes application and a perfectly good one for a low-stakes suggestion feature. Deciding that trade-off deliberately, with numbers, is the difference between a cache that quietly helps and one that quietly hurts.
Where a gateway fits in
Because caching logic — key construction, embedding and similarity search, TTLs, and invalidation — is non-trivial and identical across many applications, response caching is frequently implemented at an AI gateway that sits between applications and model providers. Placing the cache there means every service routing through the gateway benefits from the same hit rate without each team building its own cache, and cache policy becomes a single configurable layer rather than scattered code. A shared cache also raises hit rates, since requests from different applications that happen to be identical or semantically similar can serve one another. Centralising it additionally makes cache behaviour observable — hit rates, savings, and staleness can be monitored in one place.
Key takeaways
- Caching serves repeated LLM requests from a store instead of recomputing them, cutting both cost and latency; the hit rate drives the savings.
- Exact-match caching keys on byte-identical inputs: it is simple and correct by construction but brittle against paraphrasing. Canonicalise inputs to raise hit rates.
- Semantic caching matches on meaning via embeddings and similarity search, raising hit rates on natural language but risking false positives.
- The similarity threshold is the critical dial: too loose returns wrong answers, too strict erodes the benefit. Combining exact-match first with semantic fallback is common.
- Invalidation — via TTLs, explicit deletion, or versioned keys — is the hardest and most important part, and some requests (personalised or sensitive) should not be cached at all.
- Caching is often implemented at an AI gateway so many applications share one observable, configurable cache rather than each building their own.
Top comments (0)