Katkat

Semantic Caching for LLM Applications

By the Katkat team · Updated · 9 min read

Quick overview

Learn how exact and embedding-similarity LLM caches work, how to pick thresholds, invalidate entries, and avoid wrong or leaked cached answers.

Lesson 24 of 88 · AI Engineering Interview Course

After this lesson you should be able to explain how an exact-match cache and an embedding-similarity ("semantic") cache differ, and how a similarity threshold trades savings against wrong answers. You should also be able to describe how to invalidate entries and name the correctness and security risks that make semantic caching harder than it looks. Interviewers use this topic to check whether you can cut cost and latency without quietly degrading answer quality.

What a cache in front of an LLM does

An LLM call is slow (seconds) and costs money per token. If many users ask the same thing, you can store the answer once and return it on later requests. This is a response cache: the stored value is the finished model output, and a hit skips the model call entirely.

The simplest version is an exact cache:

  1. Build a key from the request: normalised prompt text, model ID, system prompt version, and generation parameters.
  2. Hash the key and look it up in a key-value store such as Redis or a database table.
  3. On a hit, return the stored answer. On a miss, call the model, then store the result with a time-to-live (TTL).

Exact caching is cheap, fast (a sub-millisecond to a few milliseconds lookup, depending on your store), and never returns an answer for a different question. Its weakness is that natural language rarely repeats byte for byte. "How do I reset my password?" and "how can i reset my password" miss each other unless you normalise aggressively, and even then paraphrases miss. Exact caches work well for programmatic traffic (the same templated prompt, the same document being summarised) and poorly for free-form chat.

How a semantic cache works

A semantic cache replaces "same string" with "close enough in meaning". The mechanism:

  1. Embed the incoming query with an embedding model (see Embeddings: Representing Text as Vectors).
  2. Search a vector index of previously seen queries for the nearest neighbour (see Vector Search: HNSW, IVF and Approximate Nearest Neighbours).
  3. If the cosine similarity of the best match is at or above a threshold, return the cached answer stored with that neighbour.
  4. Otherwise call the LLM, then insert the new query embedding and its answer into the index.

Two details matter. First, you compare the new query against cached queries, not against answers. Second, each entry should carry metadata: tenant, model, prompt version, corpus version, creation time, and a hit counter. The metadata is what lets you filter and invalidate later.

A common production design is tiered: exact cache first (cheap, safe), semantic cache second, LLM last. The semantic lookup adds an embedding call plus a vector search to every request that misses the exact tier, so it must be fast relative to the model call.

Where it sits among other caches

Semantic caching is often confused with provider-side prompt caching. They solve different problems.

Cache typeWhat is storedMatch ruleSkips the model call?Main risk
Exact response cacheFinal answerIdentical keyYesLow hit rate on free text
Semantic response cacheFinal answerEmbedding similarity above thresholdYesWrong answer for a similar-looking question
Prompt/prefix cacheComputed attention state for a shared prompt prefixIdentical token prefixNo, the model still generatesLittle; only a pricing and latency effect

A prefix cache reuses computation for a repeated prompt start (for example a long system prompt) but still generates a fresh answer, so it is safe for correctness. A semantic cache reuses the answer itself. See Prefix Caching for the serving-side view. The two combine well: prefix caching speeds up the misses that semantic caching lets through.

Choosing the threshold

The threshold is the single most important knob. Cosine similarity ranges from -1 to 1, and for typical text embedding models, paraphrases score high, but so do many pairs that differ in one crucial detail. Raw score values depend on the embedding model, so a threshold of 0.9 means different things across models. Never copy a number from a blog post; calibrate it.

  • Too low: high hit rate, but users get answers to a different question (false hits).
  • Too high: few false hits, but the cache rarely fires and saves little.

Calibration procedure:

  1. Sample real queries and find, for each, its nearest earlier query.
  2. Have humans (or a carefully validated LLM judge, see LLM Evaluation and LLM-as-a-Judge) label whether the cached answer would be acceptable for the new query.
  3. Plot precision (fraction of hits that are acceptable) and hit rate at several thresholds.
  4. Choose the threshold where precision meets your quality bar, which may be stricter for high-stakes categories.

Practical refinements: use different thresholds per intent category (FAQ vs account questions), and add a verification step on candidate hits, such as a cross-encoder or a small model asking "do these two questions have the same answer?". Verification costs latency, so apply it only to borderline scores.

Worked example: savings, latency and false hits

Assumptions (hypothetical prices, chosen for easy arithmetic): 100,000 requests per day; each uncached call uses 1,000 input tokens and 300 output tokens; input costs $2 per million tokens and output costs $8 per million.

  • Cost per call: 1,000 × $2 / 1,000,000 = $0.002 input, plus 300 × $8 / 1,000,000 = $0.0024 output, total $0.0044.
  • Daily cost with no cache: 100,000 × $0.0044 = $440.
  • Embedding overhead: about 20 tokens per query × 100,000 = 2,000,000 tokens. At a hypothetical $0.02 per million, that is $0.04 per day, negligible. The real overhead is vector-store infrastructure and added latency.

Now compare two thresholds using illustrative calibration results:

SettingHit rateHits per dayDaily savingWrong-answer rate among hitsWrong answers per day
Threshold A (looser)25%25,00025,000 × $0.0044 = $1102%500
Threshold B (stricter)15%15,00015,000 × $0.0044 = $660.3%45

Moving from A to B gives up $44 per day in savings but removes 455 wrong answers per day. Whether that is a good trade depends on the product, but for most customer-facing use it is.

