Semantic caching for LLMs: thresholds, hit rates, and false hits

Semantic caching returns a stored LLM response for a similar request. See how thresholds, TTLs, and scoping set hit rate and false hits, with a tested sweep.

Published
Reading time
11 min read
Level
Intermediate
By
AI for Devs
TL;DR
  • Semantic caching embeds each request, finds the closest stored request, and returns its stored response when cosine similarity clears a threshold. The provider is never called, unlike prompt caching, which still generates and bills a new response.
  • Bifrost checks an exact hash first and searches by similarity only on a miss. As of November 16, 2026, it defaults to a 0.8 threshold and a 5-minute TTL, and scopes entries to the cache key, model, provider, parameters, and caller identity.
  • On 78 labeled support requests with a dependency-free embedder, exact matching served 26.9% of requests with no wrong answers. A 0.80 threshold raised the hit rate to 33.3% and gave 7.7% of all requests a wrong answer.
  • False hits come from near-misses that share most of their words, such as CSV and PDF export questions at 0.881 similarity. They repeat, because a request served from cache never stores its own correct answer.
  • A cache shared by two tenants served each the other's refund policy at similarity 1.0, which no threshold can block. Scope entries by tenant, and tune thresholds on your own labeled traffic.

Semantic caching returns a stored LLM response when a new request's embedding lands close enough to one already answered, so the request never reaches the provider. It catches the paraphrases an exact-match cache misses, and it also returns wrong answers, with no error, when two requests look alike but need different replies. This guide uses Bifrost, an open-source AI gateway, as the worked example for cache keys, thresholds, TTLs, and scoping. A dependency-free Python script then sweeps 16 thresholds and counts correct hits against false hits.

#What is semantic caching

Semantic caching is a response cache keyed by meaning. It embeds the request text, searches stored requests for the nearest neighbor, and returns that neighbor's stored response if the similarity score meets a threshold. Below the threshold, the request goes to the model, and its response is stored for the next caller.

The store is usually a vector database holding one vector per cached request, with the response beside it. Similarity is cosine similarity, so the threshold is a number between 0 and 1.

A request with a cache key tries a direct hash lookup first. A miss is embedded and searched within its partition, and a match at or above the threshold is served without calling the provider. Everything else calls the provider and is stored afterward.Requestto the gatewayCache key?x-bf-cache-keyyesDirect lookuphash: input + paramsmissEmbed, then searchnearest 1 in partitionSimilarity ≥ 0.80?x-bf-cache-thresholdkey, identity, model, paramshityesServe stored responseprovider not calledno key: bypassbelowCall providerfull latency and costStore entryasync, expires after TTLSolid lines carry the request. The dashed write runs after the response returns.
Fig. 1Bifrost serves a direct hash hit without embedding anything. Only a direct miss pays for an embedding and a nearest-neighbor search, and only a match at or above the threshold skips the provider.

Bifrost runs both lookups in one semantic cache plugin. The direct path hashes the trimmed, lowercased input with its parameters, so an identical request replays without an embedding call. Entries live in a vector store you run: Redis or Valkey, Weaviate, Qdrant, or Pinecone.

#Semantic cache vs exact-match cache vs prompt caching

An exact-match cache replays a response only for requests that are identical after normalization. A semantic cache replays a response for similar requests. Provider prompt caching replays no response at all: it reuses the computed prefix of an input, and the model still generates a new answer that you pay for.

Exact-match cacheSemantic cacheProvider prompt caching
What must matchWhole normalized requestMeaning, above a similarity thresholdExact prompt prefix
What is reusedStored responseStored responsePrefix computation
Provider called on a hitNoNoYes
Paid on a hitStore lookupEmbedding call and vector searchDiscounted input plus full output
Wrong-answer riskSame words, different correct answerNear-misses above the thresholdNone from the cache

