# What Is Semantic Caching?

> How semantic caching reuses an AI answer for a question that means the same thing, where it goes wrong and how to keep it safe, for your AI interview.

**In short:** Semantic caching stores an AI answer and returns it again when a new question has a close enough meaning. The match comes from comparing numbers that stand for meaning, so it saves model calls, but a close-looking question can still get a wrong answer.

AI and LLM interview question Q325, Inference, performance and cost. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-semantic-caching

## Say it in 30 seconds

Semantic caching is a store of saved AI answers. When a new question means nearly the same as one already answered, the app returns the saved answer and skips the model call. It finds the match by comparing the meaning of the two questions. The risk is a false match, a question that looks alike but differs in one key detail, like flood or water damage. So I set a strict threshold, keep each saved answer inside its scope, and give every entry an expiry.

## Say it in 2 minutes

A claims assistant at a home insurer gets the same few questions again and again, written in many ways. "Is water damage from a burst pipe covered?" and "Does a burst pipe cover water damage?" mean the same thing. A normal cache only recognises identical text, so it misses the second one. A semantic cache turns each question into a list of numbers that stand for its meaning, then looks for a saved question with numbers close enough to match.

If the closest match passes the threshold, the saved answer comes back with no model call. If not, the model answers, and the new answer is saved. The saving adds up. In a made-up example of 4,000 questions a day, about 1,200 answered from the cache save close to 28 percent of the bill, after paying for every lookup.

The hard part is the match. "Is flood damage from a burst pipe covered?" shares most words with the water-damage question, and a loose threshold would return the wrong answer with confidence. A strict threshold misses true matches. Answers also go stale, so each entry needs an expiry, and answers built on live data, like a claim's current status, should never be cached. Scope matters too: one customer's answer must never reach another.

So I start strict, measure the wrong hits on real questions, and keep each cache inside its scope. It trades a small risk of a wrong answer for lower cost and faster replies.

## What is semantic caching, in plain words?

A cache is a store of answers you already worked out, so you can hand them back without doing the work again. A normal cache works on exact requests. A semantic cache works on meaning, so two differently worded questions can share one saved answer.

Picture a hospital triage nurse who has answered the same visiting-hours question all week. A visitor asks it in a new way, and she gives the same answer, because the question means the same thing. If the visitor asks about a different ward, she checks again.

An AI version works the same way. A home insurer's claims bot has answered "Is water damage from a burst pipe covered?" many times. When a customer asks "Does a burst pipe cover water damage?", the bot can return the saved answer with no model call.

- **Embedding:** A list of numbers that stands for the meaning of a piece of text. Similar meanings get similar numbers.
- **Similarity score:** A number that says how close two questions are in meaning. 1.00 means as alike as the score can show, and lower numbers mean less alike.
- **Threshold:** The score a match must reach before the saved answer is used. It is the main safety setting. Products differ: Azure's score-threshold works the other way round, so a lower value means a stricter match.
- **Scope:** Who a saved answer may serve, such as one customer, one product or one region.

## How does a semantic cache decide what to reuse?

Every request passes a short check before the model is called. OpenAI's embeddings guide says that 'text embeddings measure the relatedness of text strings.' So the check turns the question into numbers, finds the closest saved question, and compares that score with the threshold.

1. **Turn the question into an embedding:** An embedding model returns a list of numbers for the question's meaning.
2. **Find the closest saved question:** The new numbers are compared with the saved ones, and the closest match and its score are kept.
3. **Check the score against the threshold:** If the match is strict enough, the saved answer returns at once. If not, the request goes on to the model.
4. **Save the new answer:** After the model answers, the question and the answer are stored for the next similar question.

Microsoft's Azure guide describes the same two halves. One step checks the cache before the call, and the other stores the answer: 'one to check the cache before sending requests (lookup) and another to store responses for future reuse (store).' It says semantic caching can 'return cached responses for identical prompts and also for prompts that are similar in meaning'.

A 2024 paper, GPT Semantic Cache, applied this to LLM apps. It stored embeddings of queries in Redis, an in-memory store, and named customer service chatbots as a target: 'applications like customer service chatbots that handle repetitive queries.'

