Semantic Caching

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.

Serve 1,000 requests

0.920

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

The Bill

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.

Say it aloud

C-gen equals n-in times p-in, plus n-out times p-out.

Cgen
C-gen the cost of one fresh generation, in dollars.
nin
n-in input tokens: system prompt, retrieved documents and the question.
pin
p-in the price of one input token.
nout
n-out output tokens: the answer.
pout
p-out the price of one output token, usually several times p-in.
In plain words

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 numbers

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.

SliceDistinct intentsRequestsShare
Head200480,00040%
Body12,000420,00035%
Tail214,000300,00025%

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.

Vary how people phrase it

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.

1,550

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”.

The road

  1. The loop: embed, search, decide, serve or generate.
  2. Three other caches: exact, prompt and KV caching, and how they differ.
  3. The threshold: false hits, false misses, and why 0.97 is not safer. The hero’s slider.
  4. Calibration: a labelled set and a sweep.
  5. Guards: the checks that cut wrong answers 80 times. The hero’s third button.
  6. Invalidation: TTLs, versions and document provenance.
  7. Keys: context that changes the answer.
  8. Money: break-even, latency and placement.
  9. Measuring: shadow samples and the honest dashboard.
  10. Field guide: terms, numbers, code and links.
Aggressive normalisation raises your exact cache’s hit rate from 16.7% to 24%. What do you check first?

Chapter 1

Embed, Search, Decide

Walk one request through the four steps with its shapes and milliseconds

Every semantic cache runs the same four steps:

  1. Embed. An embedding model turns the question into a vector. bge-small-en-v1.5 gives 384 numbers, 1,536 bytes as float32.
  2. Search. An approximate nearest neighbour (ANN) index, such as HNSW, finds the stored question whose vector is closest.
  3. Decide. Compare their similarity with a threshold τ (tau).
  4. Serve or generate. Above τ, serve the stored answer. Below, call the model and store the new pair.

Step one request through

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.

Say it aloud

Cos of a and b equals a dot b, over the length of a times the length of b.

cos(a, b)
cos of a and b the similarity, from −1 to 1. One means the same direction.
a · b
a dot b multiply matching numbers and add them: 384 multiply-adds here.
|a|
the length of a the square root of the sum of a’s numbers squared.
|b|
the length of b the same for the stored vector.
In plain words

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 numbers

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.

PathWhat runsTime
Hitembed 6 + search 1.8 + verify 4 + fetch 0.812.6 ms
Missembed 6 + search 1.8, then generate 2,6002,607.8 ms
Miss overhead7.8 ms spent to learn there is no hit0.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.

Why does the miss path cost so little extra?

Chapter 2

Three Other Caches

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.

CacheMatches onWhat a hit savesCan a hit be wrong?
Exact response cachethe whole request, byte for bytethe whole generationno, unless the facts went stale
Provider prompt cachean identical prompt prefixpart of the input price and timeno: the model still generates
KV cachethe tokens of the current generationrecomputing attention for earlier tokensno: it is inside one model call
Semantic cachemeaning, by a similarity scorethe whole generationyes

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.

Send a second request

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:

input cost = nc · 0.1 · pin + nnew · pin  ·  1,500 × $0.30/M + 300 × $3/M = $0.00135  ·  Cgen falls from $0.01065 to $0.00660

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.

Two users send the same 1,500-token system prompt with different questions. Which cache helps?

Chapter 3

The Threshold Is Not a Safety Dial

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.

Move the line through twelve pairs

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.

0.920

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).

Say it aloud

Precision equals TP over TP plus FP.

precision
precision the share of served answers that are correct, from 0 to 1.
TP
T-P true positives: served, and the stored answer is right.
FP
F-P false positives: served, and the stored answer is wrong. These are the false hits.
In plain words

Count the served pairs that are right, TP. Count the served pairs that are wrong, FP. Divide TP by their sum.

With numbers

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 τ.

You raise τ from 0.92 to 0.97. Hits fall by four fifths, but the share of wrong answers barely moves. What does this tell you?

Chapter 4

Calibrate on Your Own Logs

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:

  1. Sample 4,000 requests from the last two weeks.
  2. For each, find the entry the cache would have returned, using only entries older than the request.
  3. Ask a human or a strong judge one question: “Is the stored answer correct and complete for this request?”

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”.

GroupCountMean cosine μSpread σ
Positives1,6000.9450.025
Easy negatives2,0500.7800.060
Hard negatives3500.9600.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.

Say it aloud

The share above tau equals phi of mu minus tau, over sigma.

τ
tau the threshold.
Φ
phi the standard normal table: Φ(1) = 0.841, Φ(2) = 0.977.
μ
mu the group’s mean cosine.
σ
sigma the group’s spread, the standard deviation.
In plain words

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.

With numbers

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%.

Sweep the gate over three groups

Green is positives, yellow easy negatives, pink hard negatives. Shaded area right of τ is served. Drag τ, then set hard negatives to zero.

0.920
350

Illustrative labelled set of 4,000 requests; bell curves stand in for the real histograms.

τPrecisionRecallHit rateWrong / all traffic
0.8878.0%99.5%51.0%11.2%
0.9278.8%84.1%42.7%9.1%
0.9475.4%57.9%30.7%7.6%
0.9769.9%15.9%9.1%2.7%
0.9970.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.

Hard negatives have mean 0.960 and spread 0.020. What share clears τ = 0.94?

Chapter 5

Guards Do the Safety Work

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.

Turn the guards on