Provider prompt caching cannot change an answer. Anthropic's prompt caching docs say the response matches an uncached call, and OpenAI's guide says its cache stores KV tensors for a prefix that must match exactly. The Claude API pricing guide works out when a cache write pays for itself.

The two kinds of LLM caching stack. Bifrost runs semantic caching and auto prompt caching as independent features, so a semantic miss can still read a cached prefix.

Use prompt caching for long shared prefixes such as tool definitions, ordered as the context engineering guide describes. Use exact matching for repeated requests. Add semantic matching last, and only where you can measure its false hits.

#How Bifrost keys a semantic cache

Bifrost caches only requests that carry a cache key, sent as the x-bf-cache-key header or set once as default_cache_key. Within that key, an entry is reused only by requests with the same model, provider, generation parameters, and caller identity, and the similarity search stays inside that partition.

The v1.7.7 plugin source, released November 10, 2026, adds detail:

  • A parameter fingerprint covers temperature, top-p, max tokens, stop sequences, tools, response format, seed, and the OpenAI-style user field, among others. Requests with different temperatures never share an entry.
  • The embedded text is every message as a lowercased role: content line, system prompt included unless exclude_system_prompt is true.
  • Requests with more than conversation_history_threshold messages, 3 by default, skip the cache. A system prompt counts, so in a chat that has one, only the first user turn qualifies.
  • Responses with tool calls are not stored unless cache_tool_call_responses is true, since a replayed tool call would carry arguments chosen for someone else's prompt.

The documented defaults look like this in config.json, which was not run for this article.

config.json (excerpt, not run)
JSON
{
  "vector_store": { "enabled": true, "type": "redis", "config": { "addr": "localhost:6379" } },
  "plugins": [
    {
      "enabled": true,
      "name": "semantic_cache",
      "config": {
        "provider": "openai",
        "embedding_model": "text-embedding-3-small",
        "dimension": 1536,
        "ttl": "5m",
        "threshold": 0.8,
        "conversation_history_threshold": 3,
        "exclude_system_prompt": false,
        "cache_by_model": true,
        "cache_by_provider": true,
        "cache_tool_call_responses": false,
        "disable_identity_scoping": false
      }
    }
  ]
}

dimension must match the embedding model, and a namespace holds one dimension, so a new model needs a new vector_store_namespace. Setting dimension to 1 and leaving out provider gives direct-only mode, with no embedding calls.

Five headers change the defaults for one request:

HeaderEffect on that request
x-bf-cache-keySets the partition. Without it, and without default_cache_key, the cache is bypassed
x-bf-cache-thresholdRaises the threshold. A value below the configured one is floored to it
x-bf-cache-ttlOverrides the TTL
x-bf-cache-typedirect or semantic limits the lookup to one path
x-bf-cache-no-storetrue serves hits but writes nothing

Each response the cache looked up reports the outcome in x-bifrost-cache-* headers, and in extra_fields.cache_debug on routes that return it. Semantic hits include the similarity score and threshold, the data you need for tuning.

#What semantic cache hit rates depend on

Hit rate depends on your traffic more than on the cache. It rises with how often users repeat a question inside one TTL, how coarse the cache key is, and how low the threshold sits. It falls with every field that splits partitions, such as per-user keys, identity, and varied parameters, and with long conversations.

Partitioning has a measurable cost. In the sweep below, sharing one cache across two tenants raised correct exact-match hits from 21 to 30 of 78 requests. A client that sends a random seed or a per-user user field gets an empty partition for each value.

The semantic path costs time on every direct miss. Bifrost embeds the request before it searches, so a semantic miss is slower than no cache at all. With embedding time E and model time L, semantic matching saves time only when its hit rate on direct misses exceeds E / L, which is 6 percent for an assumed 150 ms embedding and 2.5-second model call.

