The Semantic Cache API: Stop Paying Your LLM to Answer the Same Question Twice

Murtaza Shajapurwala ·

Users ask the same question in a dozen different ways. "How do I reset my password?", "I forgot my password, how can I change it?" and "can't log in, need a new password" are one question to a person, and three separate, slow and paid calls to a language model.

A semantic cache answers the second and third from the first. It keeps each answer with the prompt that produced it and, when a new prompt is close enough in meaning, returns the stored answer instead of calling the model again.

Today every KiviDB Cloud database can hold semantic caches, through a REST API, the console and the MCP server. The cache lives in your own database: nothing you cache is sent anywhere else.

How it works

One lookup before the model: a hit returns the stored answer, a miss calls the model and stores its answer

You create a namespace: one cache with its own settings. Then your application makes one call before the model:

  1. Lookup. The prompt is turned into a vector (an embedding), and the cache finds the closest stored prompts. If one is similar enough, it is a hit: you get its response back and skip the model.
  2. Miss. Nothing was close enough. You call your model as usual, then store the prompt and the response, so the next person to ask it is a hit.

In Python, the whole integration is this:

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 comes back with the similarity score and the stored entry:

{
  "hit": true,
  "score": 0.821,
  "prompt": "How do I reset my password?",
  "response": "Open Settings, then Security, and choose Reset password.",
  "metadata": {},
  "embed_ms": 180,
  "latency_ms": 196
}

embed_ms is the time your embedding provider took; the rest of latency_ms is the cache itself.

Bring your own embeddings

Each namespace chooses how prompts become vectors:

  • OpenAI, with your API key and a model such as text-embedding-3-small.
  • Any OpenAI-compatible endpoint: a self-hosted model, a gateway, another provider that speaks OpenAI's /embeddings API.
  • None: you send the vector yourself with every call, for teams that already compute embeddings or want full control.

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

Creating a namespace is one request:

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.78,
    "default_ttl_seconds": 86400
  }'

Where it pays off

Four use cases: support assistants, docs and RAG answers, agent steps, and classification and routing

A semantic cache helps wherever many people ask the same thing in different words, and the answer does not depend on who is asking.

  • Support assistants. The top questions (password resets, refunds, plan limits) make up a large share of traffic, asked a hundred ways. Each is answered by the model once.
  • Docs and RAG answers. A question already answered from your documentation skips both retrieval and generation. Give the namespace a longer time to live (a week, say) and flush it when the docs change.
  • Agent steps. An agent that plans the same sub-task again gets the earlier result instead of another model round trip. With provider: none, the agent framework's own vectors are used as they are.
  • Classification and routing. Intent labels, categories, which model a request goes to: decided once for each kind of message. Store the decision in the entry's metadata and it comes back with every hit.

Where it does not fit: answers that depend on the user, their account or the time, unless that context is part of the prompt. A cache returns what was true for the prompt that was stored.

Getting the threshold right

The threshold is the similarity a lookup must reach to count as a hit, from 0 to 1. It is the one setting that decides whether the cache is useful, and the right value depends on the embedding model.

Similarity scale measured with OpenAI text-embedding-3-small: two rewordings scored 0.75 and 0.82, an unrelated question about 0; a threshold of 0.74 catches both rewordings, the default 0.9 misses both

We measured it while building the feature, with OpenAI's text-embedding-3-small. Against "How do I reset my password?", the rewording "I forgot my password, how can I change it?" scored 0.75, another rewording 0.82, and an unrelated question about 0. The default threshold of 0.9 would have missed both rewordings; a threshold just under 0.75 caught them.

So tune it from your own traffic. Every miss reports best_score, the closest similarity it found. Collect misses for prompts you consider the same question, lower the threshold until they hit, and stop before unrelated prompts do. A threshold that is too low returns an answer to the wrong question, which is worse than a miss. A single lookup can also override the namespace's threshold, which makes it easy to test a value before you commit to it.

In the console

The Semantic cache panel on a database's Search tab: the support-bot namespace with its model, threshold and time to live, its entries, hits, misses and hit rate, and a lookup that hit with similarity 0.821

Each database's Search tab has a Semantic cache panel. Create namespaces there, watch each one's entries, hits, misses and hit rate, and try a lookup or store an entry by hand while you tune the threshold. (The screenshot shows an example namespace.)

The same operations are available as tools in the KiviDB MCP server, so an assistant connected to your account can list caches, look up and store entries, and flush a namespace.

What is stored, and where

A namespace is a handful of keys in your database under kividb:semcache:{name}:: a vector set of the prompts' embeddings, a 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 one hash tag, so on a sharded database a namespace lives on one shard.

  • Time to live: every entry expires, after the namespace's default (24 hours unless you set it) or a time you give when storing it, from a minute to a year.
  • Limits: up to 50 namespaces per database; prompts and responses up to 100,000 characters each; up to 8 KB of JSON metadata per entry.
  • Access: a Member API key can store and look up; a Viewer key can only list namespaces and read their statistics; a key limited to some databases works only on those.
  • Cost: entries count toward the database's memory like any other data. There is no separate charge for the API.

Get started

  1. Create an API key under Settings → API keys.
  2. Create a namespace from the database's Search tab, or with the PUT request above.
  3. Put one lookup in front of your model call, and store on a miss.

The semantic cache docs have the full API, and the semantic cache page has the overview. If you would rather build your own on KiviDB's vector search, our earlier post on semantic caching with a Redis-compatible vector database walks through it with code.