*Diagram, How a semantic cache answers: A new question is turned into numbers and compared with the saved questions. A close enough match returns the saved answer. Otherwise the model answers, and that answer is saved for next time.*
1. The question is turned into a list of numbers for its meaning.
2. The numbers are compared with the saved questions.
3. The closest saved question goes to the check, with its score.
4. Close enough: the saved answer comes back at once.
5. Not close enough: the question goes on to the model.
6. The model's answer is saved for the next similar question.

Worked example, with made-up numbers. A home insurer's claims bot gets 4,000 questions a day, and 1,200 of them match a saved answer closely enough. Say one model call costs 1 unit. Without a cache, the day costs 4,000 units. With one, the 2,800 misses cost 2,800 units, and the 4,000 lookups cost 0.02 units each, which adds 80. The total is 2,880 units, so the cache saves 1,120 units, about 28 percent. Every miss also pays for its lookup, so a cache that rarely hits can cost more than it saves.

## Where does a semantic cache go wrong?

The match is the weak point. Two questions can share most of their words and still differ in one detail that changes the answer. The code below runs a tiny version, with word counts standing in for an embedding model. It stores two saved answers and asks four questions.

```python
# A home insurer's claims bot. Word counts stand in for a real embedding model.
import math
from collections import Counter

SAVED = {
    "Is water damage from a burst pipe covered?": "Yes, under section 4. Report it within 7 days.",
    "Do you pay for lost luggage on a trip?": "Lost luggage is covered under travel cover only.",
}
THRESHOLD = 0.6

def vector(text):
    return Counter(text.lower().replace("?", "").split())

def similarity(a, b):
    va, vb = vector(a), vector(b)
    dot = sum(va[w] * vb[w] for w in va)
    return dot / (math.sqrt(sum(v * v for v in va.values())) * math.sqrt(sum(v * v for v in vb.values())))

def ask(question):
    best = max(SAVED, key=lambda saved: similarity(question, saved))
    score = similarity(question, best)
    if score >= THRESHOLD:
        return f"HIT  {score:.2f}: {SAVED[best]}"
    return f"MISS {score:.2f}: call the model"

print(ask("Is water damage from a burst pipe covered?"))
print(ask("Does a burst pipe cover water damage?"))
print(ask("Is flood damage from a burst pipe covered?"))
print(ask("Can I change my renewal date?"))
```

Output:

```text
HIT  1.00: Yes, under section 4. Report it within 7 days.
HIT  0.67: Yes, under section 4. Report it within 7 days.
HIT  0.87: Yes, under section 4. Report it within 7 days.
MISS 0.00: call the model
```

The first question is an exact repeat, so it hits. The paraphrase hits at 0.67. The flood question also hits, at 0.87, and returns the water-damage answer. That is a false hit: a confident, wrong answer that the customer trusts. In this word-count stand-in, the flood question scores higher than the paraphrase, so no threshold can accept one and refuse the other. A threshold of 0.9 would stop the flood question, but it would also send the paraphrase to the model. Real embedding models score differently, so teams tune the threshold on their own real questions, counting wrong hits as well as right ones.

- **Scope:** A saved answer about one customer's claim must never reach another customer. Azure's example splits its cache by subscription.
- **Expiry:** Policies change, so every entry needs an expiry time, and the cache is cleared when its source changes.
- **Live data:** Balances and claim status change often, so answers built on them should never be cached.
- **Chat context:** The same question can mean something else later in a chat. The lookup must include the earlier messages, or the cache can answer the wrong thing.

## How is it different from exact and prompt caching?

- **Exact cache: Same request, same answer.** Cloudflare's AI Gateway cache says it 'applies only to identical requests'. It cannot match a paraphrase, so it cannot give a wrong meaning match either.
- **Prompt cache: Same start, reused.** The provider keeps the processed start of a prompt. Anthropic's docs say a cache entry is 'a hash of the prefix ending at that block', a fingerprint of the text up to that point. The model still answers each new question.
- **Semantic cache: Similar meaning, saved answer.** It matches by meaning, so it can serve new wording. The cost is the risk of a wrong match, which the other two do not carry.