Cost breaks even far earlier. As of November 16, 2026, OpenAI lists text-embedding-3-small at $0.02 per million tokens and gpt-5.4-mini at $0.75 input and $4.50 output, matching the LLM pricing dataset. Embedding a 200-token request costs $0.000004, and answering it with 300 output tokens costs $0.0015, so one semantic hit per 375 direct misses covers the embeddings. Latency and wrong answers decide whether the semantic layer pays off.

#Measure hit rate against false hits with a threshold sweep

A threshold sweep replays labeled traffic through a cache at each candidate threshold and counts two outcomes: requests that got a correct cached answer, and requests that got a wrong one. In the run below, no threshold added more than two correct hits over exact matching, and every threshold that added one also served at least three wrong answers.

The script models a support assistant for two tenants: 17 intents, 78 requests, and two intents whose correct answer differs by tenant. The first phrasing of each intent appears three times, standing in for suggested-question buttons. Like Bifrost, the cache tries an exact lookup before the nearest neighbor in the same partition, and it writes only on a miss.

embed() stands in for an embedding model. It hashes words and character trigrams into 512 dimensions, so it measures shared wording and nothing else. Replace it with a call to your production model to sweep real vectors.

semantic_cache_sweep.py
Python
"""Sweep a semantic cache's similarity threshold on labeled traffic. Python 3, stdlib only."""
import hashlib
import math
import random
import re
import sys
from collections import Counter
 
DIM = 512
 
# (intent, answer differs per tenant, phrasings). Neighbors such as
# reset_password and reset_2fa look alike but need different answers.
INTENTS = [
    ("reset_password", False, ["How do I reset my password?", "how can I reset my password",
                               "I forgot my password, how do I reset it?", "Reset my password please",
                               "What are the steps to reset a forgotten password?"]),
    ("reset_2fa", False, ["How do I reset my two-factor authentication?", "How do I reset my 2FA?",
                          "I lost my phone, how can I reset two-factor auth?"]),
    ("change_password", False, ["How do I change my password?", "Where can I change my password in settings?"]),
    ("change_email", False, ["How do I change my email address?", "Can I change the email on my account?",
                             "How can I update my account email?"]),
    ("cancel_plan", False, ["How do I cancel my subscription?", "How can I cancel my subscription?",
                            "I want to cancel my plan", "Cancel my subscription"]),
    ("pause_plan", False, ["How do I pause my subscription?", "Can I pause my plan for a month?"]),
    ("export_csv", False, ["How do I export my data as CSV?", "Export data to CSV",
                           "Can I download my data as a CSV file?"]),
    ("export_pdf", False, ["How do I export my data as PDF?", "Can I download a report as a PDF file?"]),
    ("rate_limit", False, ["What is the API rate limit?", "How many API requests can I make per minute?",
                           "What are the rate limits for the API?"]),
    ("streaming", False, ["Does the API support streaming?", "Can the API stream responses?"]),
    ("batching", False, ["Does the API support batching?", "Can I send batch requests to the API?"]),
    ("delete_account", False, ["How do I delete my account?", "I want to delete my account permanently"]),
    ("restore_account", False, ["How do I restore my deleted account?", "Can I undo deleting my account?"]),
    ("price_pro", False, ["How much does the Pro plan cost?", "What is the price of the Pro plan?"]),
    ("price_team", False, ["How much does the Team plan cost?", "What is the price of the Team plan?"]),
    ("refund_policy", True, ["What is your refund policy?", "How long do I have to request a refund?",
                             "Can I get a refund?"]),
    ("support_hours", True, ["What are your support hours?", "When is support available?"]),
]
TENANTS = ["acme", "globex"]
SYSTEM = ("You are the support assistant for a project management app. Answer in two short "
          "paragraphs, link the help center article you used, and never promise refunds or "
          "credits that the customer's policy does not allow.")
 
 