Bars count candidates out of 4,000 labelled requests after each stage. Toggle each guard and pick a budget for wrong answers.

0.930

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:

true: 1,161 × 0.97 = 1,126 → × 0.93 = 1,048  ·  false: 13 × 0.80 + 327 × 0.12 = 49 → × 0.08 = 4
hit rate = 1,052 / 4,000 = 26.3%  ·  precision = 99.6%  ·  wrong = 4 / 4,000 = 1.0 per 1,000

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.

A billing assistant has a budget of 0.1 wrong per 1,000. The best threshold-only setting gives 6 per 1,000. What next?

Chapter 6

Answers Go Stale

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 changedExampleFix
The factsa price, a policya time-to-live per content class
The producerthe embedder, the generator, the system promptput their versions in the namespace
The evidencea retrieved document was editeddelete 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:

Say it aloud

Stale equals one minus, one minus e to the minus lambda L, over lambda L.

e−λL
e to the minus lambda L the chance the fact has not changed during the whole TTL.
λ
lambda the change rate: changes per day, 1/T.
L
L the TTL in days.
In plain words

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.

With numbers

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.

Say it aloud

h equals r L, over one plus r L.

h
h the hit rate within one intent, from 0 to 1.
r
r the intent’s requests per day, arriving at random.
L
L the TTL in days.
In plain words

Each cycle has one miss and about r times L hits. Divide the hits by everything in the cycle.

With numbers

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%.

Pick a TTL for one intent

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.

40
61
1 day

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.

A RAG cache has a 24-hour TTL. A document is corrected at 09:14. What fixes the stale answers?

Chapter 7

Keys Hold What the Text Does Not

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.

FieldIn the key?Why
Localeyescurrency, legal text
Planoften, or template itentitlements change the answer
Platformif answers give UI steps“tap” versus “click”
Prompt and tool versionsalwaysthey change every answer
Tenant or user idno: refuse to cache private answersit deletes the cache
Request id, timestampneverunique, 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:

h = (r/N)·L / (1 + (r/N)·L)  ·  r = 400, L = 1: N = 1 → 99.75%  ·  N = 72 → 84.7%  ·  N = 288,000 → 0.14%

Build the key

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.

400

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.

Two users on different plans send the identical question and need different answers. Why can no verifier fix this?

Chapter 8

Does It Pay?

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.

Say it aloud

h-star equals c-look over C-gen.

h*
h-star the break-even hit rate: above it, the cache saves money.
clook
c-look the cost of one lookup, paid on every request.
Cgen
C-gen the cost of one generation, saved on each hit.
In plain words

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.

With numbers

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%.

Find the break-even

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.

26.3%
1,200,000
$110

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.

The cache hits 26% of requests and p50 latency did not move. Why?

Chapter 9

The Honest Dashboard

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.

hits = 1,200,000 × 0.263 = 315,600/month  ·  shadow = 2% = 6,312 × $0.01065 = $67/month, 2% of the saving

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.

Say it aloud

SE equals the square root of p times one minus p, over n.

SE
S-E the standard error of the measured rate.
√
the square root of undoes the squaring inside the variance.
p
p the rate being measured, here the false-hit rate.
n
n the number of shadow samples.
In plain words

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.

With numbers

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.

Sweep τ on one screen

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 τ.

0.930
1.0

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:

CheckWhat a failure meansAlarm
Same question as two tenantsa leak: stop everythingany difference shared
A question and its negationthe guards are off or thinsame answer
Canary fact in a documentinvalidation is brokenlag above the class TTL
Top-1 cosine, p50 and p90the query mix drifted, so τ movedshift above 0.01
Index against brute force, 10,000 queriesANN recall decayed after deletionsagreement below 98%
Stored answers matching refusal patternsthe write gate let errors inany
Offline eval, cache on and offthe cache costs qualitygap 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.

Why chart the false-hit rate as a 90-day rolling window?

Chapter 10

Field Guide

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.

TermWhat it isNumber on this page
Cgenn-in · p-in + n-out · p-out$0.01065, illustrative
Cosinea · b / (|a| |b|)0.941 for the toy paraphrase
PrecisionTP / (TP + FP)78.8% threshold only, 99.6% guarded
Share above τΦ((μ − τ) / σ)0.977 of hard negatives at 0.92
Stale share1 − (1 − e−λL) / (λL)5.5% at L = 7, 0.8% at L = 1
Hit rate per intentrL / (1 + rL)99.75% at r = 400, L = 1
Break-even h*c-look / C-gen0.004% money, 0.3% latency
Standard error√(p(1 − p) / n)0.04 points from 6,312 shadows

Checklist before launch

  1. Exact and prompt caching are on, and the semantic cache is sized after them.
  2. One embed function, pinned revision, normalised vectors, used on both paths.
  3. A written budget for wrong answers per 1,000, and τ chosen from a labelled set.
  4. Token guard and cross-encoder run behind τ.
  5. Namespace holds embedder, generator, prompt hash, corpus snapshot and answer-changing context.
  6. The write gate refuses errors, refusals, truncated answers, tool calls and private data.
  7. TTL per content class, no refresh on hit, and deletion by document.
  8. Cache-aside with a timeout, and singleflight on misses.
  9. Shadow sampling, and the false-hit rate on the same screen as the hit rate.

The core in code

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

Where it sits

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.

The takeaway. A semantic cache is a classifier that decides “same answer or not”. The threshold sets coverage; guards, keys and invalidation set correctness; shadow samples prove it.

Keep going

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.

Semantic Caching
Next: RAG · Back to Gleams