Latency, assuming a 40 ms cache lookup on every request and a 3,000 ms model call on a miss:

  • A hit costs 40 ms; a miss costs 40 + 3,000 = 3,040 ms.
  • Threshold A: 0.25 × 40 + 0.75 × 3,040 = 10 + 2,280 = 2,290 ms mean, versus 3,000 ms with no cache.
  • Threshold B: 0.15 × 40 + 0.85 × 3,040 = 6 + 2,584 = 2,590 ms mean.

Note that the mean improves modestly, but p50 latency may drop sharply if the hit rate exceeds 50%, while p95 latency is set by misses and gets slightly worse because of the lookup. Cache wins show up most in cost and in median latency for repetitive traffic.

Invalidation and cache keys

"There are only two hard things in computer science" applies here. A cached answer is valid only as long as everything that produced it is unchanged. Handle this with three mechanisms:

  • Scoped keys. Store, and filter on, the model ID, system prompt version, tool set, and generation settings. Change any of them and old entries should not match. This is the same idea as versioning in Versioning and Rolling Out Prompts and Models.
  • TTL. Give every entry an expiry matched to how fast the underlying facts change: hours for pricing or stock information, days or weeks for stable documentation.
  • Event-based invalidation. For RAG systems, tag each entry with the IDs of the source documents or a corpus version. When a document is updated or deleted, evict entries that depend on it. Without this, the cache can serve answers based on a policy that no longer exists.

Also plan for embedding-model upgrades: vectors from different models are not comparable, so changing the embedding model means rebuilding or discarding the whole index.

Correctness and security risks

Semantic caching changes behaviour, not just performance. Know these failure modes:

  • Near-miss paraphrases. "Cancel my subscription" and "cancel my subscription after the free trial" embed close together but may need different answers. Numbers, negations, dates, names and order IDs are especially risky because embeddings blur them.
  • Context dependence. In a multi-turn chat, "what about the second one?" is meaningless without history. Cache only on a self-contained query (for example after query rewriting), or skip caching for turns that depend on conversation state (see Conversation Memory for Chat Applications).
  • Personalised or private data. If an answer includes one user's account details and is returned to another, that is a data leak. Partition the cache by tenant or user, and never cache responses produced from private context unless the key includes that scope.
  • Time-sensitive answers. "What's the status of the outage?" must not be served from yesterday.
  • Cache poisoning. If an attacker can get a malicious or incorrect answer stored (including via prompt injection) and then trigger hits on similar queries, it spreads to other users. Cache only answers that passed output checks, and see Prompt Injection and Guardrails.
  • Sampling variance. A cache freezes one sampled answer. If your product expects varied outputs (creative writing) or you use high temperature (see Decoding: Greedy, Temperature, Top-k and Top-p), caching changes the experience. It suits deterministic, factual workloads best.

Mitigations in practice: an allowlist of cacheable intents, shadow mode before launch (log what the cache would have returned and judge it, without serving it), a per-hit feedback signal such as thumbs-down that evicts the entry, and monitoring of hit rate and false-hit rate over time.

How does this come up in interviews?

1. How does a semantic cache differ from an exact cache, and when would you use each? An exact cache keys on a normalised hash of the request and only matches identical inputs, so it is safe and fast but has a low hit rate on free text. A semantic cache embeds the query and matches on vector similarity, raising hit rate at the risk of returning an answer to a different question. Use exact for templated or programmatic traffic, and semantic for repetitive, self-contained, non-personalised queries such as FAQs, usually behind an exact tier.

2. How would you choose the similarity threshold? Build a labelled set of query pairs from real traffic, label whether the cached answer is acceptable, and measure precision and hit rate at several thresholds. Pick the point that meets the quality bar, and consider per-category thresholds or a verification step for borderline scores. Emphasise that the number is specific to the embedding model and must be recalibrated if it changes.

3. Your support bot's semantic cache gave a user the wrong refund policy. What happened and how do you fix it? Likely causes are a false hit on a near-paraphrase with different details, or a stale entry after the policy changed. Check the similarity score and the matched query, then tighten the threshold or add verification for that intent, and add document-version tags so policy updates evict dependent entries. Add the incident as a regression case in your evaluation set.

4. Is it safe to cache answers in a multi-tenant app? Only if entries are scoped. Include the tenant (and user, when answers use personal data) in the key or as a mandatory metadata filter on the vector search, so one customer's answer can never match another's query. Exclude responses built from private context unless that scope is part of the key.

5. Where does caching fit in a plan to cut LLM cost or latency? It is one lever alongside model routing, prompt trimming and prefix caching. Quantify it: hit rate × cost per call gives the saving, minus lookup overhead and the cost of wrong answers. See How Would You Cut LLM Costs by 10x? for the broader framing.

Common mistakes

  • Treating the threshold as a universal constant instead of calibrating it on labelled data for your embedding model and domain.
  • Reporting hit rate as the success metric without measuring false-hit rate.
  • Matching on the whole multi-turn conversation, or on a context-dependent follow-up, rather than a self-contained query.
  • Omitting model, prompt version and corpus version from the cache scope, so entries survive changes that should invalidate them.
  • Sharing one cache across tenants or caching answers built from personal data.
  • Forgetting that a cache freezes one sampled output, which is wrong for products that need varied answers.
  • Confusing semantic caching with provider-side prompt caching; the latter reuses computation, not answers.
  • Ignoring the latency of the lookup itself, which is paid on every miss.
  • Never evicting: no TTL, no event-based invalidation, no feedback loop from user complaints.