def embed(text):
    """Stand-in for an embedding model: signed feature hashing of words and
    character trigrams, L2-normalized so a dot product is cosine similarity."""
    t = " " + " ".join(re.sub(r"[^a-z0-9]", " ", text.lower()).split()) + " "
    feats = Counter("w:" + w for w in t.split())
    feats.update("c:" + t[i:i + 3] for i in range(len(t) - 2))
    v = [0.0] * DIM
    for f, n in feats.items():
        h = int.from_bytes(hashlib.blake2b(f.encode(), digest_size=8).digest(), "big")
        v[h % DIM] += n if h >> 63 else -n
    norm = math.sqrt(sum(x * x for x in v))
    return [x / norm for x in v]
 
 
def traffic(seed=7):
    """Every phrasing once, the first phrasing of each intent twice more
    (suggested-question buttons), random tenant and casing, shuffled."""
    rng = random.Random(seed)
    reqs = []
    for intent, per_tenant, phrasings in INTENTS:
        for i, text in enumerate(phrasings):
            for _ in range(3 if i == 0 else 1):
                tenant = rng.choice(TENANTS)
                answer = f"{intent}@{tenant}" if per_tenant else intent
                reqs.append((tenant, rng.choice([text, text.lower(), " " + text]), answer))
    rng.shuffle(reqs)
    return reqs
 
 
def run(reqs, threshold, semantic=True, scoped=True, system=False):
    """Online cache: exact lookup on trimmed, lowercased text first, then the
    nearest neighbor at or above the threshold. A miss calls the model and
    stores the correct answer. Embedded text is "role: content" lines."""
    cache = []  # (partition, normalized text, vector, answer)
    hits = wrong = 0
    for tenant, text, answer in reqs:
        part = tenant if scoped else "shared"
        norm = text.strip().lower()
        vec = embed((f"system: {SYSTEM.lower()}\n" if system else "") + f"user: {norm}")
        served = next((a for p, n, _, a in cache if p == part and n == norm), None)
        if served is None and semantic:
            sim, a = max(((sum(x * y for x, y in zip(vec, v)), a) for p, _, v, a in cache if p == part),
                         default=(-1.0, None))
            served = a if sim >= threshold else None
        if served is None:
            cache.append((part, norm, vec, answer))
        else:
            hits += 1
            wrong += served != answer
    return hits, wrong
 
 
def report(label, hits, wrong):
    n = len(REQS)
    share = f"{wrong / hits:.1%}" if hits else "-"
    print(f"{label:>18} {hits / n:9.1%} {(hits - wrong) / n:8.1%} {wrong / n:10.1%} {share:>14}")
 
 
REQS = traffic()
print(f"{len(REQS)} requests, {len({a for _, _, a in REQS})} distinct correct answers, {len(TENANTS)} tenants")
print(f"{'threshold':>18} {'hit rate':>9} {'correct':>8} {'false hits':>10} {'wrong of hits':>14}")
report("exact only", *run(REQS, 2.0, semantic=False))
for t in [round(0.50 + 0.03 * i, 2) for i in range(16)]:
    report(f"{t:.2f}", *run(REQS, t))
print("\nat threshold 0.80")
report("scoped per tenant", *run(REQS, 0.80))
report("shared", *run(REQS, 0.80, scoped=False))
report("shared, exact only", *run(REQS, 2.0, semantic=False, scoped=False))
report("system prompt in", *run(REQS, 0.80, system=True))
 
# Nearest earlier request in the same tenant, with nothing served from cache.
pairs, seen = [], []
for tenant, text, answer in REQS:
    norm = text.strip().lower()
    vec = embed(f"user: {norm}")
    best = max(((sum(x * y for x, y in zip(vec, v)), a, s) for p, v, a, s in seen if p == tenant), default=None)
    if best and best[2] != norm:
        pairs.append((round(best[0], 3), best[1] == answer, norm, best[2]))
    seen.append((tenant, vec, answer, norm))
pairs.sort(reverse=True)
print(f"\nnearest earlier request, top 8 of {len(pairs)}")
for sim, same, text, near in pairs if "--pairs" in sys.argv else pairs[:8]:
    print(f"{sim:.3f} {'same ' if same else 'WRONG'} {text!r} -> {near!r}")

