How to Cache Embeddings by Content Hash
Avoid re-embedding identical text by keying a cache on a content hash and the model version, with LRU eviction and stampede protection.
On this page
Introduction
Embedding calls are the slow, metered part of many pipelines: they cost money per token, they add latency to every ingest or query, and the same text is embedded over and over because documents repeat boilerplate, users retype questions and chunks overlap. Caching embeddings by content hash removes that repeated work. The cache key must include the model and its parameters, because an embedding is only valid for the model that produced it, and the cache must be bounded and stampede-safe or it will exhaust memory and amplify load under concurrency.
What Makes an Embedding Cacheable
An embedding is a pure function of (model, parameters, text). If any of those differ, the vector is not interchangeable. So the cache key is a hash over the text plus a fingerprint of the model and its options such as dimensions and normalisation. Omitting the model from the key is the classic bug: after upgrading the model the cache returns vectors from the old one, and similarity scores become meaningless.
Cache the vector, not the retrieval result, unless the retrieval parameters are also part of the key. Two queries with identical text but different top_k or filters are different operations and should not share a cache entry. Keep the boundary of the cache at the embedding call so the rest of the pipeline stays unchanged.
import { createHash } from 'node:crypto';
const MODEL = 'text-embedding-3-small';
const OPTIONS = { dimensions: 1536, normalize: true };
export function embeddingKey(text: string): string {
const h = createHash('sha256');
h.update(MODEL);
h.update(JSON.stringify(OPTIONS));
h.update(text);
return h.digest('hex');
}
Building a Bounded LRU Cache
An unbounded cache grows until it exhausts memory, because every distinct chunk and every distinct query adds an entry. Bound it by entry count or by bytes, and evict with least-recently-used order so the working set stays resident. Embeddings are large: a 1536-dimensional float32 vector is about six kilobytes, so a hundred thousand entries is over half a gigabyte before overhead.
Measure the hit rate before and after sizing the cache. If the hit rate is low, the corpus is too diverse for the cache to pay off and the memory is wasted; if it is high, a larger cache is usually worth it. Report both sizes and the eviction counter, because a cache that evicts hot entries is mis-sized.
class LruEmbeddingCache {
private map = new Map<string, number[]>();
constructor(private maxEntries: number) {}
get(key: string): number[] | undefined {
const value = this.map.get(key);
if (value === undefined) return undefined;
this.map.delete(key); // move to most-recently-used
this.map.set(key, value);
return value;
}
set(key: string, value: number[]): void {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.maxEntries) {
const oldest = this.map.keys().next().value as string;
this.map.delete(oldest); // evict LRU
}
}
}
Stampede Protection with Single-Flight
When many requests need the same uncached embedding at once, a naive cache issues one upstream call per request and the cache does nothing under load. Single-flight collapses concurrent misses for the same key into one in-flight promise that all callers await. Combined with the cache, a burst of identical queries results in exactly one embedding call.
Guard against a thundering herd on model upgrade too. When the model fingerprint changes, every key misses at once; a warm-up job that pre-populates the new keys before the switchover keeps the switch from turning into a spike. And always set a timeout on the in-flight call so a stuck request cannot poison every waiter.
const inFlight = new Map<string, Promise<number[]>>();
export async function embedWithCache(text: string, cache: LruEmbeddingCache, embed: (t: string) => Promise<number[]>) {
const key = embeddingKey(text);
const cached = cache.get(key);
if (cached) return cached;
const existing = inFlight.get(key);
if (existing) return existing; // dedupe concurrent misses
const promise = embed(text)
.then((vec) => { cache.set(key, vec); return vec; })
.finally(() => inFlight.delete(key));
inFlight.set(key, promise);
return promise;
}
A Durable Cache Layer
An in-process cache dies with the process, so a restart re-embeds everything. A shared cache such as Redis keeps entries across instances and shrinks the fleet-wide miss rate, at the cost of a network hop and serialization. Store the vector compactly, for example as a Float32 buffer, and set a TTL aligned with how often the model changes.
Key the shared cache with the same content hash so in-process and shared layers agree. Use a two-level strategy: an in-process LRU in front of a shared store, so the hottest keys are answered without a network call. This mirrors a tiered cache, with the upstream embedding API as the origin.
# Two-level lookup order
1. in-process LRU -> ~microseconds, hottest keys
2. shared Redis -> ~1 ms network hop, fleet-wide hits
3. embedding API -> slow + metered, the origin
on miss at level 1: check level 2
on miss at level 2: call API, then backfill level 2 and level 1
always key all levels by sha256(model + options + text)
Invalidation and Versioning
Embeddings rarely need fine-grained invalidation because the model version is in the key: changing the model changes every key, and old entries simply stop being read. That makes upgrade-time cache waste, not corruption. Let old entries expire by TTL rather than trying to delete them eagerly, which can be expensive across instances.
If you change preprocessing such as lowercasing or stripping whitespace before embedding, that change must be part of the fingerprint, or cached vectors will reflect the old preprocessing. Treat every code change that affects the input text to the model as a version bump in the cache key.
Measuring Impact
Track cache hits, misses, evictions, single-flight collapses and the cost saved in tokens. The token-savings counter is the business case: multiply avoided tokens by the price per token and the cache pays for itself visibly. Also watch the p95 latency of embedded operations, which should drop as the hit rate rises.
A useful health metric is the ratio of unique keys to total lookups. If every lookup is a unique key, the cache is pure overhead; if the ratio is low, the cache is doing real work. Watch this ratio over time as the corpus grows, because a growing ratio means the cache is falling behind the working set.
Common Pitfalls and Conclusion
Do not omit the model from the key. Do not cache by raw bytes when the meaningful input is normalised text, or trivial formatting differences will miss. Do not leave the cache unbounded. Do not skip single-flight, or a burst defeats the cache exactly when it matters. And do not forget that a stale cache after a preprocessing change silently mixes incompatible vectors.
Embedding caching is a small amount of code with a large payoff: a content-and-model hash as the key, an LRU in front of a shared store, single-flight to collapse concurrent misses, and metrics that prove the savings. Keyed correctly and bounded properly, it turns the most expensive repeated operation in the pipeline into a lookup.
Sources: OpenAI: Embeddings, Redis: Caching patterns, MDN: SubtleCrypto.digest.
FAQ
- Why include the model name in the cache key?
- An embedding is only comparable with vectors from the same model and parameters. If the model changes and the key does not, the cache returns vectors from the old model and similarity scores become garbage. The fingerprint makes the upgrade a clean cache miss instead of silent corruption.
- Is a shared cache worth the network hop?
- When many instances embed overlapping content, yes: it turns a fleet-wide miss rate into a shared hit rate. Put an in-process LRU in front of it so the hottest keys avoid the hop entirely, and keep the shared store as the next level.
Report a problem with this articleOpens a pre-filled issue on GitHub.