Users ask the same few hundred questions in a million different sentences. A semantic cache serves a stored answer when the meaning matches. With only a similarity threshold it can serve 91 wrong answers in every 1,000 requests; with two guards, about 1.
Choose a cache and drag the threshold. Each dot is one request: green is a correct cached answer, red is a wrong one, purple is a fresh generation. Then we build, piece by piece, the loop, the threshold, calibration, guards, invalidation, keys, the money and the dashboard.
You need a little Python and the idea that a model can turn a sentence into a list of numbers. We build the rest from zero.
Illustrative support traffic built for this page: three populations of cosine scores (Chapter 4) and assumed guard rates (Chapter 5). Prices are illustrative: $3 per million input and $15 per million output tokens.
Chapter 0
Price one request, then count how many of a month’s answers were new
You run a support assistant. Last month it served 1,200,000 requests. Finance asks if the model bill is right. It is. The better question is how many of those answers were new.
How much does one request cost? Call the input tokens sent nin and the price of one input token pin. Call the output tokens returned nout and their price pout. Call the cost of one generation Cgen.
C-gen equals n-in times p-in, plus n-out times p-out.
Multiply the input tokens n-in by their price p-in. Multiply the output tokens n-out by their price p-out. Add the two. That is C-gen.
With illustrative prices: n-in = 1,800 at $3 per million, n-out = 350 at $15 per million. C-gen = $0.00540 + $0.00525 = $0.01065. Times 1,200,000 requests: $12,780 a month.
Now label a sample of the logs by intent: two requests share an intent if one stored answer serves both. Human questions follow a steep curve. A few questions take most of the traffic.
| Slice | Distinct intents | Requests | Share |
|---|---|---|---|
| Head | 200 | 480,000 | 40% |
| Body | 12,000 | 420,000 | 35% |
| Tail | 214,000 | 300,000 | 25% |
Each head question ran 2,400 times from scratch. A perfect cache on the head saves 480,000 − 200 = 479,800 generations, 40% of traffic. That is a ceiling, not a promise.
You already have an exact-match cache: hash the request string and look it up. The head’s 480,000 requests arrive as 310,000 distinct strings, because people type “reset pw”, “forgot my password” and “how do I reset my password?”. Each string misses once, so the head gives only 170,000 hits.
The slider sets how many different strings each head intent is typed as. Watch the exact-match bar shrink while the meaning ceiling stays put.
Illustrative logs. Exact hits on the head = 480,000 − 200 × strings per intent. Your logs sit at 1,550.
A semantic cache keys on meaning instead of spelling. It turns the question into a vector and serves a stored answer whose question is close enough. The risk is the other half of language: two questions can share nearly every word and need opposite answers.
The failure. Symptom: someone adds stop-word removal to the exact cache, and “how do I NOT reset my password” collides with “how do I reset my password”. Measure: list every pair of different strings that now share a key. Fix: string rules cannot express meaning, so move to vectors and keep a guard for words like “not”.
Chapter 1
Walk one request through the four steps with its shapes and milliseconds
Every semantic cache runs the same four steps:
Pick an incoming question. The stored question is “how do I reset my password”. Press Step to run each stage and watch the milliseconds add up.
Illustrative timings for a small CPU embedder and an HNSW index of 214,000 entries; the threshold here is 0.93. The first three cosines come from the four-number toy below; the fourth is illustrative.
How close is close? Call the incoming question’s vector a and a stored question’s vector b. The score is the cosine similarity, the cosine of the angle between the arrows.
Cos of a and b equals a dot b, over the length of a times the length of b.
Multiply a and b number by number and add. Divide by both lengths so only direction counts. If you scale every vector to length 1 when you store it, the score is a dot b alone.
With made-up four-number vectors: a = (3, 4, 0, 0), length 5. The paraphrase b = (4, 3, 1, 0), length 5.099. a · b = 12 + 12 = 24, so cos = 24 / 25.50 = 0.941. The API-key question d = (2, 4, 3, 0) scores 22 / 26.93 = 0.817.
Store each entry as one row. It holds the vector, the question, the answer and the time. It also holds the embedder and its revision, the generator, the prompt hash and the document ids. Chapters 6 and 7 need every field.
| Path | What runs | Time |
|---|---|---|
| Hit | embed 6 + search 1.8 + verify 4 + fetch 0.8 | 12.6 ms |
| Miss | embed 6 + search 1.8, then generate 2,600 | 2,607.8 ms |
| Miss overhead | 7.8 ms spent to learn there is no hit | 0.3% of a generation |
The failure. Symptom: many different queries return the same long stored question. Measure: print the norms of a few stored vectors; they are not 1. Fix: normalise on both paths. An index that ranks by raw dot product favours long vectors.
Chapter 2
Tell semantic caching apart from exact, prompt and KV caching, and stack them
“Cache” names four different things in an LLM stack. They match on different keys. Only one of them can serve a wrong answer.
| Cache | Matches on | What a hit saves | Can a hit be wrong? |
|---|---|---|---|
| Exact response cache | the whole request, byte for byte | the whole generation | no, unless the facts went stale |
| Provider prompt cache | an identical prompt prefix | part of the input price and time | no: the model still generates |
| KV cache | the tokens of the current generation | recomputing attention for earlier tokens | no: it is inside one model call |
| Semantic cache | meaning, by a similarity score | the whole generation | yes |
A KV cache keeps the attention keys and values of tokens already processed, so each new token reuses them. It lives inside one generation. A prompt cache stores that state for a shared prefix across requests. Anthropic’s docs say a hit needs “100 percent identical prompt segments” up to the marked block.
The model answered request A a minute ago. Pick request B. Each bar is a prompt: system prompt, retrieved documents, question. Teal marks the prefix B shares with A.
Token counts and prices are illustrative. Cache reads at 0.1 times the input price follow Anthropic’s prompt caching page (checked 2026-11-22); cache writes cost more and are left out here.
Prompt caching changes the input price. Call the cached prefix tokens nc and the rest nnew. With reads at a tenth of p-in:
The caches stack. Turn on exact and prompt caching first: they are cheap and never wrong. Size the semantic cache after, because prompt caching cuts Cgen by 38% and so cuts what each semantic hit saves.
The failure. Symptom: the prompt cache hit rate drops to zero after a release. Measure: diff the first lines of the system prompt; a timestamp or user name sits at the top. Fix: put fixed text first and per-request text last.
Chapter 3
Name the two errors, then watch a stricter threshold make precision worse
Someone writes THRESHOLD = 0.92. It does not mean “92% the same”. Sentence encoders squeeze most pairs into a narrow band near the top. In the toy traffic below, two unrelated questions already score 0.681.
Two errors matter. A false miss is a correct stored answer that the cache did not serve: it costs one generation. A false hit is a stored answer served to a question it does not answer. The user gets a wrong answer in 12 ms, in a confident tone.
Each dot is a pair: an incoming question and its nearest stored one. Green pairs share an answer; pink pairs do not. The cache serves everything right of τ. Find a τ that serves only green.
Illustrative scores, chosen to show the pattern; real scores depend on your model and traffic. Measure your own.
Score a threshold by the share of served answers that are right. Call the correct hits TP (true positives) and the wrong hits FP (false positives).
Precision equals TP over TP plus FP.
Count the served pairs that are right, TP. Count the served pairs that are wrong, FP. Divide TP by their sum.
At τ = 0.92 the device serves 9 pairs: TP = 5, FP = 4, so precision = 5 / 9 = 0.556. At τ = 0.97 it serves 3: TP = 1, FP = 2, precision = 0.333. The stricter line is worse.
Recall is the other side: correct hits divided by all pairs that should hit, TP / 5 here. At 0.92 it is 1.0; at 0.97 it is 0.2.
Why do the worst pairs score highest? A retrieval encoder learns to put a question near the page that answers it. “Enable 2FA” and “disable 2FA” are answered by one help page, so they land side by side. An embedding squeezes out short words like “not”; that is right for retrieval and wrong for a cache.
The failure. Symptom: a user asks how to disable 2FA and gets the steps to enable it, in 11 ms, logged as a successful hit. Measure: ask a pair and its negation and diff the answers. Fix: a guard that reads both questions (Chapter 5), not a higher τ.
Chapter 4
Label 4,000 requests, fit three populations, and sweep the threshold
Twelve pairs show the pattern. They cannot set τ. For that, build a labelled set from your traffic:
The labels split into three groups. Positives have a correct stored answer. Easy negatives have a loosely related neighbour. Hard negatives are minimal edits: a negation, an entity swap, “per year”.
| Group | Count | Mean cosine μ | Spread σ |
|---|---|---|---|
| Positives | 1,600 | 0.945 | 0.025 |
| Easy negatives | 2,050 | 0.780 | 0.060 |
| Hard negatives | 350 | 0.960 | 0.020 |
The hard negatives’ mean, 0.960, is above the positives’ 0.945. No single line can split two groups when the wrong one sits on top.
What share of a group clears τ? Model each group’s scores as a bell curve with mean μ (mu) and spread σ (sigma). Call Φ (phi) the bell curve’s table: the share of a standard bell curve below a value.
The share above tau equals phi of mu minus tau, over sigma.
Count how many spreads sigma the mean mu sits above tau. Look that number up in the table phi. That is the share of the group the cache serves.
At τ = 0.92, positives: (0.945 − 0.92) / 0.025 = 1, Φ(1) = 0.841, so 1,346 hits. Hard negatives: (0.96 − 0.92) / 0.02 = 2, Φ(2) = 0.977, so 342 false hits. Easy negatives add 20. Precision = 1,346 / 1,708 = 78.8%.
Green is positives, yellow easy negatives, pink hard negatives. Shaded area right of τ is served. Drag τ, then set hard negatives to zero.
Illustrative labelled set of 4,000 requests; bell curves stand in for the real histograms.
| τ | Precision | Recall | Hit rate | Wrong / all traffic |
|---|---|---|---|---|
| 0.88 | 78.0% | 99.5% | 51.0% | 11.2% |
| 0.92 | 78.8% | 84.1% | 42.7% | 9.1% |
| 0.94 | 75.4% | 57.9% | 30.7% | 7.6% |
| 0.97 | 69.9% | 15.9% | 9.1% | 2.7% |
| 0.99 | 70.7% | 3.6% | 2.0% | 0.6% |
Precision stays between 69% and 80% across the whole sweep. τ trades hits for hits. It does not buy safety.
The failure. Symptom: offline numbers look better than production. Measure: check whether step 2 built the index from entries newer than the request. Fix: rebuild the index as of each request’s timestamp, or the future leaks into the past.
Chapter 5
Put two cheap checks behind the threshold and choose from a written budget
The threshold cannot see “not”. Two checks can. Both run only on candidates that already passed τ.
Guard 1, the decision-token check. Keep a set of words that flip answers in your product. It holds negations (not, never), polarity verbs (enable, disable), platforms, plans, periods and every number. If the two questions differ on any of them, refuse the hit. It costs a set lookup.
Guard 2, the cross-encoder. An embedding model is a bi-encoder: it reads each sentence alone and squeezes it into one vector. A cross-encoder reads both sentences in one pass, so its attention sees “enable” next to “disable”. It is too slow to run against 214,000 entries, but fine on one candidate.
Bars count candidates out of 4,000 labelled requests after each stage. Toggle each guard and pick a budget for wrong answers.
Assumed guard rates, illustrative: the token guard rejects 88% of hard-negative hits, 20% of easy-negative hits and 3% of true hits; the cross-encoder catches 92% of the false hits left and costs 7% of true hits.
Work it at τ = 0.93. The threshold passes 1,161 true hits and 339 false ones. The token guard keeps 97% of true and removes most hard negatives. The cross-encoder keeps 8% of what is left wrong:
Compare: threshold only at 0.92 gave 91 wrong per 1,000. The guards cut that by about 90 times and keep two thirds of the hits. The cross-encoder runs on 29% of requests, so it adds 0.29 × 4 ms = 1.2 ms on average.
Choose from a budget written before you look: “at most F wrong answers per 1,000 requests.” Then take the highest hit rate that meets it. Medical, legal and financial advice get no semantic cache at all.
The failure. Symptom: “turn off 2FA” never hits “disable 2FA”. Measure: sample the true hits the token guard rejects. Fix: map synonyms to one decision token, so off and disable count as one word.
Chapter 6
Price a time-to-live, version the producers, and delete by document
Three weeks after launch, the Pro plan price changes. The stored answer still says $29 a month, and it will say so until something deletes it. A stored answer goes bad for three reasons:
| What changed | Example | Fix |
|---|---|---|
| The facts | a price, a policy | a time-to-live per content class |
| The producer | the embedder, the generator, the system prompt | put their versions in the namespace |
| The evidence | a retrieved document was edited | delete the entries built from it |
A time-to-live (TTL) deletes an entry L days after it was written. Suppose the fact behind an answer changes at random, on average once every T days, so at rate λ (lambda) = 1/T per day. Then the share of served answers that are stale is:
Stale equals one minus, one minus e to the minus lambda L, over lambda L.
An entry of age t is stale with chance 1 minus e to the minus lambda t. Average that over its life from 0 to L, assuming hits spread evenly. Short L relative to T gives a small stale share.
Pricing changes six times a year: T = 60.8 days, λ = 0.0164. With L = 7, λL = 0.115 and stale = 1 − 0.1088 / 0.1151 = 5.5%. With L = 1, stale = 0.8%.
What does a shorter TTL cost in hits? Call an intent’s requests per day r. After a miss writes an entry, it lives L days and collects about r·L hits. The next request after it expires is the miss that writes it again.
h equals r L, over one plus r L.
Each cycle has one miss and about r times L hits. Divide the hits by everything in the cycle.
A head intent, r = 400: with L = 1, h = 400 / 401 = 99.75%; with L = 7, 99.96%. A cold intent, r = 0.5: with L = 1, h = 0.5 / 1.5 = 33%.
Red is the stale share; green is the hit rate. Move the intent’s traffic and watch only the green curve shift. Then drag the TTL.
Assumes random (Poisson) requests and fact changes, and no refresh of the TTL on a hit. Illustrative rates.
Short TTLs are nearly free on the head and fatal on the tail. Set them by content class: pricing an hour, policy a day, how-to a week.
A TTL cannot see the other two reasons. Put the producer versions into the namespace: embedder and revision, generator, prompt hash, corpus snapshot. Any change then makes every lookup miss. For documents, keep a map from each document to the entries built from it, and delete them when it changes.
The failure. Symptom: support fixes the refund policy at 09:14 and the bot quotes the old one all day. Measure: a canary fact in a document you control, polled every 15 minutes. Fix: delete by document provenance, not only by age.
Chapter 7
Put answer-changing context in a namespace, and pay the partition tax
Two users type “can i export my data to csv” one second apart. One is on Enterprise, on iOS. One is on Free, on the web. The cosine is exactly 1.000, and the correct answers differ. No threshold or verifier can split them, because the difference is not in the text.
The rule: anything that changes the answer and is not in the question goes in the key. The key becomes a namespace, a partition id computed from context, and search runs inside one namespace.
| Field | In the key? | Why |
|---|---|---|
| Locale | yes | currency, legal text |
| Plan | often, or template it | entitlements change the answer |
| Platform | if answers give UI steps | “tap” versus “click” |
| Prompt and tool versions | always | they change every answer |
| Tenant or user id | no: refuse to cache private answers | it deletes the cache |
| Request id, timestamp | never | unique, so nothing ever hits |
Each field divides an intent’s traffic among N namespaces, so each sees r / N requests a day. Put that into Chapter 6’s hit rate:
Toggle the fields you put in the key. The bar shows the namespace count on a log scale; the read-out shows the head intent’s hit rate. Then turn on tenant.
One-day TTL, random arrivals, traffic spread evenly over namespaces. Illustrative field counts.
Two tricks reduce the tax. Templating: if Free and Pro answers differ only by a number, store “Your plan allows {{rate_limit}} requests per minute” once and fill the slot per request. Dropping plan takes 72 namespaces to 18 and the head intent from 84.7% to 95.7%. Rewriting: cache the standalone question your RAG step already writes, so “and the second one?” becomes a shared head question.
The failure. Symptom: a user asks to summarise “my last invoice” and sees someone else’s. Measure: a CI test that asks the same question as two tenants and diffs the answers. Fix: never write an answer whose retrieval touched private data, called a tool, or contains personal data.
Chapter 8
Find the break-even hit rate, then place the cache where its failure is harmless
Every request pays for a lookup. Only a hit saves a generation. Call the lookup cost clook: about 22 tokens to an embedding API at an illustrative $0.02 per million, so $0.00000044. Call the hit rate h. The cache wins when the hits save more than all the lookups cost.
h-star equals c-look over C-gen.
The cache saves h times C-gen per request and costs c-look. Set them equal and solve for h. Use milliseconds in place of dollars for the latency break-even.
h* = $0.00000044 / $0.01065 = 0.004%, one hit in 24,200 requests. For latency: 7.8 ms / 2,600 ms = 0.3%. With fixed costs of $110 a month on 1,200,000 requests: h* = 110 / 12,780 = 0.86%.
Purple is the bill with no cache. Teal is the bill with the cache, including its fixed cost. Drag the volume down until the lines meet at your hit rate.
Illustrative: C-gen $0.01065, fixed cost a small instance plus Redis. Build cost and prompt caching are not in the plot.
At 26.3%: 1,200,000 × 0.263 × $0.01065 = $3,361 saved, $3,251 net a month. Three engineer-days at about $3,600 pay back in 1.1 months. At 50,000 requests a month the saving is $140, and the build never pays back.
Latency needs care. The mean falls: 0.263 × 12.6 + 0.737 × 2,607.8 = 1,925 ms, 26% below 2,600. The median does not move, because the 50th percentile still lands among the misses. A cache moves the median only once its hit rate passes 50%.
Where does the cache live? Cache-aside: your app embeds, searches and falls back to the model. Read-through: a proxy speaks the model API in between. Choose cache-aside. If the cache dies or slows past a 25 ms timeout, the app calls the model as before. A dead proxy is an outage.
The failure. Symptom: a viral question costs 130 identical generations in 2.6 seconds (50 per second × 2.6 s). Measure: count concurrent generations per namespace. Fix: singleflight, one lock per question bucket; the first miss generates and the rest wait, with a timeout.
Chapter 9
Buy a production false-hit rate with shadow samples and chart it next to the hit rate
The usual cache dashboard shows hit rate and dollars saved. Both rise when you lower τ. Both rise when the cache serves wrong answers. You need the false-hit rate, and in production nobody labels it for you.
So buy it. On 2% of hits, serve the cached answer as normal. Then generate the real answer in the background and ask a judge: “Is the served answer correct and complete for this question?” This is shadow sampling. The user waits for nothing.
How sure is a rate from n samples? Call the true rate p and the sample count n. The standard error SE is the typical distance between the measured rate and p.
SE equals the square root of p times one minus p, over n.
Multiply p by 1 minus p. Divide by the sample count n. Take the square root. A band of two SE either side of the measured rate holds the true rate most of the time.
p = 0.001 and n = 6,312: SE = √(0.000999 / 6,312) = 0.0004. The month’s 0.10% has a band of about 0.02% to 0.18%. With only 4,000 labels, SE = 0.0005, half the rate itself.
Green is hit rate, red is wrong answers per 1,000, yellow is precision. The shaded band breaks the budget. Turn the guards off and look for any safe τ.
The illustrative populations and guard rates of Chapters 4 and 5.
Put hit rate and false-hit rate on the same screen, same size, same time axis. Then add the checks that catch the silent failures:
| Check | What a failure means | Alarm |
|---|---|---|
| Same question as two tenants | a leak: stop everything | any difference shared |
| A question and its negation | the guards are off or thin | same answer |
| Canary fact in a document | invalidation is broken | lag above the class TTL |
| Top-1 cosine, p50 and p90 | the query mix drifted, so τ moved | shift above 0.01 |
| Index against brute force, 10,000 queries | ANN recall decayed after deletions | agreement below 98% |
| Stored answers matching refusal patterns | the write gate let errors in | any |
| Offline eval, cache on and off | the cache costs quality | gap above 2 points |
The failure. Symptom: hit rate climbs from 26% to 34% with no change, and everyone is pleased. Measure: the top-1 cosine histogram moved up; a new product area brought new minimal-edit pairs. Fix: treat an unexplained rise as an alarm and recalibrate on fresh labels.
Chapter 10
Keep the terms, numbers, checks and the core loop in one place
A semantic cache embeds the question, searches a namespace, and serves a stored answer only if the threshold and two guards agree. It deletes entries by age, by producer version and by document. Its false-hit rate sits next to its hit rate on the dashboard.
| Term | What it is | Number on this page |
|---|---|---|
| Cgen | n-in · p-in + n-out · p-out | $0.01065, illustrative |
| Cosine | a · b / (|a| |b|) | 0.941 for the toy paraphrase |
| Precision | TP / (TP + FP) | 78.8% threshold only, 99.6% guarded |
| Share above τ | Φ((μ − τ) / σ) | 0.977 of hard negatives at 0.92 |
| Stale share | 1 − (1 − e−λL) / (λL) | 5.5% at L = 7, 0.8% at L = 1 |
| Hit rate per intent | rL / (1 + rL) | 99.75% at r = 400, L = 1 |
| Break-even h* | c-look / C-gen | 0.004% money, 0.3% latency |
| Standard error | √(p(1 − p) / n) | 0.04 points from 6,312 shadows |
pythondef answer(req): q = rewrite(req.history, req.question) # standalone question (ch 7) ns = namespace(req) # producers + context (ch 6, 7) v = embed(q) # float32[384], unit length (ch 1) nbr, sim = index.search(v, k=1, filter={"ns": ns}) if (nbr and sim >= TAU # coverage dial (ch 3, 4) and decision_tokens_agree(q, nbr.question) # guard 1 (ch 5) and cross_encoder(q, nbr.question) >= 0.60 # guard 2 (ch 5) and nbr.age < ttl_for(nbr.doc_class)): # expiry (ch 6) if random.random() < 0.02: background(shadow_check, q, req, nbr) # ch 9 return render(nbr.answer, req.entitlements) # templating (ch 7) ans, docs, meta = generate(q, req) if is_cacheable(req, docs, ans, meta): # write gate (ch 7, 9) index.add(v, q, ans, ns=ns, doc_hashes=[d.id + "#" + d.hash for d in docs]) return ans
The vectors come from vector embeddings, scored with similarity metrics and searched in a vector database. The cache usually sits in front of RAG, whose documents set the provenance rules. LLM inference explains the KV cache and where Cgen comes from. AI evaluation covers the labelling and judging, and caching and CDNs the classical caches whose rules this one breaks.
Libraries exist. GPTCache, an MIT-licensed project from Zilliz, wires an embedding generator, a vector store, a cache store and a similarity evaluator. Its docs say it can also run as a plain keyword cache. The threshold, guards, keys and dashboard in this lesson are still your job.
Vector embeddings · Vector databases · Embedding ops · RAG · Text chunking · Embedding benchmarks · Prompt engineering
Sources for the product facts: the GPTCache repository, Anthropic’s prompt caching page (both checked 2026-11-22), and the bge-small-en-v1.5 model card. All traffic, scores and guard rates on this page are illustrative.
Now press Present or Teach and explain from memory: why 0.97 is not safer, how the guards cut wrong answers, why a short TTL is free on the head, and why the median ignores a 26% cache. Then go back to the hero, choose threshold only, and find a τ with fewer than 10 red dots.