Run it with python3 semantic_cache_sweep.py. It ran on Python 3.15.1 on an Apple M2 in 0.6 seconds, with no packages or network access. No embedding model, LLM, or Bifrost instance was called, so the gateway behavior in this article comes from its docs and source, not this run. Real output:

Text
78 requests, 19 distinct correct answers, 2 tenants
         threshold  hit rate  correct false hits  wrong of hits
        exact only     26.9%    26.9%       0.0%           0.0%
              0.50     62.8%    29.5%      33.3%          53.1%
              0.53     55.1%    24.4%      30.8%          55.8%
              0.56     55.1%    24.4%      30.8%          55.8%
              0.59     55.1%    24.4%      30.8%          55.8%
              0.62     52.6%    25.6%      26.9%          51.2%
              0.65     50.0%    26.9%      23.1%          46.2%
              0.68     44.9%    24.4%      20.5%          45.7%
              0.71     42.3%    24.4%      17.9%          42.4%
              0.74     41.0%    23.1%      17.9%          43.8%
              0.77     37.2%    24.4%      12.8%          34.5%
              0.80     33.3%    25.6%       7.7%          23.1%
              0.83     32.1%    28.2%       3.8%          12.0%
              0.86     30.8%    26.9%       3.8%          12.5%
              0.89     26.9%    26.9%       0.0%           0.0%
              0.92     26.9%    26.9%       0.0%           0.0%
              0.95     26.9%    26.9%       0.0%           0.0%
 
at threshold 0.80
 scoped per tenant     33.3%    25.6%       7.7%          23.1%
            shared     51.3%    33.3%      17.9%          35.0%
shared, exact only     43.6%    38.5%       5.1%          11.8%
  system prompt in     97.4%     3.8%      93.6%          96.1%
 
nearest earlier request, top 8 of 55
0.889 same  'how do i reset my password?' -> 'how can i reset my password'
0.881 WRONG 'how do i export my data as csv?' -> 'how do i export my data as pdf?'
0.881 WRONG 'how do i export my data as csv?' -> 'how do i export my data as pdf?'
0.844 same  'i forgot my password, how do i reset it?' -> 'how do i reset my password?'
0.837 same  'how can i cancel my subscription?' -> 'cancel my subscription'
0.809 WRONG 'how do i cancel my subscription?' -> 'how do i pause my subscription?'
0.798 WRONG 'how do i reset my 2fa?' -> 'how do i reset my password?'
0.790 WRONG 'how do i change my password?' -> 'how do i reset my password?'

Exact matching alone served 21 of 78 requests, all correct. At the 0.80 default, correct hits fell to 20 while 6 requests got a wrong answer. A threshold of 0.83 reached 22 correct hits with 3 wrong, and 0.50 reached 23 with 26 wrong. False hits reached zero only at 0.89, where semantic matching added nothing.

Correct and false hits as a share of 78 requests across thresholds 0.50 to 0.95. False hits fall from 33.3 percent to zero at 0.89, where correct hits equal exact matching alone at 26.9 percent.Share of 78 requests served from cache0%20%40%60%0.500.530.560.590.620.650.680.710.740.770.800.830.860.890.920.95Similarity thresholdBifrost default33.3% wrong7.7% wrong0 wrongexact match only: 26.9%correct hitsfalse hitsexact match onlyfirst zero
Fig. 2Correct and false hits as a share of 78 requests. False hits reach zero only at 0.89, where correct hits equal exact matching alone. The curves are not smooth, because each false hit changes what the cache stores.

These numbers come from a lexical embedder on hand-written traffic, so treat them as a method, not a benchmark. Trained embedding models are built to place paraphrases such as "can I get a refund" and "what is your refund policy" close together, where this one scored them 0.357. That would lift the correct-hit curve without removing the near-misses below.

#Why false hits happen and what they cost

