Embedding cache: never embedding the same text twice
An embedding cache stores the vector for a piece of text, keyed by a hash of the text and the embedding model version. Use it when the same chunks or queries are embedded repeatedly, such as re-indexing or repeat searches.
Embedding cache in 60 seconds
- What: a store from a hash of the text plus the embedding model version to the vector that model produced.
- Saves: repeated embedding calls, which matters most during re-indexing, re-chunking and for common search queries.
- Safe by design: the same text and model always give the same vector, so a hit is identical to a fresh result.
- Key must include: the model version, and any text preprocessing that changes the input.
- Cost: storage. A vector can take several kilobytes, so cap the size and expire unused entries.
Where this type fits
The embedding cache is an application-controlled cache, and it is the safest of them. Unlike the semantic cache it never changes what a user sees, because it returns the very vector a fresh call would. The caching hub compares it with the exact-match and retrieval-result caches. It supports the retrieval steps described in vector search and chunking.
The problem it solves
Embedding work is repeated more often than most teams expect. When you rebuild a search index after changing the chunk size, most chunks are the same as before, yet each is embedded again. When a document is edited, only a few paragraphs change, but a naive pipeline re-embeds the whole file. At query time, popular searches arrive again and again, and each is embedded on every request.
Each embedding call has a price and a delay. A large re-index may involve millions of chunks. Query-time embedding sits directly in the user's wait, before search can begin. Calls to a hosted embedding service can also hit rate limits, which slows batch jobs further.
An embedding cache removes the repeats. The first time a text is embedded, the vector is stored. Every later request for the same text with the same model reads the stored vector. Because embedding is deterministic for a given model and input, nothing about quality changes.
How it works
- Prepare the text: apply the exact preprocessing used for embedding, such as trimming, lower-casing or adding a title prefix.
- Build the key: hash the prepared text together with the embedding model name and version, and any setting that changes the output, such as vector size.
- Look up: ask the cache store for that key.
- Hit: reuse the stored vector. For indexing, write it straight into the vector index.
- Miss: call the embedding model, store the vector under the key, then use it.
- Expire and cap: remove entries that go unused for a set time, and cap total size.
The model version in the key is essential. Vectors from different embedding models are not comparable, and even a minor model update can shift them. If the key lacks the version, you can mix old and new vectors in one index, and search quality drops without any error. With the version in the key, an upgrade just causes misses, and the cache refills with new vectors.
The cache lives beside the index, not inside it. The vector index is built for similarity search. The embedding cache is a simple key-value store, which is cheaper and simpler to run.
A worked example
Acme keeps 200,000 help-centre chunks in a vector index. The team decides to change the chunk size, which changes the boundaries of many chunks, but the title prefix and cleaning rules stay the same.
- Before the change: the cache holds vectors for 200,000 chunk texts, keyed by hash and model 'emb-v2'.
- Re-chunking: the new pipeline produces 190,000 chunks. About 120,000 have identical text to old chunks, because short articles were not split differently.
- Lookup: for each new chunk the pipeline hashes the text plus 'emb-v2'. About 120,000 are hits and go straight to the new index. About 70,000 are misses and are embedded in batches, then stored.
- Result: the job makes 70,000 embedding calls instead of 190,000, and runs correspondingly faster.
- Model upgrade later: the team moves to 'emb-v3'. Every key changes, so every lookup misses. This is expected. The full re-embedding refills the cache with v3 vectors, and v2 entries expire.
- Query time: the search box embeds each query. The query 'reset password' arrives 800 times a day, so it hits the cache after the first time and skips the embedding call.
Building it
import hashlib
import struct
# Placeholders: embed_batch(texts) calls your embedding model and returns a list of float lists;
# store is a key-value store with get_many(keys), set_many(items, ttl_seconds).
MODEL = 'emb-v2' # include the exact model version in every key
DIMENSIONS = 768 # part of the key: a different size is a different vector
TTL_SECONDS = 30 * 24 * 3600 # expire entries that nobody reads, to cap storage
BATCH_SIZE = 64 # embedding calls work best in batches, and respect rate limits
def prepare(text):
return ' '.join(text.split()) # same cleaning used in indexing and queries
def key_for(text):
raw = f'{MODEL}|{DIMENSIONS}|{prepare(text)}'
return 'emb:' + hashlib.sha256(raw.encode()).hexdigest()
def pack(vector):
return struct.pack(f'{len(vector)}f', *vector) # compact binary, not JSON text
def unpack(blob):
return list(struct.unpack(f'{len(blob) // 4}f', blob))
def embed_with_cache(texts, embed_batch, store, metrics):
keys = [key_for(t) for t in texts]
found = store.get_many(keys) # one round trip for all keys
result = {}
missing = []
for t, k in zip(texts, keys):
if k in found:
result[k] = unpack(found[k])
metrics.count('embedding_hit')
else:
missing.append((t, k))
for i in range(0, len(missing), BATCH_SIZE):
chunk = missing[i:i + BATCH_SIZE]
vectors = embed_batch([prepare(t) for t, _ in chunk])
store.set_many([(k, pack(v)) for (t, k), v in zip(chunk, vectors)], TTL_SECONDS)
for (t, k), v in zip(chunk, vectors):
result[k] = v
metrics.count('embedding_miss', len(chunk))
return [result[k] for k in keys] # keep the caller's original order
Three details matter. The key holds the model, the dimension size and the cleaned text, so a change to any of them creates a clean miss. The vectors are stored in compact binary form to keep storage small. And lookups and embedding calls are batched, which cuts round trips and respects service limits.
Design decisions
- Key contents: hash the prepared text with model name, version and dimensions. Default to including anything that can change the vector.
- Storage choice: use a key-value store, not the vector index. Keep vectors in compact binary form to cut size by several times versus text.
- TTL and size cap: expire unused entries after weeks, and cap total size with least-recently-used eviction. Vectors are large, so unbounded growth is the main operating risk.
- Privacy: the key is a hash, but the vector can still reveal information about the text. Apply the same access rules and deletion rules as the source data, including removal on a deletion request.
- Model upgrades: plan for a full miss on upgrade. Keep the old and new caches side by side during migration, then drop the old one.
- Failure handling: if the cache is down, call the embedding model directly. Slower and dearer is fine, but never serve a wrong vector.
- Placement: put it in the shared indexing pipeline and the query service, so both use one implementation.
Measuring it
- Hit rate: hits divided by lookups, reported separately for indexing jobs and for query-time calls, because they behave differently.
- Embedding calls avoided: hits multiplied by the cost per call, which is the saving.
- Job duration: time to rebuild an index with a warm cache versus a cold cache.
- Query latency: p50 and p95 of the embedding step for hits and misses.
- Storage per entry and total size: bytes used, and the share of entries read at least once before expiry.
- Equivalence check: for a random sample of hits, re-embed the text and confirm the vector matches within floating-point tolerance. A mismatch points to a key problem.
import math, random
def verify_sample(cached, embed_batch, n=100, tol=1e-4):
"""cached: dict text -> stored vector. embed_batch is a placeholder model call."""
texts = random.sample(list(cached), min(n, len(cached)))
fresh = embed_batch(texts)
bad = 0
for t, f in zip(texts, fresh):
dist = math.sqrt(sum((a - b) ** 2 for a, b in zip(cached[t], f)))
if dist > tol:
bad += 1
return bad / max(len(texts), 1) # should be about zero
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Frequent re-indexing or re-chunking of a large corpus | Yes | Most chunks are unchanged, so most embeddings can be reused. |
| Common search queries repeated by many users | Yes | The query embedding is computed once and reused. |
| Documents edited in small ways | Yes | Only the changed chunks need new vectors. |
| One-off embedding of a corpus that will not be rebuilt | No | Nothing repeats, so the cache only adds storage. |
| Unique, long, never-repeated inputs | No | Hit rate will be near zero. |
| Very small embedding bills and fast local models | Probably not | The saving may not justify the extra storage and code. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | No change, since the same vector is reused | Run the equivalence check and include the model version in the key. |
| Latency | Faster query embedding on a hit, and much faster index rebuilds | Report hit and miss latency separately. |
| Cost | Fewer embedding calls, but more storage | Cap size and expire unused entries. |
| Complexity | Low, with one extra lookup step | Share one implementation between indexing and queries. |
| Failure modes | Mixed vectors after a model change, and stale data after deletion requests | Version the key and delete cached vectors with their source. |
Compared with related types
The semantic cache embeds each question and then searches for similar past questions. The embedding cache is a different layer and works well underneath it: it makes the embedding step cheap, while the semantic cache decides whether to reuse an answer. Only the semantic cache can return an answer to a different question.
The retrieval-result cache sits one step later. It stores which chunks a search returned, so repeated queries skip the index search as well. Use the embedding cache for the vector, and the retrieval cache for the search result.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems: the hub that compares every cache type.
- Vector search and chunking: how chunks become vectors and how search works.
- Retrieval-result cache: the next layer, which caches search results.
- Simple RAG: a pipeline that embeds both chunks and questions.
An embedding cache is a quiet saving with little risk. Key it by text and model version, bound its size, and it pays for itself on every rebuild.