Semantic cache
Large-language-model calls are slow and cost money, and many of the prompts an application sends mean the same thing in different words. A semantic cache…
Large-language-model calls are slow and cost money, and many of the prompts an application sends mean the same thing in different words. A semantic cache keeps each answer with the prompt that produced it and, for a new prompt, returns a stored answer when the two prompts are close enough in meaning. Only a miss goes to the model.
Every KiviDB Cloud database can hold semantic caches. The entries are stored in that database, so nothing you cache leaves it.
How it works
A namespace is one cache with its own settings:
| Setting | |
|---|---|
| Embeddings | kividb (a model KiviDB runs, billed per token: no API key needed), openai (OpenAI, with your API key), openai_compatible (any HTTPS endpoint with OpenAI's /embeddings request and response), or none (you send a vector with every call) |
| Model and dimensions | e.g. text-embedding-3-small, 1536. The vectors the model returns must have this many dimensions. With kividb the model is titan-embed-text-v2, at 256, 512 or 1024 dimensions. |
| Threshold | the cosine similarity (1 means the same direction) a lookup must reach to count as a hit, between 0 and 1. Default 0.45 with kividb, 0.6 otherwise. |
| Default time to live | how long an entry is kept unless the put says otherwise. Default 24 hours. |
Put stores a prompt and its response: the prompt is turned into a vector (an embedding) and stored with them. Lookup turns the new prompt into a vector, finds the closest stored ones, and returns the first whose similarity reaches the threshold and that has not expired. Otherwise it reports a miss and the closest similarity it found, which helps you tune the threshold.
Your embedding provider's API key is stored encrypted and never shown again. A custom endpoint must be HTTPS on a public address; private, loopback and cloud metadata addresses are refused, both when you save it and on every call.
Hosted embeddings
With "provider": "kividb", KiviDB embeds your prompts with Amazon Titan Text
Embeddings V2 on Amazon Bedrock, so you need no account with a model provider.
It costs $0.05 per million tokens (a token is roughly four characters of
English), taken from your credit and shown on the Usage page as Hosted
embeddings, by database. A cache of 10,000 lookups a day of 200-character
prompts uses about 15 million tokens a month: $0.75.
- Prompts are sent to Amazon Bedrock in AWS's
us-east-1region, whatever region your database is in. Bedrock does not store them or use them to train models. If your data must stay in one region, use your own provider. - A prompt can be up to 50,000 characters.
- Your organization needs credit to spare: a month of your running databases,
plus $1. Without it, calls are refused with
insufficient_credits(402). - Calls are rate-limited per organization, at roughly 20 a second; past that they
are refused with
hosted_ai_rate_limited(429). Retry after a short wait.
Create namespaces in the console's Semantic cache section, which lists every cache in your organization with the database it lives in, or on a database's Semantic cache tab, or with the API below. Each cache shows its entries, hits, misses and hit rate, lets you browse and remove entries, and lets you try a lookup.
Choosing a threshold
The right threshold depends on the embedding model. As an example, with
OpenAI's text-embedding-3-small at 256 dimensions, a reworded question
("I forgot my password, how can I change it?" against "How do I reset my
password?") scored 0.75, another rewording 0.82, and an unrelated question
about 0. At 1536 dimensions the same rewording scored 0.61, while an unrelated
question ("What is the capital of Peru?") scored 0.11. The default of 0.6 catches
rewordings at either size and stays well clear of unrelated prompts; a stricter
0.9 misses rewordings entirely.
The hosted model, Titan Text Embeddings V2, scores lower. Measured with six pairs of reworded customer questions and four unrelated pairs:
| Dimensions | Rewordings | Unrelated |
|---|---|---|
| 256 | 0.34 to 0.78 | 0.09 to 0.29 |
| 512 | 0.29 to 0.78 | 0.04 to 0.15 |
| 1024 | 0.30 to 0.76 | 0.02 to 0.10 |
So a hosted namespace starts at 0.45, which caught four or five of the six rewordings at each size and no unrelated pair. At 1024 dimensions unrelated prompts score lowest, so you can go lower there with less risk.
Look at the best_score your misses report for prompts you consider the same
question, lower the threshold until those hit, and stop before unrelated
prompts do. A threshold that is too low returns answers to the wrong question,
which is worse than a miss. Scores can be slightly below 0 for unrelated text.
A single lookup can override the namespace's threshold.
Near misses: same question, different subject
No threshold protects you from a question that is worded like a cached one but asks about something else. On the hosted model at 1024 dimensions, with "Which regions does KiviDB support on Azure?" cached, "What regions does KiviDB support on Google Cloud?" scored 0.83, as high as a true rewording. With "How much does a 1 GB Essentials database cost on AWS?" cached, "How much does a Pro 25 GB database cost?" scored 0.66. Both would be served the cached answer, and both answers would be wrong.
Keep apart the things a single word changes, such as a cloud, a plan, a
product or a customer, with a scope. Give scope when you store an answer
and when you look one up:
POST /instances/{id}/semantic-cache/answers/entries
{ "prompt": "Which regions does KiviDB support?", "response": "...", "scope": "azure" }
POST /instances/{id}/semantic-cache/answers/lookup
{ "prompt": "What regions can I use?", "scope": "gcp" }
A lookup with a scope compares only against entries stored with exactly that
scope, so the Google Cloud question above can no longer get the Azure answer.
A lookup without a scope never matches a scoped entry, so answers stored for
one customer under customer-42 are not served to anyone else. Entries stored
without a scope behave as they always have. A scope is up to 128 letters,
digits, spaces and . _ : @ / -, and needs KiviDB 1.2 or later on the
database.
Writing the subject into the prompt is not a substitute. With [azure] and
[gcp] in front of the two region questions above, the pair still scored
0.83.
Thresholds and scores are cosine similarity on every KiviDB version. From
KiviDB 1.2, the engine's own VSIM ... WITHSCORES reports (1 + cosine) / 2,
from 0 to 1, as Redis does; the cache turns that back into cosine before it
compares, so a threshold you set before upgrading means the same afterwards.
If your own code calls VSIM directly, adjust its thresholds when you upgrade:
a cosine threshold t is (1 + t) / 2 on 1.2.
API
Calls are made with an API key from Settings → API keys. A key with the Member role (or higher) can store and look up; a Viewer key can only list namespaces and read their statistics. A key limited to particular databases works only on those databases.
| Method and path | |
|---|---|
GET /semantic-cache | every namespace in the organization, with its database |
GET /instances/{id}/semantic-cache | list namespaces |
GET /instances/{id}/semantic-cache/{name}/entries?offset= | a page of 25 entries, newest expiry first |
PUT /instances/{id}/semantic-cache/{name} | create or change a namespace |
GET /instances/{id}/semantic-cache/{name} | settings and statistics |
DELETE /instances/{id}/semantic-cache/{name} | delete it and everything cached in it |
POST /instances/{id}/semantic-cache/{name}/entries | store an entry |
POST /instances/{id}/semantic-cache/{name}/lookup | look up a prompt |
DELETE /instances/{id}/semantic-cache/{name}/entries/{entry} | remove one entry |
POST /instances/{id}/semantic-cache/{name}/flush | remove every entry and reset its counters, keep the settings |
Namespace names are 1–63 lowercase letters, digits, - or _. A database can
have up to 50 namespaces. Prompts and responses are limited to 100,000
characters each, and an entry's metadata to 8 KB of JSON.
Create a namespace
With hosted embeddings:
curl -X PUT https://api.kividb.io/instances/$DB/semantic-cache/support-bot \
-H "Authorization: Bearer $KIVIDB_API_KEY" -H "Content-Type: application/json" \
-d '{"provider": "kividb", "dimensions": 1024}'
With your own OpenAI key:
curl -X PUT https://api.kividb.io/instances/$DB/semantic-cache/support-bot \
-H "Authorization: Bearer $KIVIDB_API_KEY" -H "Content-Type: application/json" \
-d '{
"provider": "openai",
"model": "text-embedding-3-small",
"api_key": "'"$OPENAI_API_KEY"'",
"dimensions": 1536,
"threshold": 0.9,
"default_ttl_seconds": 86400
}'
To change settings later, send the same request; leave out api_key to keep
the stored one. Changing dimensions or the embedding model needs an empty
namespace (flush it first): vectors from two models cannot be compared, even
when they have the same number of dimensions.
Look up, and store on a miss
import os, requests
API = "https://api.kividb.io"
DB = os.environ["KIVIDB_DATABASE_ID"]
H = {"Authorization": f"Bearer {os.environ['KIVIDB_API_KEY']}"}
NS = f"{API}/instances/{DB}/semantic-cache/support-bot"
def answer(prompt: str) -> str:
hit = requests.post(f"{NS}/lookup", json={"prompt": prompt}, headers=H, timeout=30).json()
if hit["hit"]:
return hit["response"]
response = call_your_model(prompt) # the slow, paid call
requests.post(f"{NS}/entries", json={"prompt": prompt, "response": response}, headers=H, timeout=30)
return response
A hit returns:
{
"hit": true,
"id": "3f9c0d4e5a6b7c8d9e0f",
"score": 0.962,
"prompt": "How do I reset my password?",
"response": "Open Settings, then Security, then Reset password.",
"metadata": {},
"created_at": "2026-10-23T09:14:00.000Z",
"embed_ms": 180,
"latency_ms": 196
}
and a miss:
{ "hit": false, "best_score": 0.71, "threshold": 0.9, "embed_ms": 175, "latency_ms": 181 }
embed_ms is the time the embedding provider took; the rest of latency_ms is
the cache itself.
Your own vectors
With "provider": "none", send the prompt's embedding yourself:
POST /instances/{id}/semantic-cache/{name}/entries
{ "prompt": "…", "response": "…", "vector": [0.012, -0.08, …] }
POST /instances/{id}/semantic-cache/{name}/lookup
{ "vector": [0.011, -0.07, …] }
You can also send vector on a namespace that has a provider, to skip the
embedding call.
Store options
| Field | |
|---|---|
ttl_seconds | keep this entry for this long instead of the namespace's default (60 seconds to a year) |
metadata | any JSON object, returned with a hit (a model name, a source document id) |
What is stored in your database
Each namespace uses keys under kividb:semcache:{name}: — a vector set of the
prompts' embeddings, one hash per entry that expires with it, a sorted set of
expiry times, and a hash of counters. All of a namespace's keys share the hash
tag {name}, so on a sharded database a namespace lives on one shard. Leave
these keys to the cache: changing them by hand can make entries unreachable.
The entries count toward the database's memory like any other data.