A false hit happens when two requests score above the threshold but need different answers. Similarity measures shared wording and topic, while the correct answer often turns on the one word that differs: CSV or PDF, cancel or pause, delete or restore. Those near-misses can outscore true paraphrases, so no single threshold separates them.

Similarity of each request to its nearest earlier request. At 0.80 and above, three neighbors share the right answer and three need a different one, and near-misses between 0.70 and 0.80 outnumber paraphrases seven to two.same answer15 requestsdifferent answer40 requests0.20.40.60.8Cosine similarity to the nearest earlier requestat 0.80 or above: 3 same, 3 different
Fig. 3Each square is one request's nearest earlier request in the same tenant. Between 0.70 and 0.80, neighbors that need a different answer outnumber paraphrases seven to two, so moving the threshold trades one kind of error for the other.

The overlap is not an artifact of a toy embedder. In vCache, an ICLR 2026 paper, Schroeder et al. tested text-embedding-3-small, GTE-large, and E5-large-v2 and found highly overlapping similarity distributions for correct and incorrect hits. They argue that one fixed threshold is unreliable and learn a threshold per cached prompt under a user-set error bound. The MeanCache authors also reported high false-hit rates in existing caches.

A false hit costs more than one wrong answer:

  • It returns a normal success status. Only cache metadata, such as x-bifrost-cache-hit-type, and the log entry show it came from cache.
  • It repeats. A hit writes nothing, so the correct answer is never stored. At 0.80, all three CSV export requests got the PDF answer, and all three of one tenant's "How do I cancel my subscription?" requests got the pause instructions.
  • It multiplies with traffic. Both of those were the most-asked phrasing of their intent, and each kept hitting the wrong entry until the TTL expired.

A long system prompt makes everything look alike. The last row of the 0.80 block embedded a 35-word system prompt with each question, as Bifrost does by default. Shared wording dominated the vector, so the hit rate jumped to 97.4% and 93.6% of requests got a wrong answer.

Setting exclude_system_prompt to true removes system messages from both the hash and the embedding. Then put a prompt version in the cache key, so a prompt change starts a new partition.

#How to tune the similarity threshold

Tune the threshold on labeled request pairs from your own traffic, embedded with your production model, and pick the lowest threshold whose wrong-answer rate you can accept. The 0.8 default is only a starting point, and a billing route tolerates far fewer wrong answers than a docs lookup.

  1. Run direct-only mode first. Its hit rate is your zero-risk floor, and semantic matching has to beat it.
  2. Sample a few hundred real requests per route, embed them with the production model, and label each close pair as same or different answer.
  3. Swap that model into embed() and sweep. Choose the threshold where the false-hit rate meets your limit, and count the correct hits it adds over exact matching.
  4. Set the global threshold for your least sensitive route. x-bf-cache-threshold can only raise it, so stricter routes send a higher value.
  5. Send x-bf-cache-type: direct on routes where one word changes the answer, such as order IDs, dates, plan names, and amounts.
  6. Each week, filter the logs by hit type and read a sample of semantic hits with their scores. Repeat the sweep whenever the embedding model changes.

#Invalidation and TTLs

A cached answer goes stale when the facts behind it change, and the TTL is the only automatic invalidation. Bifrost stores each entry with an expiry, 5 minutes by default or x-bf-cache-ttl per request. For changes that cannot wait, it deletes entries by ID or by cache key.

Clear entries (not run)
Shell
# One entry, using cache_id from cache_debug or x-bifrost-cache-id
curl -X DELETE http://localhost:8080/api/cache/clear/550e8500-e29b-41d4-a725-446655440001
 
# Every entry under a cache key, for every identity that wrote under it
curl -X DELETE http://localhost:8080/api/cache/clear-by-key/support-faq-v14

Entries survive a Bifrost restart, so restarting is not a way to clear them. Design keys around invalidation. Put a content version in the key, such as support-faq-v14 for a help center release, so publishing the next release moves traffic to a fresh partition at once. Then clear the old key.

