Build an Embedding Cache for Deduplicating Repeated Queries
caching databases performance
AI System Design Deep Dive
Embedding Cache for Repeated Queries
The cheapest embedding is the one you already computed, if you can recognise it.
A search platform embeds every query before it can look anything up. Ours does that 31,000 times a second on average, 48,000 at peak, 2.68 billion times a day, for a 110M-parameter model that turns a 14-token string into 768 floats. On an L4 GPU a batch of 32 takes about 9ms, so one card sustains roughly 2,400 embeddings a second once tokenisation and host-device transfers are counted, and we hold each card to 55% utilisation to keep the queueing tail honest. Do the division and the uncached answer is 37 GPUs at about $587 each per month, $21,700, to compute the same few million vectors over and over.
Think of a reference librarian who re-derives the call number for the most popular book in the building every time someone asks for it. Each derivation is correct and fast. The cost is not any single lookup, it is that the work is repeated 2.68 billion times a day while the answers barely change. A card taped to the desk with the call number on it beats a faster librarian.
The card is the easy part. The hard part is deciding when two requests are the same question. Quarterly revenue by region and quarterly revenue by region? and quarterly revenue by region with a double space are one question to a human and three different strings to a hash map. If 40% of requests arrive in some non-canonical surface form, an exact-string cache leaves a large share of its hits unrecognised. In a replay of a Zipf-distributed workload with those properties, raw keys held a 50.2% hit rate at 80M entries, and canonical keys held 61.8% in the same memory.
A naive cache also fails in the opposite direction. LRU admits everything, and 58% of the distinct queries in a day are asked exactly once. Each of those evicts something useful to make room for a 1.6 KB vector nobody will read again. And the moment a hot key expires, thousands of in-flight requests per second discover the miss at once and send the same text to the GPU.
We need to solve for key identity, admission, and fill coordination simultaneously, and keep the cache from ever serving a vector that belongs to a different model.
Hit rate on an embedding cache is decided mostly by the key function and the admission rule, not by how much RAM you buy. Normalising the key was worth about twice what doubling the cache was worth in our replay.
Requirements and Constraints
Functional Requirements
- Return the 768-dimension query embedding for any text, computing it on a GPU only when no valid cached vector exists.
- Treat trivially different spellings of one query (case, whitespace, trailing punctuation, Unicode forms) as one key.
- Never return a vector produced by a different model, tokenizer, prompt template, or normaliser version than the one the index was built with.
- Collapse concurrent requests for the same missing key into one GPU computation.
- Roll to a new embedding model without a latency or GPU-cost cliff.
Non-Functional Requirements
- Latency: L1 hit under 0.1ms, L2 hit 0.9ms p50 and 2.5ms p99, miss path 12ms p50 and 34ms p99 for a batch of 32 on an L4.
- Throughput: 48,000 requests per second at peak, 31,000 average, 2.68 billion per day.
- Quality: a cached vector must match a fresh computation at cosine 0.999 or better; normalisation must not move downstream ANN top-10 overlap below 0.98 Jaccard.
- Cost: under $0.15 per million queries all-in, against $0.27 uncached.
- Capacity: L1 at 204 MB per router pod, L2 at roughly 137 GB across four Redis primaries, doorkeeper Bloom filter at 0.7 GB per filter.
Constraints
- Model:
intfloat/e5-base-v2, 768 dimensions, uncased tokenizer,query:prefix, mean pooling, FP16 on L4 GPUs. The uncased tokenizer is what makes case folding safe. A cased model changes the normaliser rules. - Hardware:
g6.xlargenodes at about $0.805 an hour,r7g.2xlargeRedis nodes at about $0.428 an hour (list prices, us-east-1, checked November 2026). - Out of scope: caching ANN results. The previous post measured a 4.1% hit rate on result caching, because embedding-space queries are nearly all unique even when the text is similar. This post caches the embedding, keyed on text, where the repetition actually lives. LLM answer caching and cross-lingual query matching are also out of scope.
Hit rates in this post come from a simulated workload, not a production trace: Zipf exponent 0.92, 6M requests over a 3M-key universe, 40% of requests in a non-canonical surface form, with cache capacity scaled as a fraction of daily volume. They show the shape and the ordering of the design choices. Calibrate the absolute numbers on your own query log before you size anything.
Cost is the requirement that shapes the rest. The whole four-shard Redis cluster costs about what five GPUs cost, so every requirement about hit rate is really a requirement about the key function and the admission rule.
High-Level Architecture
Six components sit on the query path, and every request ends at ANN search holding a 768-dimension vector.
- Normalizer canonicalises the text and builds a 16-byte key from the model fingerprint and the canonical string.
- L1 cache is an in-process LRU of 120,000 vectors per router pod, 204 MB, no network hop.
- Single-flight table guarantees at most one fill per key per pod, and a Redis lock extends that across pods.
- L2 Redis cluster holds about 80M vectors across four primaries, evicting with approximate LRU.
- Doorkeeper is a Bloom filter that admits a key to L2 only on its second sighting.
- Model registry holds the fingerprint of the serving model and the rollout state of the next one.
- Miss batcher and GPU workers gather misses for at most 2ms or 32 items and run one forward pass.
A request flows left to right through the router pod. The text is canonicalised in 20 microseconds, hashed with the model fingerprint into a key, and looked up in the pod’s L1. About 14.6% of requests end there. The rest join or start a flight for that key, read L2 with a 6ms timeout, and another 49.4% of all traffic ends there with a 0.9ms read. The remaining 36.0% acquire a fill lock, wait up to 2ms in the batcher, run on a GPU, and return in 12ms at the median.
The write-back is where admission happens. The vector is placed in L1 immediately, and written to L2 only if the doorkeeper has seen the key before. A one-off query pays for one GPU forward pass and nothing else, and never displaces a vector that has been read a hundred times.
The most important decision is that the model fingerprint is part of the key, not a cache setting. A model upgrade then changes every key at once, so a stale vector is unreachable instead of wrong, and no flush, scan, or DEL is ever needed.
The Key Builder
The key builder turns raw text into a 16-byte identity such that two requests share a key exactly when they would produce the same vector.
A smart engineer assumes the key is a hash of the query string. It is a hash of the string plus everything that shaped the vector, and the second half is where the cache gets its safety. The fingerprint covers the weights, the tokenizer, the prompt template, the pooling mode, the output dimension, the dtype, and the version of the normaliser itself. Change any one and every key changes. This is the same discipline as a content-addressed build cache: the key is the full set of inputs, so a stale hit cannot exist.
Canonicalisation is the other half, and it is a trade of precision for hit rate that you have to measure. The rules below are valid for an uncased BERT-family model, where the tokenizer already lowercases and strips accents, so folding them in the key loses nothing the model could see.
Normalisation is a bet that the model cannot tell two strings apart. Each rule is exactly as safe as the measurement behind it, so a few tested rules beat many clever ones.
# Canonicalize raw query text and build a keyed 16-byte cache key
import hashlib
import re
import unicodedata
NORMALIZER_VERSION = 3
MAX_CACHEABLE_CHARS = 256
_CONTROL = re.compile(r"[\u0000-\u001f\u007f-]")
_SPACE = re.compile(r"\s+")
_TAIL = re.compile(r"[\s?!.,;:]+$")
def canonicalize(text: str) -> str | None:
t = unicodedata.normalize("NFKC", text)
t = _CONTROL.sub("", t).casefold()
t = _TAIL.sub("", _SPACE.sub(" ", t).strip())
if not t or len(t) > MAX_CACHEABLE_CHARS:
return None # empty or long queries bypass the cache
return t
def model_fingerprint(weights_sha: str, tokenizer_sha: str, template: str,
pooling: str, dim: int, dtype: str) -> bytes:
h = hashlib.sha256()
for part in (weights_sha, tokenizer_sha, template, pooling,
str(dim), dtype, str(NORMALIZER_VERSION)):
h.update(part.encode("utf-8"))
h.update(b"\x1f")
return h.digest()[:8]
class KeyBuilder:
def __init__(self, fingerprint: bytes, secret: bytes):
self.fp = fingerprint
self.secret = secret # per-environment, from the secret manager
def key(self, canon: str) -> bytes:
return hashlib.blake2b(self.fp + b"\x1f" + canon.encode("utf-8"),
digest_size=16, key=self.secret).digest()Premium Content
Unlock the full article along with everything else in the archive — all in one place.