The three can run together. A prompt cache can cut the cost of a long policy text, while a semantic cache skips the model entirely for a repeat. Say which one you mean, because the names get mixed up in interviews.

### How would you add a semantic cache to a support bot safely?

A telecom's support bot gets the same billing and roaming questions thousands of times a day. This is the order I would work in.

1. **Cache only general answers:** Policy answers that are the same for every customer can be shared. Account questions stay out.
2. **Scope every entry:** Key each saved answer by product and region, and never share one entry between customers.
3. **Start strict and test:** Replay a set of real questions, count the wrong hits by hand, and only then loosen the threshold.
4. **Expire and clear:** Give each entry an expiry, and clear the cache on the day a policy changes.
5. **Watch the numbers:** Track hits, wrong hits, lookup time and cost, so a slow or wrong cache gets switched off.

> **Tip:** Asked what to leave out? Say account balances, a bill's current total and anything that changes during the day.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: reuse a saved answer when a new question means the same thing.
- [ ] How matching works: embeddings, the closest saved question, and a threshold.
- [ ] Where it goes wrong: false hits, and why a confident wrong answer is the worst case.
- [ ] Scope, expiry and live data: what must never be cached.
- [ ] How it differs from exact caching and prompt caching.
- [ ] How you would measure it: wrong hits first, then hits and cost.

**Common traps**

- Trap: "A higher threshold fixes it." Better: A strict threshold cuts wrong hits, but it also cuts true ones. Measure both on real questions.
- Trap: "It is a faster database, so it is always cheaper." Better: Each miss pays for an embedding and a lookup first. The saving depends on the hit rate.
- Trap: "Once cached, the answer can stay." Better: Policies change. Give each entry an expiry and clear it when its source changes.

## Can you spot the problem?

**Spot the problem:** A bank's assistant uses a semantic cache. Which saved answer should never be cached?

A. Card replacement takes 5 to 7 working days.
B. Your account balance is £2,340.10.
C. Branch opening hours are 9:30 to 16:00 on Saturdays.
D. To reset online banking, use the link on the sign-in page.

**Answer:** B. A balance changes often, so a cached one returns an old number with confidence. Cache the policy answers, and fetch account data live.

**Quick check:** The cache keeps giving the old excess (the sum a customer pays before insurance pays) after the insurer changed its policy. What is the first fix?

A. Raise the threshold so only very close matches are reused
B. Give each entry an expiry and clear the cache when the policy source changes
C. Add more saved answers
D. Switch to a bigger model

**Answer:** B. The problem is an old answer, so the fix is expiry and clearing on change. A stricter threshold, more saved answers or a bigger model will not fix an old answer.

## Can you answer these from memory?

**Flash cards**

- **What is semantic caching?** Reusing a saved answer when a new question means the same thing.
- **What does it compare?** The meaning of two questions, as embeddings: lists of numbers.
- **What is the main risk?** A false hit: a close-looking question gets the wrong saved answer.
- **What is the threshold?** The score a match must reach before the saved answer is used.
- **Can live data be cached?** No. Balances and claim status change, so the saved answer goes stale.
- **Exact cache vs semantic cache?** Exact matches identical requests. Semantic matches similar meaning, with wrong-hit risk.

## Likely follow-up questions

- Q326 Prompt cache vs semantic cache vs KV cache? https://designervenkat.online/interview/ai/prompt-cache-vs-semantic-cache-vs-kv-cache
- Q324 How do you estimate token cost for a feature? https://designervenkat.online/interview/ai/how-to-estimate-token-cost
- Q322 What is model routing (cascades)? https://designervenkat.online/interview/ai/what-is-model-routing
- Q334 How do you cut cost on a cloud-hosted LLM workload? https://designervenkat.online/interview/ai/how-do-you-cut-cost-on-a-cloud-hosted-llm-workload
- Q323 Small vs large model: how do you choose? https://designervenkat.online/interview/ai/small-vs-large-model