Pick the TTL from how often the answer changes and how often the question repeats. A 5-minute TTL absorbs bursts and lets a wrong or stale entry expire quickly. Longer TTLs raise hit rates on slow-changing content and keep a false hit alive just as long.

#Scope a semantic cache per user and per tenant

Scope a semantic cache at least as narrowly as its answers differ. When two tenants can get different correct answers to the same words, they must not share entries, because that false hit arrives at similarity 1.0 and no threshold stops it. Narrower scope costs hit rate, so share only what is identical for every caller.

With one shared cache and exact matching only, 4 of 78 requests got the other tenant's refund policy or support hours, word for word. Scoping per tenant removed those errors and cut correct exact hits from 30 to 21, because each tenant warmed its own copy of the shared answers.

Bifrost scopes by identity by default. An entry is served only to the identity that wrote it: the resolved virtual key and, when the request is attributed to a user, that user. The identity is folded into the entry's hash and never stored on it. Setting disable_identity_scoping to true shares entries by cache key across identities, which suits only content that is identical for everyone, such as public docs answers.

Each entry stores a full response, which can include personal data, in your own vector store until it expires. The semantic path also sends the request text to the embedding provider, so give the cache store the same access controls and retention as request logs.

Skip semantic matching for account-specific answers such as balances or order status, for time-sensitive facts, for high-temperature creative output, and for agent turns that call tools.

#Questions

What is semantic caching in LLMs?

Semantic caching stores LLM responses next to an embedding of the request that produced them. When a new request arrives, the cache embeds it, finds the nearest stored request, and returns that stored response if cosine similarity meets a threshold such as 0.8. The model is not called on a hit, so the request costs one embedding call and a vector search instead of a full generation.

What is the difference between semantic caching and prompt caching?

Semantic caching returns a stored response and skips the model call. Prompt caching, run by providers such as Anthropic and OpenAI, reuses the computed prefix of an input that matches exactly, and the model still generates and bills a fresh response. Prompt caching cannot return a wrong answer, and a semantic cache can. The two are independent, and a gateway can run both on the same request.

What similarity threshold should a semantic cache use?

No single value works everywhere, because similarity scores depend on the embedding model and on your traffic. Bifrost defaults to 0.8 as of November 16, 2026, and this article's test needed 0.89 before false hits reached zero. Label a sample of request pairs from your own logs, embed them with your production model, sweep thresholds, and pick the lowest one whose wrong-answer rate you accept.

Can a semantic cache return the wrong answer?

Yes. A false hit happens when two requests score above the threshold but need different answers, such as exporting as CSV versus PDF, or canceling versus pausing a subscription. The cached answer arrives with a normal success status. A hit writes nothing, so every repeat of that question inside the TTL gets the same wrong answer. Scoping and stricter thresholds reduce the risk.

How do you invalidate a semantic cache?

Entries expire after their TTL, which is the only automatic invalidation. Bifrost defaults to 5 minutes, accepts a per-request TTL header, and deletes one entry by its cache ID or every entry under a cache key through its cache API. Putting a content version, such as a policy or docs release number, in the cache key moves traffic to a fresh partition when the content changes.

Is semantic caching safe in a multi-tenant app?

Only when entries are scoped per tenant. If two tenants ask the same question and have different correct answers, an unscoped cache serves one tenant's answer to the other at similarity 1.0, which no threshold blocks. Bifrost scopes entries to the virtual key and user that wrote them by default, and the cache key adds narrower partitions, such as one per feature or per session.

Does semantic caching work for chat conversations and agents?

Only for short exchanges by default. Bifrost skips caching when a request carries more than 3 messages, so with a system prompt only the first user turn is cached. It also skips responses that contain tool calls unless you opt in. Follow-up questions depend on earlier turns, and a replayed tool call would carry another user's arguments, so most agent traffic should bypass the cache.