Summary#
A vector database stores embeddings, which are arrays of hundreds or thousands of numbers produced by a machine-learning model. It answers one question fast: which stored items are most similar to this one? Similar meanings, images, products or users end up as nearby points in a high-dimensional space, so "find similar" becomes "find the nearest points".
Comparing a query against every vector is exact but slow. At a million 1,536-dimension vectors, that's billions of floating-point operations and gigabytes of memory traffic per query. Vector databases therefore use approximate nearest neighbour (ANN) indexes:
- HNSW, a layered graph you walk greedily;
- IVF, which clusters vectors and searches only the nearest clusters;
- product quantization, which compresses vectors 30–60x.
These answer in a few milliseconds while finding about 95–99% of the true nearest neighbours. Every deployment is a deliberate trade between recall, latency and memory.
Production use adds harder problems: metadata filters ("similar and in stock"), hybrid keyword-plus-vector ranking, index maintenance under inserts and deletes, re-embedding when the model changes, and sharding billions of vectors. The practical rule is to start with what you already run: pgvector in Postgres, Elasticsearch or OpenSearch kNN, or Redis. Move to a purpose-built engine (Pinecone, Milvus, Weaviate, Qdrant) when scale, often beyond about 100 million vectors, or filtering and QPS needs demand it.
Vector search powers semantic search, RAG (retrieval-augmented generation for LLMs), recommendations, image and audio similarity, deduplication and anomaly detection. It's always an index over data whose source of truth lives elsewhere.
Why It Exists#
Traditional databases excel at exact questions:
- "the user with id 12345";
- "orders placed on 1 January";
- "products whose title contains 'running shoe'".
B-trees, hash indexes and inverted indexes (Database Indexing) all assume you can say exactly what matches.
Many valuable questions aren't exact:
- A support user types "I can't get into my account". The best help article is titled "Resetting your password", and it shares no keywords with the query.
- A shopper looks at a photo of a green velvet armchair and wants "things like this".
- A streaming service wants songs that sound like the one you just replayed five times.
- An LLM assistant needs the three paragraphs from 2 million internal documents most relevant to a question, so it can answer with citations instead of hallucinating.
- A marketplace wants to flag a new listing as a near-duplicate of one posted yesterday with a reworded title.
Keyword search fails on vocabulary mismatch. Hand-written rules don't scale. What these problems need is a numeric representation of meaning, where "similar" is something you can compute.
Machine learning supplies that representation. An embedding model maps each item to a fixed-length vector, so that items the model considers similar land close together. "The cat sat on the mat" and "A feline rested on a rug" produce vectors that are nearly identical. "The stock market crashed" lands far away.
Once data is vectors, similarity search becomes nearest-neighbour search in high-dimensional space, and that turns out to be hard to do fast:
- Brute force is expensive at scale. 10 million vectors × 768 dimensions × 4 bytes is about 30 GB to stream per query. Even at 20 GB/s of memory bandwidth that's 1.5 seconds per query, with a full CPU core kept busy, so a few hundred QPS needs a warehouse of machines.
- Classic spatial indexes collapse in high dimensions. k-d trees, R-trees and the geohash and quadtree ideas from Geospatial Indexing and Proximity Search prune beautifully in 2 or 3 dimensions. Beyond about 20 dimensions, nearly every region of the space is "close" to the query, so they degrade to scanning everything. This is the curse of dimensionality.
- Relational engines weren't built for it. They have no operator for "ORDER BY distance to this 1,536-number array" that can use an index.
Vector databases exist to make this primitive fast, scalable and operable. They provide approximate indexes with tunable accuracy, compression to fit billions of vectors into RAM, metadata filtering, hybrid ranking, sharding and replication, and APIs for keeping indexes fresh while data and models change.
The idea isn't new. Recommendation systems have used nearest-neighbour search over learned vectors for well over a decade. Spotify built Annoy, and Meta (then Facebook AI Research) released FAISS in 2017. Two things changed, which turned it from a niche recommender component into a mainstream infrastructure category:
- Embedding models got dramatically better (transformers, CLIP).
- LLMs created an urgent need to ground generation in private data.
How It Works#
Embeddings: turning things into points#
An embedding (or vector) is an array of floats, such as [0.12, -0.34, 0.78, ..., 0.45], that represents an item. The individual dimensions usually mean nothing to humans. What matters is the geometry: the distances and angles between vectors mirror whatever notion of similarity the model learned.
"The cat sat on the mat" → [ 0.12, -0.34, 0.78, ..., 0.45] (1,536 numbers)
"A feline rested on a rug" → [ 0.11, -0.32, 0.79, ..., 0.44] ← nearly identical
"The stock market crashed" → [-0.89, 0.12, -0.45, ..., 0.23] ← far awayWhere embeddings come from:
- Pre-trained general models. These cover text (OpenAI's embedding API, open models such as Sentence-Transformers / SBERT, BERT-family encoders, E5, BGE), images (CLIP, ResNet features), audio and code. To the system designer, the model is an expensive function: content goes in, a fixed-length vector comes out. It typically runs on a GPU at 1–50 ms per item, or behind a paid API. CLIP (Radford et al., 2021) is notable because it embeds images and text into the same space, so "a photo of a green armchair" can retrieve images directly.
- Task-specific trained models. "Similar" can mean something precise to the business. For recommendations, diapers and baby bottles are only loosely similar semantically, but are profoundly similar in that new parents buy both. A custom model is trained so that items bought or watched together end up close. The usual architecture is a two-tower model: one network embeds users or queries, another embeds items, and training pushes the dot product of matching pairs up and non-matching pairs down. This is contrastive learning. The distance metric is then whatever the training objective optimised.
Typical dimensions range from 128 to 3,072:
- many open-source text models use 384 or 768;
- OpenAI's
text-embedding-3-smallproduces 1,536 andtext-embedding-3-largeproduces 3,072; - recommender item embeddings are often 64–256.
Memory per vector is 4 bytes per dimension as float32, so a 1,536-dim vector is 6 KB. That's bigger than the text chunk it represents. A million of them is 6 GB before any index overhead.
Some models are trained with Matryoshka representation learning ("Matryoshka Representation Learning", Kusupati et al., NeurIPS 2022). The first 256 or 512 dimensions form a usable lower-resolution embedding on their own, so you can truncate vectors for a cheap first pass and use the full vector to re-rank.
Embeddings belong to their model. A vector from model A is meaningless next to one from model B, even at the same dimension. Changing or upgrading the model means re-embedding everything. That's the root cause of one of the biggest operational problems, covered in a deep dive at the end of this page.
Similarity metrics#
Given two vectors a and b of dimension d:
| Metric | Formula (intuition) | Range / meaning | Notes |
|---|---|---|---|
| Euclidean (L2) distance | √Σ(aᵢ − bᵢ)²: straight-line distance | 0 = identical; smaller = closer | Sensitive to both direction and magnitude |
| Cosine similarity | (a·b) / (‖a‖‖b‖): angle between vectors | 1 same direction, 0 orthogonal, −1 opposite | Ignores magnitude; default for most text models |
| Dot product (inner product) | Σ aᵢbᵢ | Unbounded; larger = more similar | = cosine × lengths; used when magnitude carries signal (e.g. popularity) |
| Hamming distance | Number of differing bits in binary vectors | 0 = identical | XOR + popcount: extremely fast; used with binary codes and LSH |
| Jaccard | Set overlap ∣A∩B∣ / ∣A∪B∣ | 0–1 | For sets and sparse features; MinHash approximates it |
The useful relationships:
- If vectors are normalised to unit length (‖a‖ = ‖b‖ = 1), cosine similarity equals the dot product. L2 distance is then a monotone function of it: ‖a − b‖² = 2 − 2·cos(a, b). All three metrics rank neighbours identically. Most text embedding models output normalised vectors, or you can normalise at ingest. In that case, pick dot product, the cheapest to compute, and move on.
- Unnormalised dot product search is called maximum inner product search (MIPS). It's genuinely different, because a long vector can be "similar" to everything. Recommenders use it deliberately, letting item norm encode popularity. Some indexes support MIPS only via a transformation to L2 search, by adding one extra dimension.
- Use the metric the model was trained with. If a two-tower model was trained to maximise dot products, searching by L2 gives wrong neighbours.
In an infrastructure-style interview, metric choice rarely matters. "Cosine similarity on normalised embeddings" is a complete answer. In an ML design interview, tie it to the training objective.
The nearest-neighbour problem#
k-nearest neighbours (kNN): given a query vector q, return the k stored vectors most similar to q. The query vector is the embedding of the search text, the image, the current item, or the user.
Exact kNN is easy: compute the similarity of q with every vector and keep the top k in a min-heap.
def exact_knn(q, vectors, k):
heap = [] # min-heap of (score, id), size ≤ k
for vid, v in vectors:
s = dot(q, v) # normalised → cosine
if len(heap) < k:
heapq.heappush(heap, (s, vid))
elif s > heap[0][0]:
heapq.heapreplace(heap, (s, vid)) # evict the current worst
return sorted(heap, reverse=True) # O(n·d + n·log k)The cost is O(n · d). For n = 1 million and d = 1,536, that's 1.5 billion multiply-adds, about 3 GFLOP per query. More importantly, it streams 6 GB of vectors from memory:
- SIMD (AVX2 or AVX-512) computes 8–16 lanes per instruction, so compute is rarely the limit on a CPU. Memory bandwidth is, at roughly 20–50 GB/s per socket, which means 120–300 ms per query for 1M × 1,536 float32.
- GPUs have about 1–3 TB/s of HBM bandwidth and thousands of cores. Brute force over 1M vectors takes about 2–6 ms, and batches of queries amortise memory reads further. FAISS's GPU brute-force and IVF kernels ("Billion-scale similarity search with GPUs", Johnson, Douze and Jégou, 2017) made this practical.
Brute force is the right answer more often than people think. Under about 100k vectors, or when a filter already narrows the candidates to a few thousand, exact search costs a millisecond or two and gives perfect recall. Every vector database falls back to it in those cases.
Beyond that, we accept approximate nearest neighbour (ANN) search. Results are probably the nearest, most of the time, at a tiny fraction of the cost.
Recall@k is the standard quality measure: of the true top-k neighbours (computed by brute force), what fraction did the ANN search return? Recall@10 = 0.95 means 9.5 of the 10 true neighbours were found on average. The misses are usually still good results, just ranked 11th to 15th. For most applications 0.95 is ample, because the embedding model's own imperfection dwarfs a 5% ANN miss.
Every ANN index lets you trade among three resources:
You can't maximise all three. HNSW buys high recall and low latency with memory. IVF-PQ buys low memory with some recall. DiskANN buys low RAM with SSD reads.
Index family 1: flat (brute force)#
A flat index stores the raw vectors and scans them all. It has perfect recall, zero build time, and trivial inserts and deletes. It's the baseline every other index is measured against, and the right choice for small collections, for per-tenant collections of a few thousand vectors, and for re-scoring a candidate set. FAISS calls it IndexFlatL2 or IndexFlatIP. pgvector does this when no vector index exists, and Redis calls it FLAT.
Index family 2: IVF (inverted file index)#
IVF partitions the space into clusters:
- Train. Run k-means on a sample of the vectors to find
nlistcentroids. A common heuristic is nlist ≈ √n to 4√n, so about 1,000–4,000 clusters for a million vectors. - Assign. Each vector goes into the posting list of its nearest centroid. This is the same "inverted list" idea as a search engine's term to documents, with a centroid in place of the term.
- Search.
- Compare the query to all
nlistcentroids, which is cheap. - Pick the
nprobeclosest clusters. - Brute-force only the vectors in those lists.
- Compare the query to all
With 1,000 clusters and nprobe = 10, you scan about 1% of the data.
Why not search just the one nearest cluster? Because of the edges. If the query lies near a cluster boundary, its true nearest neighbours may sit in an adjacent cluster. In 2D, a point has a few neighbouring regions. In 768 dimensions, a cluster has an enormous number of neighbouring clusters, and a large share of points lie close to some boundary. nprobe is the recall knob:
- nprobe = 1 might give 40–60% recall;
- nprobe = 10 around 85–95%;
- nprobe = 50 about 98%, at 5x the work.
Probes are independent and parallelise well within a query, but under load the cores are already saturated, so higher nprobe shows up as higher average latency and lower QPS.
Properties:
- Build is fast: k-means on a sample, then one assignment pass.
- Inserts are easy: assign the new vector to its nearest centroid and append.
- Memory overhead is small: centroids plus ids.
- Weaknesses: recall is lower than HNSW at the same latency, especially when the data isn't naturally clustered. Clusters drift as the data distribution changes, so new data piles into a few lists that grow unbalanced and slow, and IVF indexes need periodic re-training.
IVF's real strength is combining with compression. IVF-PQ is the workhorse of billion-scale search.
Index family 3: HNSW (hierarchical navigable small world)#
HNSW ("Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs", Malkov and Yashunin, arXiv 2016 / IEEE TPAMI 2018) is the most widely deployed ANN index. It's the default in pgvector, Elasticsearch/OpenSearch (via Lucene), Redis, Weaviate, Qdrant, and among the options in Milvus.
The skip-list intuition.
- Finding an element in a linked list is O(n).
- A skip list adds "express lanes": higher levels containing a random subset of nodes. Search zooms along the top lane until it would overshoot, drops a level, and continues, for O(log n) expected.
HNSW applies that idea to a proximity graph.
The graph. Every vector is a node. When a vector is inserted, the index finds its nearest existing vectors and creates edges to them. An embedding for "Taylor Swift" links to "Ed Sheeran" and "Beyoncé", not because anyone linked them, but because their vectors are close. If two vectors are similar, a short path of edges likely connects them. Following edges that move closer to a query is greedy routing, and on a well-built graph it reaches the query's neighbourhood quickly.
The hierarchy.
- Layer 0 contains all vectors, each with up to 2M neighbours.
- Each vector is also assigned a random maximum layer, drawn from an exponentially decaying distribution: most nodes exist only at layer 0, a few percent also at layer 1, fewer at layer 2, and so on.
- Upper layers are sparse and their edges span long distances. They're the express lanes.
Search.
- Start at the fixed entry point on the top layer.
- Greedily move to whichever neighbour is closest to q. Repeat until no neighbour is closer: a local minimum for this layer.
- Drop to the next layer, starting from that node, and repeat.
- On layer 0, run a wider beam search:
- keep a candidate list of size
ef_search, say 100; - expand the closest unexpanded candidate;
- add its neighbours;
- stop when no candidate can improve the list;
- return the best k.
- keep a candidate list of size
The upper layers zoom into the right region in a few hops. Layer 0 then explores locally. The search visits a few hundred to a few thousand nodes out of millions, and has roughly logarithmic complexity in practice.
The knobs:
| Parameter | What it controls | Typical | Effect of raising |
|---|---|---|---|
M | Max links per node (layer 0 gets 2M) | 16 (8–64) | Better recall, more memory, slower build |
ef_construction | Beam width while inserting | 100–400 | Better graph quality, slower build |
ef_search | Beam width while querying (≥ k) | 40–400 | Higher recall, higher latency, tunable per query |
Strengths: excellent recall at low latency. Recall@10 of 0.95–0.99 at about 1 ms on millions of vectors is routine. Inserts are incremental, with no training step, and ef_search is a per-query knob.
Costs:
- Memory. Neighbour lists add about M × 2 × 4 bytes ≈ 128 bytes per node at layer 0 when M = 16, plus the vectors, which must stay in RAM for good performance. With 768-dim float32 vectors (3 KB), the graph is a modest overhead. With compressed vectors, the graph dominates. The common rule of thumb is that HNSW roughly doubles memory compared with raw vectors once implementation overheads are included. It's heavily dependent on M and the dimension.
- Build time. Each insert runs a search, so a 10M-vector build takes tens of minutes to hours depending on parameters and cores.
- Deletes are awkward. Removing a node breaks paths through it. Most implementations use tombstones (marked deleted, skipped at query time, but still traversed) and repair or rebuild later.
- Random memory access. Each hop is a cache miss into a different part of RAM. That's fine in memory, but disastrous if the graph is paged from disk, hence DiskANN (below).
In an interview, if asked "how does the vector DB find neighbours quickly?", this is the answer:
It builds a multi-layer graph where vectors are nodes linked to their near neighbours. Search starts at a sparse top layer, greedily walks toward the query, and drops to denser layers as it gets closer. It's like a skip list for high-dimensional space, with roughly logarithmic hops and 95%+ recall.
Index family 4: locality-sensitive hashing (LSH)#
Ordinary hash functions avoid collisions. LSH hash functions are designed so that similar items collide. The landmark papers are Indyk and Motwani (STOC 1998) and Charikar's random-hyperplane hash for cosine similarity (STOC 2002).
Random hyperplanes (SimHash) for cosine similarity:
- Draw a random hyperplane through the origin, represented by its normal vector r.
- Each vector gets 1 bit: whether it lies on the positive or negative side (sign(r · v)).
- Use b hyperplanes to get a b-bit hash. Two vectors at angle θ agree on each bit with probability 1 − θ/π. Close vectors share most bits, so they often share the whole hash bucket.
Amplification. One table with b = 16 bits is precise but misses many neighbours, because one unlucky hyperplane separates them. Using L independent tables, each with its own random hyperplanes, gives a candidate set that is the union of the matching buckets across all tables. The probability that a true neighbour is found in at least one table is 1 − (1 − p^b)^L. Tuning b (precision) and L (recall) is the classic AND-OR construction. At query time, hash q in every table, gather the candidates, and compute exact distances on them.
When LSH still fits:
- Index building is trivial (just compute hashes), and streaming inserts are O(L).
- It has theoretical guarantees.
- Hamming space is natural for it: binary codes, and near-duplicate detection with MinHash for Jaccard similarity on shingled documents. Web crawlers still use this to detect near-duplicate pages. See Probabilistic Data Structures for Big Data.
In practice, graph indexes like HNSW achieve better recall per unit of latency and memory on dense embeddings, so LSH has largely been displaced for that use.
Index family 5: tree forests (Annoy)#
Annoy ("Approximate Nearest Neighbors Oh Yeah", built and open-sourced by Spotify) extends the random-hyperplane idea into trees. To build one tree:
- Pick two random points and split the space with the hyperplane equidistant between them.
- Recurse on each side until a leaf holds, say, 100 vectors.
A single tree can wrongly separate true neighbours at an early split, so Annoy builds a forest of 10–100 trees with different random splits, much like a random forest. At query time it descends all trees, using a priority queue to explore near-boundary branches too. It gathers the union of the candidate leaves and computes exact distances.
Annoy's killer feature was memory-mapping.
- The entire index is one static file that is
mmap'd. - Multiple processes share one copy of the index in the OS page cache.
- Indexes can exceed RAM, because the OS pages in what's touched.
- Loading is instant, with no deserialisation.
The downside is that indexes are immutable: to add vectors you rebuild. That fits a music catalogue refreshed in daily batches, but not real-time inserts. Annoy was a common choice before HNSW libraries matured, and still fits static, memory-mapped serving.
Index family 6: graph indexes on SSD (DiskANN and friends)#
HNSW wants everything in RAM. A billion 768-dim float32 vectors is about 3 TB, which is expensive. DiskANN ("DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node", Subramanya et al., NeurIPS 2019, Microsoft Research) keeps three things in different places:
- a compressed (PQ) copy of every vector in RAM, at about 32–64 bytes each;
- the full-precision vectors and the graph on SSD, using a single-layer graph called Vamana built with a pruning rule that guarantees long-range edges, so fewer hops are needed;
- each query navigates using the in-RAM compressed distances, reads a few dozen SSD pages (each holding a node's full vector and neighbour list together), and re-ranks using the full vectors.
The paper reported billion-scale search on a single machine with about 64 GB of RAM at around 95% recall and a few milliseconds of latency. That's a fundamental change in cost per vector. Variants include FreshDiskANN for updates and filtered DiskANN. SSD-resident graph indexes now appear in several managed services and open-source engines (Milvus offers a DiskANN index type). Related ideas, such as SPANN ("SPANN: Highly-efficient Billion-scale Approximate Nearest Neighbor Search", Chen et al., NeurIPS 2021), keep cluster centroids in memory and the posting lists on disk.
Google's ScaNN ("Accelerating Large-Scale Inference with Anisotropic Vector Quantization", Guo et al., ICML 2020) contributed a quantization loss that weights errors along the direction that matters for inner-product ranking, which improves MIPS accuracy at a given code size. It's used inside Google products and offered in AlloyDB and Vertex AI Vector Search.
Compression: quantization#
A graph or cluster structure decides which vectors to compare. Quantization decides how many bytes each comparison reads. At scale, quantization is usually the bigger lever for cost.
Scalar quantization (SQ, int8).
- Map each float32 dimension to an 8-bit integer using per-dimension min/max, or a learned range: 4 bytes become 1, a 4x reduction.
- Distances computed on int8 are slightly noisy. Recall typically drops by a point or two, and is recovered by rescoring the top candidates with full-precision vectors.
- SIMD on int8 is also faster.
- Elasticsearch, OpenSearch, Qdrant, Milvus and pgvector (via
halfvecfor float16, and binary quantization expressions) all offer scalar or half-precision variants.
Binary quantization (BQ).
- Keep only the sign bit of each dimension: 1,536 floats become 1,536 bits = 192 bytes, a 32x reduction.
- Distance becomes Hamming distance: XOR plus popcount, which is blazing fast.
- Crude for some models, but surprisingly effective for high-dimensional embeddings, if followed by rescoring. Use BQ to get the top 200–500 candidates, then exact distances on those.
- Some models are explicitly trained to tolerate binary or Matryoshka truncation.
Product quantization (PQ) ("Product Quantization for Nearest Neighbor Search", Jégou, Douze and Schmid, IEEE TPAMI 2011) is the classic high-ratio scheme. Here's a worked example for d = 768:
- Split each vector into m = 96 sub-vectors of 8 dimensions each.
- Train a codebook per sub-space. Run k-means with 256 centroids on each 8-dim sub-space. Each centroid id fits in 1 byte.
- Encode. Replace each sub-vector with the id of its nearest centroid. A vector becomes 96 bytes instead of 3,072, which is 32x smaller. With m = 48 it's 48 bytes, or 64x.
- Search with asymmetric distance computation (ADC).
- For a query q (kept in full precision), precompute a lookup table of size m × 256: the distance from each query sub-vector to each centroid of that sub-space.
- The approximate distance to any encoded vector is then the sum of m table lookups: 96 additions, no multiplications, all from cache.
- Scanning millions of PQ codes runs at memory speed on tiny data.
The approximation error comes from replacing sub-vectors with centroids. Refinements include:
- OPQ (optimized PQ: learn a rotation first, so information is balanced across sub-spaces);
- additive and residual quantizers;
- ScaNN's anisotropic loss;
- rescoring: keep the full vectors on SSD or in a cheaper tier, and re-rank the top few hundred PQ candidates exactly.
IVF-PQ: the billion-scale workhorse. This combines IVF's pruning with PQ's compression. It encodes the residual (vector minus its centroid) rather than the raw vector, because residuals are smaller and quantize more accurately. Searching nprobe lists of PQ codes, then rescoring, is how FAISS demonstrated billion-scale search on GPUs.
Memory budgets for 100 million 768-dim vectors:
| Representation | Bytes/vector | 100M vectors | Typical recall@10 (with rescoring) |
|---|---|---|---|
| float32 + HNSW (M=16) | ~3,072 + ~200 | ~330 GB RAM | 0.95–0.99 |
| float16 + HNSW | ~1,536 + ~200 | ~175 GB | ≈ float32 |
| int8 SQ + HNSW | ~768 + ~200 | ~97 GB | 0.95–0.98 |
| PQ 96 B (IVF-PQ) | ~96 + ids | ~12 GB | 0.85–0.95 (rescoring helps) |
| Binary 96 B + rescoring from SSD | ~96 | ~10 GB RAM + 300 GB SSD | 0.9–0.97 |
| DiskANN (PQ in RAM, graph + vectors on SSD) | ~64 RAM | ~6 GB RAM + ~400 GB SSD | 0.95+ |
The recall figures are indicative. They depend heavily on the dataset, the model and the parameters, which is exactly why you benchmark. The cost difference is real: about 330 GB of RAM means several large instances, while 12 GB fits on one modest box. That's the difference between a $20k-a-month and a $1k-a-month deployment.
Tuning recall against latency#
There's no closed-form way to know which index or parameters suit your data. Practitioners run a loop:
- Build an evaluation set.
- Sample 1,000–10,000 real queries.
- Compute their exact top-k by brute force: the ground truth.
- Optionally, add relevance labels for end-to-end quality, since the embedding model matters more than ANN error.
- Sweep parameters. For HNSW, sweep
M,ef_constructionandef_search. For IVF, sweepnlistandnprobe. Include quantization on and off, with rescoring depth. - Plot recall@k against p50/p99 latency and QPS at the target concurrency, plus memory and build time.
- Pick the knee of the curve that meets the SLO. A typical target is recall@10 ≥ 0.95 at p99 under 20 ms.
- Re-run on schedule. Data drifts, and new data distributions can degrade an index tuned last quarter.
The community benchmark ann-benchmarks (Aumüller, Bernhardsson and Faithfull, "ANN-Benchmarks: A Benchmarking Tool for Approximate Nearest Neighbor Algorithms", 2018/2020) popularised these recall-against-QPS curves. Its typical shape:
- QPS stays flat as recall rises from 0.5 to 0.9;
- QPS falls steadily to 0.97;
- it drops off a cliff approaching 0.99–1.0.
The last 1–2% of recall is the most expensive, often 2–5x the work.
Useful planning numbers (in-memory HNSW, a single modern node, about 1–10M vectors, d = 768):
- query latency is about 1–5 ms, and under 10 ms is achievable at p99 when well tuned;
- throughput is thousands to tens of thousands of QPS per node;
- recall@10 is 0.95+ at modest ef_search, and 0.99 costs noticeably more;
- build throughput is thousands to tens of thousands of inserts per second per node. A 10M-vector HNSW build can take an hour or more.
- Embedding generation is often the true bottleneck. A GPU encoder handles hundreds to thousands of short texts per second. At about $0.02 per million tokens for small API embedding models (prices change frequently, so check current pricing), embedding 1B tokens costs about $20. The GPU time for self-hosted models at billions of items is a real budget line.
Metadata filtering#
Real queries rarely say only "find the 10 most similar items". They say:
- "the 10 most similar that are in stock";
- "in the user's price range";
- "published this year";
- "that this tenant is allowed to see".
That's filtered vector search, and it's harder than it looks, because ANN indexes are built over all vectors with no notion of the filter. There are three strategies.
Post-filtering. Run ANN for the top N (N much larger than k), then discard the non-matching results.
- It works when the filter is permissive. If 50% of items match, ask for N = 20 to get about 10.
- It fails when the filter is selective. If only 0.1% match, the top 1,000 ANN results may contain one match, or none. Raising N to 10,000 or more costs a lot, and still doesn't guarantee k results.
Pre-filtering. Evaluate the filter first, using a B-tree, a bitmap or an inverted index, to get the set of matching ids. Then search only within that set.
- It works when the filter is very selective. With 2,000 matches, brute-forcing 2,000 vectors takes well under a millisecond and gives perfect recall.
- It fails when the matching set is large (millions) but not everything. Brute force is too slow, and the ANN index can't be restricted to an arbitrary subset efficiently. A graph restricted to "only nodes with category = shoes" may be disconnected, so greedy search gets stuck.
In-filter (filtered traversal). Traverse the ANN index normally, but only count nodes that pass the filter, and keep exploring until k passing results are found.
- Non-matching nodes can still be used as stepping stones, so the graph stays connected.
- Cost rises as the filter tightens, because more nodes must be visited per hit. Engines switch to pre-filter brute force below a selectivity threshold.
- Refinements:
- Qdrant's filterable HNSW adds extra intra-category links for indexed payload fields, so filtered subgraphs stay connected.
- ACORN ("ACORN: Performant and Predicate-Agnostic Search Over Vector Embeddings and Structured Data", Patel et al., SIGMOD 2024) builds a denser graph so that any predicate's subgraph stays navigable.
- Filtered-DiskANN (Gollapudi et al., WWW 2023) builds label-aware graphs.
Which is best depends on the data. The right answer in an interview is: "it depends on filter selectivity, so I'd benchmark with real data". Then show you know the regimes:
- very selective filter → pre-filter and brute force;
- permissive filter → post-filter with oversampling;
- in between → an engine with filtered traversal.
Partitioning by the most common filter sidesteps the problem entirely. If almost every query is scoped to one tenant or one language, give each tenant or language its own namespace, collection or partition (Pinecone namespaces, Milvus partitions, per-tenant indexes in Weaviate and Qdrant). The filter then becomes routing, and each sub-index is complete.
How common systems handle filters:
-
pgvector relies on the Postgres query planner. You write
WHERE category = 'shoes' ORDER BY embedding <=> $1 LIMIT 10, and the planner chooses:- the HNSW or IVFFlat index, which effectively post-filters the candidates it yields;
- or a B-tree on
category, followed by exact distance on the matching rows.
Highly selective filters often (correctly) skip the vector index. Historically, the awkward middle ground could return fewer than k rows, because the index scan produced only
ef_searchcandidates before filtering. pgvector 0.8 added iterative index scans (hnsw.iterative_scan), which keep pulling candidates until enough rows pass the filter. Partial indexes (CREATE INDEX ... WHERE category = 'shoes') and table partitioning help for a few hot filter values. -
Elasticsearch and OpenSearch kNN accept a
filterinside theknnclause that is applied during the HNSW traversal on each Lucene segment. Exploration continues until enough matching candidates (num_candidates) are gathered, so k results are returned if they exist. Restrictive filters cost more traversal, and Lucene falls back to exact search when the filtered set is small. Elasticsearch also natively combines BM25 and kNN in one request. -
Purpose-built engines (Pinecone, Qdrant, Weaviate, Milvus) treat metadata as first-class. They maintain inverted or payload indexes on metadata fields alongside the vector index, intersect the filter with the traversal in a single operation, and expose filter-aware tuning. Pinecone allows up to 40 KB of metadata per vector.
Hybrid search: keywords plus vectors#
Pure vector search is great at meaning and poor at exact tokens: product codes ("SKU-48213"), error strings, names, rare terms and acronyms the model never saw. Pure keyword search (BM25) is the reverse. Hybrid search runs both and merges the results. A query like "red running shoes size 11" benefits from keyword precision on "size 11" and semantic recall on "running shoes".
Fusion methods:
- Reciprocal Rank Fusion (RRF) ("Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods", Cormack, Clarke and Büttcher, SIGIR 2009). Each document's fused score is Σ 1/(k + rankᵢ) over the result lists it appears in, with k = 60 conventionally.
- It uses ranks only, so there's no need to calibrate BM25 scores (unbounded) against cosine scores (between −1 and 1).
- Worked example: document A is rank 1 in vector and rank 10 in keyword, giving 1/61 + 1/70 = 0.0307. Document B is rank 3 in both, giving 2/63 = 0.0317. B edges ahead, which rewards agreement between the lists.
- Elasticsearch, OpenSearch, Weaviate, Qdrant and others support RRF natively.
- Weighted score combination. Normalise each score (min-max per query), then combine as α·vector + (1−α)·keyword. It's tunable, but sensitive to score distributions.
- Learned rerankers. A cross-encoder model reads the query and each candidate together, which is far more accurate than comparing two independent embeddings. It's also far slower, at about 5–50 ms per batch of candidates on a GPU, so it's applied only to the top 20–100 fused candidates. This "retrieve cheaply, rerank expensively" pattern is standard in search and RAG.
- Sparse learned vectors (SPLADE-style) and multi-vector late interaction (ColBERT, Khattab and Zaharia, SIGIR 2020) sit between keyword and dense retrieval. Some engines support them natively.
Inserts, updates, deletes and index maintenance#
Vector indexes are optimised for reads. Writes are where much of the operational complexity lives:
- Inserts.
- HNSW: each insert runs a search to find neighbours, then rewires edges, costing roughly as much as several queries. Under heavy insert load the graph's quality can degrade, because late arrivals connect to a graph shaped by earlier data.
- IVF: inserts are cheap (append to the nearest list), but clusters drift as new data arrives, so recall decays until you re-train the centroids.
- Updates are almost always delete + insert, because a changed embedding means a new position in the space.
- Deletes are soft. A tombstone marks the vector, and queries skip it. Deleted nodes still occupy memory and are still traversed in HNSW, so heavy deletion (above about 10–20%) slows queries and hurts recall until compaction or rebuild.
The hot/cold (segment) pattern is the standard answer, and the same LSM idea as in Storage Engines: B-Trees vs LSM Trees:
How it works:
- The hot segment is small, perhaps 10k–1M recent vectors. It can be a flat list searched by brute force, or a cheaply built small HNSW. New data becomes searchable within seconds.
- Cold segments are large, immutable and highly optimised: a well-built HNSW, or IVF-PQ with trained codebooks.
- Queries search all segments and merge the top-k by score.
- A background job periodically seals the hot segment and builds or merges it into an optimised cold segment, applying tombstones.
Lucene-based engines (Elasticsearch, OpenSearch) do exactly this: each segment has its own HNSW graph, and segment merges rebuild graphs. That's why heavy indexing in Elasticsearch costs CPU, and why force_merge to fewer segments speeds up kNN queries on static data. Milvus has growing and sealed segments, and Qdrant has optimiser thresholds. The pattern generalises: keeping a small "recently deleted" set checked at query time lets you hide deleted items instantly, while slower cleanup of caches and indexes catches up.
Rebuild strategies. Building HNSW over tens of millions of vectors takes hours, so plan for it:
- Blue/green index swap. Build a new index alongside the old one, then switch an alias atomically. This is required for model changes.
- Partitioned indexes. Rebuild one partition or shard at a time.
- Background reindexing that never blocks queries, with capacity reserved for it.
- Batch rather than real-time. If freshness of minutes or hours is acceptable, periodic batch builds give better indexes at a lower cost.
Consistency. Vector search is almost always fine being eventually consistent. A new product appearing in "similar items" 30 seconds after creation is acceptable, and you should say so explicitly in a design. The usual pipeline is: the primary DB commits, then CDC or an outbox event fires (Change Data Capture and the Outbox Pattern), then an embedding worker runs, then the vector upsert happens. Its lag is measured in seconds to minutes, dominated by embedding time. Exceptions where you need read-your-writes, such as a user immediately searching a document they just uploaded, can be handled by querying the hot segment synchronously, or by searching the new item's chunks directly.
Sharding and scaling vectors#
Single nodes go far. With quantization, 100M vectors fit on one large machine. Beyond that, or for QPS and availability, vectors are distributed.
Scale reads with replicas. Every replica holds a full copy of a shard's index. QPS scales linearly with replicas. This is the first lever when the dataset fits on a node but traffic doesn't.
Scale data with shards. There are two broad strategies:
| Strategy | How queries work | Pros | Cons |
|---|---|---|---|
| Random / hash sharding (by id) | Scatter-gather: every query goes to every shard; each returns its local top-k; coordinator merges | Even data and load; simple; recall unaffected | Fan-out cost grows with shard count; tail latency = slowest shard |
| Semantic sharding (by cluster / IVF centroid) | Route query only to shards owning the nearest clusters | Fewer shards per query; better efficiency at huge scale | Hot shards for popular regions; recall loss if routing misses; rebalancing when data drifts |
| Tenant / attribute sharding | Route by tenant id or other filter key | Isolation; natural pre-filter; easy deletion per tenant | Uneven tenant sizes; cross-tenant queries scatter |
Most systems use hash sharding with scatter-gather. Vectors carry no natural key that groups similar items, unlike user_id for a feed. Any shard may hold a query's neighbours, so all shards must be asked:
- each shard returns its top k′, where k′ = k or slightly more;
- the coordinator merges them with a heap.
This is the same pattern as distributed search engines (Elasticsearch and Search Systems), and the same sharding mechanics covered in Partitioning and Sharding.
The catch is tail latency. With 20 shards, the query waits for the slowest. If each shard's p99 is 10 ms, the probability that at least one of 20 exceeds it is 1 − 0.99^20 ≈ 18%. The coordinator's p99 therefore lands well above 10 ms. Mitigations:
- fewer, larger shards;
- hedged requests to replicas;
- per-shard timeouts that return partial results;
- capping fan-out with semantic routing at very large scale.
Sizing example. Take 1 billion vectors at 768 dims:
- Raw float32 is 3 TB, which as HNSW in RAM is about 3.3 TB: roughly 30 nodes with 128 GB of usable RAM each, before replicas. That's expensive.
- With int8 SQ (about 1 KB per vector incl. graph) it's about 1 TB: 8–10 such nodes.
- With IVF-PQ at 64 B codes it's 64 GB, plus SSD for full vectors used in rescoring. That's 1–2 nodes per replica for data, with more for QPS.
- With DiskANN (PQ in RAM, graph on NVMe) it's a handful of nodes.
The choice is a cost against recall and latency decision, and the interviewer wants to see you do this arithmetic.
A distributed engine's internals (Milvus as an example). Milvus 2.x separates storage and compute:
- Proxies take requests.
- Coordinators manage metadata, held in etcd.
- Data nodes consume an insert log (Pulsar or Kafka) and write segments to object storage.
- Index nodes build indexes on sealed segments.
- Query nodes load segments and indexes into memory and serve searches.
It's the same "log + object storage + stateless compute" pattern as modern data systems. Each tier scales independently. The cost is operational complexity: many node types plus etcd, a message queue and object storage.
Object-storage-first vector search is a newer direction. Indexes live in S3-compatible storage and are cached on local SSD and in RAM. Examples include AWS S3 Vectors (announced in 2025), LanceDB on the Lance columnar format, and turbopuffer. It trades higher cold-query latency (tens to hundreds of ms) for very low storage cost, which suits large, infrequently queried corpora and many-tenant RAG.
The tools#
The landscape moves fast. The durable advice is to start with an extension to a database you already run. Extensions handle millions of vectors comfortably, and avoid operating another stateful system. Graduate to a purpose-built engine when scale (often above about 100M vectors), QPS, filtering complexity or multi-tenancy demand it.
Extensions to existing stores (start here):
-
pgvector (PostgreSQL). This adds a
vectortype, distance operators, and two index types:- distance operators:
<->is L2,<=>is cosine distance,<#>is negative inner product; - IVFFlat, which needs data present before building, because it trains lists;
- HNSW, with
m,ef_constructionand query-timehnsw.ef_search.
It also adds
halfvec(float16),bit(binary) andsparsevectypes. The killer advantage is everything else Postgres gives you: ACID transactions, joins, row-level security, backups, replicas, and one query that combines similarity with relational filters ("similar products in stock in the user's region"). It handles millions to tens of millions of vectors well, especially with halfvec or quantization. Beyond that, index build time, memory and vacuum behaviour become the pressure points. See PostgreSQL in Practice. - distance operators:
-
Elasticsearch / OpenSearch kNN. Uses the
dense_vector(Elasticsearch) orknn_vector(OpenSearch) field types, with HNSW per Lucene segment, quantization options, filtered kNN, and native hybrid search combining BM25 and kNN with RRF. It's the obvious choice if you already run it for search. You inherit its operational weight: JVM tuning, segment merges, shard sizing. -
Redis (Redis Query Engine / RediSearch).
FLATandHNSWvector indexes over hashes or JSON, with hybrid filters. It's in-memory, so latency is very low and memory cost is high. It fits real-time recommendations and semantic caching of LLM responses (embedding the prompt, returning a cached answer for near-duplicates). See Redis in Practice. -
Others:
- MongoDB Atlas Vector Search;
- Cassandra/DataStax and ScyllaDB vector search;
- ClickHouse and DuckDB vector functions;
- SQLite extensions;
- AWS S3 Vectors, for cheap, large, rarely queried vector sets close to your data lake.
Purpose-built vector databases (when you need scale or features):
- Pinecone. Fully managed and serverless: no infrastructure, just an API. It has namespaces for tenant isolation, metadata filtering applied during search, and hybrid sparse-dense support. It's the easiest to operate. The trade-offs are cost at high scale, less control, and vendor dependence.
- Milvus (open source, LF AI & Data Foundation; Zilliz offers it managed). Built for billions of vectors, with the widest range of index types (HNSW, IVF variants, DiskANN, GPU indexes, sparse), partitions and multi-tenancy. The price is operational complexity, from its multi-component distributed architecture.
- Weaviate (open source, Go). Strong hybrid search (BM25 + vector with fusion), GraphQL and REST APIs, built-in "vectorizer" modules that call embedding models for you, and multi-tenancy. It's a middle ground between DIY and managed.
- Qdrant (open source, Rust). Notably good filtering: payload indexes plus filter-aware HNSW. Supports quantization (scalar, binary, product), sparse vectors, and an efficient single-binary deployment. Consider it when complex filtered queries are central.
- Chroma. Lightweight and developer-friendly, popular for prototyping RAG and in notebooks and small apps.
- Vespa (open source, originally from Yahoo). A full search and recommendation serving engine with tensor ranking, hybrid retrieval and multi-phase ranking at large scale. It's heavier, and very capable for combined search plus ranking.
- LanceDB / turbopuffer. Object-storage-first, so storage is cheap. Good for huge multi-tenant corpora.
Libraries, not databases:
- FAISS (Meta) is the reference toolkit: flat, IVF, PQ, HNSW, GPU kernels.
- hnswlib is the original HNSW implementation.
- Annoy, ScaNN and DiskANN are also libraries.
None of them gives you persistence, replication, filtering APIs or multi-tenancy. Many databases embed them inside.
Where vector search is used#
1. Retrieval-augmented generation (RAG). LLMs don't know your private, recent data, and they hallucinate when asked. RAG retrieves relevant passages and puts them into the prompt.
The offline (ingest) side:
- Parse documents.
- Chunk them, usually 200–800 tokens with some overlap, ideally on semantic boundaries such as headings and paragraphs.
- Embed each chunk.
- Upsert each chunk with metadata: document id, tenant, ACL, timestamp, source URL.
Design points that matter:
- Chunking quality and the embedding model drive answer quality more than ANN parameters do.
- Hybrid retrieval plus reranking fixes many "the answer was in the docs but not retrieved" failures.
- Access control must be enforced at retrieval, by filtering on the ACL or tenant. Otherwise the LLM may leak documents a user can't see.
- Freshness: use a CDC-driven re-embed pipeline when source documents change, and delete chunks when documents are removed.
- Evaluation: measure retrieval recall and answer faithfulness on a labelled set.
Designing LLM and AI-Powered Systems and Design an LLM Chat Service (ChatGPT) build on this.
2. Recommendations: candidate generation. Large recommenders work in stages, because scoring every item with a heavy model is impossible:
Two-tower embeddings plus ANN produce a few hundred to a few thousand candidates in milliseconds. A heavier ranking model then uses features the embeddings can't capture: recency, context, the predicted probability of a click or watch. YouTube's "Deep Neural Networks for YouTube Recommendations" (Covington, Adams and Sargin, RecSys 2016) is the classic description of the candidate-generation-then-ranking split. See Design a Recommendation System (Twitter For You).
Cold start is the weak spot. New users have no behaviour to embed, and new items have no interactions. Fall back to content-based embeddings (text and image), popularity, or onboarding questions.
3. Semantic search: document search, code search, support search and e-commerce search. Embed the query, find the nearest chunks or products, and usually combine with keyword search and a reranker. See Design Post Search (Facebook Search) for the search-serving architecture it plugs into.
4. Image, video and audio similarity:
- reverse image search;
- "similar videos";
- music fingerprinting and similarity;
- visual product search ("shop the look").
The pattern is the same: embed the media with CLIP or a domain model, then search.
5. Deduplication and near-duplicate detection:
- plagiarism;
- duplicate listings and support tickets;
- re-uploads of copyrighted media;
- web pages.
Embed each item, query with each new item, and flag neighbours above a similarity threshold. That's a range query rather than top-k.
6. Anomaly and fraud detection. Embed transactions or sessions. A new event far from all normal neighbours, or close to known fraud clusters, is suspicious.
7. Semantic caching for LLMs. Embed incoming prompts and return the cached response if a previous prompt is within a tight similarity threshold. This cuts LLM cost for repetitive queries, at the risk of returning a subtly wrong answer, so keep thresholds conservative.
Architecture patterns for wiring it in:
-
The vector DB as a separate index service. This is the default, so use it unless the problem centres on search.
- The app embeds the query.
- The vector service returns ids and scores.
- The app fetches full records from the primary database.
The concerns stay cleanly separated, and the source of truth remains in the OLTP store.
-
Hybrid search. Query a keyword index and a vector index in parallel and fuse the results. Use it for search products where exact tokens matter.
-
Two-stage retrieval. Run ANN for a large candidate set, then an expensive reranker or ranking model. Use it for recommendations and high-quality search and RAG.
Adding hybrid search and multi-stage ranking to a design that doesn't need them invites a rabbit hole. Unless the question is about search or recommendations, pattern 1 is enough.
When to Use It#
Use vector search when similarity, not exact match, is the question:
- Semantic search: natural-language queries over documents, tickets, code or products, where vocabulary mismatch defeats keywords.
- RAG: grounding LLM answers in a private or recent corpus of thousands to billions of chunks.
- Recommendations: candidate generation over item catalogues of 10^5 to 10^9 items using user and item embeddings.
- Media similarity: images, video, audio, and cross-modal search (text to image via CLIP).
- Near-duplicate detection and clustering: listings, tickets, content moderation, plagiarism.
- Anomaly detection, entity resolution and semantic caching.
Choose the type of store by scale and context:
- Under about 100k vectors: brute force in application memory, or any extension, is fine.
- About 100k to tens of millions: use pgvector, Elasticsearch/OpenSearch kNN, Redis or MongoDB Atlas inside the stack you already run.
- About 100M+ vectors, or very high QPS, heavy filtering, or many tenants: use a purpose-built engine (Milvus, Qdrant, Weaviate, Vespa, Pinecone), quantization, and possibly SSD-resident indexes.
- Huge, rarely queried corpora: object-storage-first options (S3 Vectors, LanceDB, turbopuffer).
Pick something else instead when:
- You need exact lookups by id or attribute. Use the primary database or a KV store.
- Exact token or phrase matching is what users expect: SKUs, error codes, legal clauses. Use keyword search, and perhaps hybrid.
- The questions are structured analytics, like counts and aggregations. Use OLAP.
- The data is geographic proximity: use Geospatial Indexing and Proximity Search (geohash, quadtrees, S2 or H3). Two dimensions don't need ANN.
When NOT to Use It#
- As a source of truth. Vector databases are indexes, not transactional stores. Keep authoritative data in Postgres, DynamoDB or similar, and treat the vector store as rebuildable.
- When you have no good embeddings. If no model captures the similarity you care about, the index will efficiently return irrelevant results. Validate retrieval quality first.
- For a tiny corpus. A few thousand items fit in a numpy array or a Postgres table scan. A dedicated vector DB adds ops cost for nothing.
- When strict freshness or transactional visibility is required and can't be designed around. Most indexes are eventually consistent by nature.
- When explainability is mandatory. "Why was this returned?" is harder to answer for embeddings than for keyword matches. Regulated contexts may need hybrid or keyword-first retrieval.
How to Implement It#
- Define "similar" for the product: semantic text, visual, or co-purchase. Pick or train an embedding model, then fix the dimension and metric (normalise and use dot product or cosine).
- Build an evaluation set of real queries with expected results. Measure end-to-end retrieval quality before tuning infrastructure.
- Design the ingest pipeline:
- source DB → CDC or events → chunk (for text) → embed in batches on GPU or via API → upsert with metadata (ids, tenant, ACL, timestamps,
model_version). - Make upserts idempotent by stable id (Idempotency and Safe Retries).
- source DB → CDC or events → chunk (for text) → embed in batches on GPU or via API → upsert with metadata (ids, tenant, ACL, timestamps,
- Choose the store by scale, as above. Start with pgvector or the engine you already run.
- Choose and tune the index.
- HNSW is the default (M = 16, ef_construction = 200, then tune ef_search against recall@k).
- Add quantization with rescoring when memory dominates.
- Use IVF-PQ or DiskANN at billion scale.
- Plan filtering. Index the filter fields, decide on pre-, post- or in-filtering per query type, and partition or namespace by tenant if most queries are tenant-scoped.
- Add hybrid search and reranking only if evaluation shows misses on exact terms, or quality gaps.
- Plan maintenance:
- a hot segment for freshness;
- compaction for deletes;
- blue/green rebuilds for re-embedding;
- a
model_versionon every vector, so queries never mix models.
- Scale: add replicas for QPS and shards for data, watch scatter-gather tail latency, and monitor recall drift, p99, memory, and ingest lag.
A pgvector example: similarity plus a relational filter in one query, with an HNSW index.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE product_embeddings (
product_id BIGINT PRIMARY KEY REFERENCES products(id),
model_version TEXT NOT NULL, -- never mix models in one search
embedding vector(768) NOT NULL
);
-- HNSW over cosine distance; build after bulk load for speed
CREATE INDEX ON product_embeddings
USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 200);
SET hnsw.ef_search = 100; -- recall/latency knob, per session
SET hnsw.iterative_scan = relaxed_order; -- pgvector 0.8+: keep scanning until filters satisfied
SELECT p.id, p.title, p.price,
1 - (e.embedding <=> $1) AS cosine_similarity
FROM product_embeddings e
JOIN products p ON p.id = e.product_id
WHERE e.model_version = 'text-v3'
AND p.in_stock AND p.region = $2 AND p.price BETWEEN $3 AND $4
ORDER BY e.embedding <=> $1 -- index-assisted ANN ordering
LIMIT 10;| Technology | Fits when |
|---|---|
| pgvector (Postgres) | Already on Postgres; up to tens of millions of vectors; need joins, ACID, relational filters |
| Elasticsearch / OpenSearch kNN | Already running search; need hybrid BM25 + vector with filters |
| Redis vector search | Real-time, in-memory, low-latency recommendations or semantic caching |
| Pinecone | Want zero-ops managed serverless; willing to pay for convenience |
| Milvus / Zilliz | Billions of vectors; many index types incl. GPU and DiskANN; can run a distributed system |
| Qdrant | Complex payload filtering central; efficient Rust engine; quantization options |
| Weaviate | Hybrid search, built-in vectorizer modules, multi-tenancy, open source |
| Vespa | Large-scale search + recommendation with multi-phase ranking in one engine |
| FAISS / hnswlib / ScaNN | Embedded library inside your own service or batch jobs; no DB features needed |
| S3 Vectors / LanceDB / turbopuffer | Very large, cost-sensitive corpora on object storage; tolerant of higher latency |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Flat / brute force | Perfect recall; no build; trivial updates | O(n·d) per query | Under ~100k vectors, or after a selective pre-filter |
| HNSW | Best recall/latency; incremental inserts; per-query ef | Memory-hungry; slow builds; deletes degrade it | Default for in-memory up to hundreds of millions |
| IVF (flat) | Fast build; cheap inserts; low overhead | Lower recall per latency; needs re-training as data drifts | Write-heavy or memory-constrained moderate scale |
| IVF-PQ | 30–60x compression; billion-scale on few nodes / GPUs | Approximation error; training; rescoring needed for high recall | Huge collections where RAM cost dominates |
| DiskANN / SSD graphs | Billion-scale with small RAM; good recall | SSD IOPS bound; more complex updates | Billion-scale, cost-sensitive, latency of a few ms OK |
| LSH | Trivial build; streaming; guarantees; Hamming-friendly | Worse recall/memory than graphs on dense embeddings | Near-duplicate detection, MinHash/SimHash, streaming |
| Annoy (tree forest, mmap) | Shared mmap'd static index; tiny ops | Immutable; rebuild to update | Static catalogues refreshed in batches |
| Extension (pgvector, ES, Redis) | No new system; joins/hybrid; existing ops | Scale and tuning ceilings | Most products, up to tens of millions of vectors |
| Purpose-built DB | Scale, filtering, multi-tenancy, index variety | Another stateful system; cost; maturity varies | 100M+ vectors, high QPS, retrieval-centric products |
Common Pitfalls#
- Treating the vector DB as the source of truth. It's an index. Keep the canonical records elsewhere, and keep the vector store rebuildable from them.
- Mixing embedding models. Querying model-B vectors against a model-A index returns garbage silently. Tag every vector with a
model_version, and migrate with blue/green indexes. - Ignoring filter selectivity. Post-filtering a 0.1% filter returns empty pages. Pre-filtering a 40% filter brute-forces millions. Know your regimes.
- Tuning ANN before checking embedding quality. A 99%-recall index over poor embeddings is still poor. Evaluate end to end.
- Underestimating memory. 6 KB per 1,536-dim vector, plus the graph. Do the arithmetic and consider quantization early.
- Choosing the largest dimension by default. A 3,072-dim model costs 4x the memory and search time of a 768-dim one, often for marginal gains. Matryoshka truncation can help.
- Forgetting deletes and ACLs. Soft-deleted vectors still appear unless they're filtered. RAG systems must enforce document permissions at retrieval time.
- Not planning rebuilds. HNSW over 50M vectors can take hours. Reserve capacity, and use alias swaps.
- Exact-match expectations. Users searching "INV-2024-0042" expect that exact invoice. Add keyword or hybrid search.
- Bad chunking in RAG. Chunks that are too big dilute relevance, and chunks that are too small lose context. Split on structure, and keep the headings as metadata.
Real-World Examples#
- Spotify and Annoy. Spotify built and open-sourced Annoy for music recommendations. It's a memory-mapped, static forest of random-projection trees, suited to a catalogue refreshed in batches.
- Meta and FAISS. Facebook AI Research released FAISS in 2017, a library of flat, IVF, PQ and HNSW indexes with GPU kernels. The paper "Billion-scale similarity search with GPUs" (Johnson, Douze and Jégou) showed billion-vector search on GPUs. FAISS underpins many vector databases and research systems.
- Google and ScaNN. Google published ScaNN (ICML 2020) and offers ScaNN-based indexing in Vertex AI Vector Search and AlloyDB.
- Microsoft and DiskANN. Microsoft Research's DiskANN (NeurIPS 2019) demonstrated billion-scale ANN on a single node with SSDs, and was open-sourced.
- YouTube's two-stage recommender. The RecSys 2016 paper describes embedding-based candidate generation followed by a ranking network. It's the canonical multi-stage recommendation architecture.
Case studies that use this pattern#
- Design a Recommendation System (Twitter For You): embedding-based candidate generation, then ranking.
- Design an LLM Chat Service (ChatGPT): retrieval for grounding, and semantic caching.
- Design Post Search (Facebook Search): the search-serving tier where hybrid keyword and semantic retrieval plugs in.
- Design a Web Search Engine (Google Search): near-duplicate detection and semantic retrieval alongside inverted indexes.
In the Interview#
Here are some useful numbers to state:
- 128–1,536 dimensions are typical, and up to 3,072;
- 4 bytes per dimension as float32, so a 1,536-dim vector is 6 KB;
- 1M of those is about 6 GB raw, and about 12 GB with HNSW;
- queries take 1–10 ms, at thousands to tens of thousands of QPS per node;
- the recall target is 0.95 or more;
- an HNSW build takes about an hour per 10M vectors.
Probing questions and strong answers:
- "Why not just use Elasticsearch keyword search?" Vocabulary mismatch: synonyms, paraphrases and cross-language queries. Vectors capture meaning, while keywords capture exact tokens. Many systems use both.
- "How do you guarantee the 10 most similar in-stock items?" Discuss filter selectivity and the three strategies. Mention filtered HNSW and pre-filtered brute force, and the risk of post-filtering returning fewer than k.
- "What happens when you change the embedding model?" Re-embed everything into a new index, dual-run and evaluate, then swap the alias atomically. Never mix versions. Budget GPU time for the re-embed.
- "How do you scale to a billion vectors?" Quantization (PQ or int8), sharding with scatter-gather, replicas for QPS, DiskANN or IVF-PQ for RAM cost, and tail-latency mitigations.
- "How fresh is the index?" It's eventually consistent: seconds to minutes, dominated by embedding latency. Use a hot segment for immediately searchable items.
Deep Dive: HNSW internals: why greedy routing works and how the graph is builtShow
Lineage. HNSW grew out of navigable small world (NSW) graphs ("Approximate nearest neighbor algorithm based on navigable small world graphs", Malkov et al., Information Systems, 2014). It builds on Kleinberg's work on small-world navigability (STOC 2000): in graphs that mix many short-range links with a few long-range ones, greedy routing using only local information finds short paths, in roughly polylogarithmic hops.
A flat NSW built by inserting points in random order naturally gets long links early, because the first points are far apart, and short links later. Search on it, however, has polylogarithmic complexity with high constants, and gets stuck in local minima on clustered data. HNSW makes the long links explicit, by separating them into layers by distance scale, much as a skip list separates lanes.
Level assignment. Each inserted element draws its top layer as l = ⌊−ln(U) · mL⌋, where U is uniform on (0, 1). With the recommended mL = 1/ln(M), the probability that a node reaches layer ≥ l is M^(−l). For M = 16:
| Layer reached | Share of nodes |
|---|---|
| Layer 0 | all nodes |
| Layer 1 or above | 1/16 |
| Layer 2 or above | 1/256 |
| Layer 3 or above | 1/4,096 |
A 10M-node index therefore has about log₁₆(10⁷) ≈ 6 layers. Each layer is about M times sparser than the one below, so greedy descent does a roughly constant number of hops per layer. That gives the logarithmic overall behaviour.
Insertion. For each new element q with top layer l:
- Greedy-search from the global entry point down to layer l + 1, keeping 1 candidate.
- From layer l down to 0, run a beam search with width
ef_construction, then select up to M neighbours (2M at layer 0) from the candidates. - Add bidirectional edges. If a neighbour now exceeds its maximum degree, prune its list using the same selection rule.
- If l is above the current top layer, q becomes the new entry point.
The neighbour-selection heuristic is the crucial detail. Naively connecting to the M closest candidates makes clusters link only internally, and the graph fragments. HNSW's heuristic adds candidate c (in order of distance to q) only if c is closer to q than to every neighbour already selected. This keeps neighbours in diverse directions, preserves "bridge" edges between clusters, and approximates a relative-neighbourhood graph. In clustered real-world data, it's the difference between 99% and 80% recall. DiskANN's Vamana uses a related rule with a relaxation factor α > 1, which deliberately keeps some longer edges so that paths need fewer hops. That matters when every hop is an SSD read.
Search complexity and ef. At layer 0, the beam of size ef holds the best candidates found so far. The search expands the closest unexpanded candidate and stops when that candidate is farther than the worst in the beam. The number of distance computations is roughly ef × (average degree) × (a small factor). With ef = 100 and degree 32, that's a few thousand distance computations, against 10 million for brute force. That ratio is where the 1,000x speedup comes from. Raising ef has diminishing returns, following the recall curve's flattening.
Memory formula, per node:
- the vector: d × bytes per component;
- layer-0 links: 2M × 4 bytes (ids);
- upper-layer links: an expected M × 4 × 1/(M − 1) bytes, which is negligible;
- per-node bookkeeping.
For d = 768 float32 and M = 16, that's 3,072 + 128 + about 30 bytes ≈ 3.2 KB. With 96-byte PQ codes, the links (128 B) dominate. Graph-plus-quantization designs therefore reduce M, or compress the adjacency lists too.
What degrades HNSW:
- Deletions. Tombstoned nodes remain traversable, so paths stay intact. But results must skip them, and at high delete ratios the search wastes work. Truly removing nodes needs neighbour repair (reconnecting the deleted node's neighbours to each other) or periodic rebuilds.
- Distribution shift. Inserting many points from a new region after the graph was built leaves that region with fewer long-range links. Recall for queries there drops, and a rebuild restores it.
- Hubness. In high dimensions some nodes become neighbours of many others. That helps routing, but concentrates load and can hurt diversity.
- High intrinsic dimension. What matters is the intrinsic dimension of the data manifold, not the nominal d. Data with little structure (random vectors) is hard for every ANN method, while real embeddings with a low intrinsic dimension are easy.
- Concurrency. Parallel builds need per-node locks on adjacency lists. Build-time parallelism scales well, but the final graph differs slightly by insertion order, so results aren't bit-for-bit reproducible across builds.
Deep Dive: Quantization mathematics: PQ distance tables, fast scan and rescoringShow
Distortion and code size. Quantization replaces vector x by a reconstruction x̂ from a codebook. The quality measure is the mean squared error E‖x − x̂‖². With plain k-means using K centroids, error falls slowly as K grows, and storing log₂K bits per vector needs K = 2^64 centroids for 8-byte codes, which is impossible to train or search. Product quantization factorises the space:
- split x into m sub-vectors;
- quantize each with its own small codebook of K* = 256 entries;
- the effective codebook is the Cartesian product, with 256^m reconstructions (for m = 8 that's 2^64), from only m × 256 trained centroids.
That's the idea behind the 2011 paper (Jégou, Douze and Schmid).
Asymmetric distance computation (ADC). For query q, kept unquantized, and database code c = (c₁, ..., c_m):
‖q − x̂‖² = Σⱼ ‖qⱼ − centroidⱼ[cⱼ]‖²
Precompute the table Tⱼ[i] = ‖qⱼ − centroidⱼ[i]‖² once per query. That's m × 256 entries: for m = 96, 24,576 floats, about 96 KB, which fits in L2 cache. Each database vector's distance then costs m lookups and additions. ADC is more accurate than symmetric computation (quantizing q too), because only one side carries quantization error. For inner product, the decomposition works the same way with dot products per sub-space.
Fast scan. On a CPU, m random lookups per vector are bottlenecked by L1/L2 latency. PQ fast scan ("Cache locality is not enough: High-Performance Nearest Neighbor Search with Product Quantization Fast Scan", André, Kermarrec and Le Scouarnec, VLDB 2015) uses 4-bit sub-quantizers (16 centroids each). Each table then fits in a SIMD register, and lookups become in-register shuffle instructions that process many codes per instruction. FAISS's "fast-scan" indexes build on this, and gain several-fold throughput for a little accuracy.
Rescoring math. Suppose PQ alone gives recall@10 = 0.80, because quantization error reorders close candidates. Retrieving the PQ top 200 typically contains nearly all true top-10. The true neighbours are near the top even if they're misordered, which is recall@10 measured within a top-200 set. Exact distances on 200 vectors cost 200 × 768 multiply-adds ≈ 150k FLOPs, which is trivial. If the full vectors live on SSD, 200 random 3 KB reads at about 100 µs each, done in parallel, cost about 0.5–2 ms. This oversample-then-rescore pattern is how int8, binary and PQ indexes reach recall near float32. The rescoring depth (k′ = 2–20× k) is a key tuning knob.
Binary quantization and its limits. The sign bit preserves the vector's orthant. For two unit vectors at angle θ, the expected fraction of agreeing bits under a random rotation is 1 − θ/π, the same quantity as SimHash. With d = 1,536 bits, the Hamming distance is a usable but noisy proxy for angle. Real embedding dimensions aren't random rotations, though, and can have biased means. So:
- centre the data first (subtract the mean), so sign bits are balanced;
- use more than 1 bit per dimension (2–4) if needed;
- always rescore.
Models trained for binary or Matryoshka robustness lose much less.
IVF residuals. In IVF-PQ, encode r = x − centroid(x) rather than x. Residuals have a much smaller norm and more uniform structure across clusters, so a single PQ codebook trained on residuals has lower distortion. At query time the tables depend on q − centroid for each probed list, so they're rebuilt per list. That's a cost of nprobe × m × 256 operations, and it's why nprobe can't grow without bound.
OPQ and learned rotations. PQ assumes the sub-spaces are roughly independent and balanced in variance. If a few dimensions carry most of the variance, some sub-quantizers waste bits. OPQ learns an orthogonal rotation R that minimises PQ distortion (alternating between optimising R and the codebooks). It's applied as a cheap matrix multiply before encoding.
Choosing in practice:
- float16 is nearly free: 2x saving, with negligible loss;
- int8 gives 4x, with a small loss, recovered by rescoring;
- binary gives 32x, with a significant loss and rescoring required, and only for compatible models;
- PQ gives 16–64x, with a tunable loss, and is the standard at billion scale.
Always measure recall after rescoring, at target latency, on your own data.
Deep Dive: Index maintenance, embedding migrations and distributed vector searchShow
Embedding model migration is the vector equivalent of a schema migration, and it's often harder. Every vector must be recomputed. Take 500M chunks at about 500 tokens each, which is 250B tokens. At 2,000 embeddings per second per GPU, that's about 70 GPU-hours, multiplied by the corpus refresh cadence. At API prices it's a material cost. A safe procedure:
The rules:
- Queries must use the same model as the index. The query embedder and the index alias must switch together, so version both.
- Dual-write during the backfill, so items created mid-migration exist in both indexes.
- Keep the old index until rollback is no longer needed. That temporarily doubles storage, so budget for it.
- Budget throughput. Throttle backfill embedding so it doesn't starve real-time ingest.
Distributed top-k correctness. With hash sharding and exact per-shard search, merging each shard's local top-k gives the exact global top-k. Any global top-k item is necessarily in its own shard's top-k. With ANN per shard, global recall is roughly each shard's recall, since misses are local. Asking each shard for k′ above k, such as 2k, raises the chance that borderline items survive. The costs are network transfer and merge work: k′ × shards candidates. For a 100-shard deployment with k = 10 and k′ = 20, that's 2,000 candidates per query, which is cheap. But each query occupies 100 shard-threads, so cluster QPS capacity is per-shard QPS, not a multiple of it. Adding shards adds capacity for data. Adding replicas adds capacity for queries.
Semantic routing at extreme scale. At tens of billions of vectors, fan-out to every shard becomes the bottleneck. Partition by coarse cluster instead, a "global IVF":
- a router compares the query with shard centroids and sends it to the nearest few shards.
The trade-offs mirror IVF:
- boundary queries need several shards (an nprobe across shards);
- popular regions create hot shards, which need extra replicas for those shards or finer splitting;
- distribution drift requires periodically re-clustering and migrating vectors.
Multi-tenancy designs suit SaaS RAG with thousands of customers:
- A shared index with a tenant filter. It's simple and efficient for large tenants. But small tenants become very selective filters (0.01% of the data), which pushes the engine into pre-filter brute force. That's actually fast for small tenants, so hybrid planners handle it well. Isolation is only logical.
- A namespace or collection per tenant. It gives clean isolation, per-tenant deletion (GDPR erasure in one operation, see Data Lifecycle, Tiering and Retention) and per-tenant tuning. The overhead per collection is memory, file handles and index metadata, and many engines struggle beyond tens of thousands of collections. Engines that support "tenant-per-shard" models or lazily loaded tenants address this.
- Tiered. Large tenants get dedicated shards, and the long tail shares a filtered index. Object-storage-first engines make idle tenants nearly free by keeping them cold until queried.
Operational metrics to watch:
- recall@k on a fixed canary query set, run continuously against brute-force ground truth;
- p50 and p99 latency per shard;
- the share of deleted (tombstoned) vectors;
- segment count;
- ingest lag (source commit to searchable);
- embedding service queue depth;
- memory headroom.
Alert on recall drift, not just on latency. An index can be fast and wrong.
Freshness architecture:
- source of truth → Change Data Capture and the Outbox Pattern or outbox → queue → embedding workers (GPU-batched, with retries and idempotent upserts) → vector DB hot segment;
- a periodic compaction or rebuild into optimised segments.
End-to-end lag is typically seconds to a minute. State that as eventual consistency in the design. For deletes, especially access-control revocations, use a fast path: apply the tombstone immediately, and filter by ACL at query time. A revoked document must never be retrieved, even before compaction.
Key Takeaways#
- Embeddings turn items into vectors whose distances reflect learned similarity. A vector belongs to its model, so version it, and re-embed everything when the model changes.
- Metrics: cosine, dot product and L2 rank identically on normalised vectors. Use the metric the model was trained with.
- Exact kNN is O(n·d) and memory-bandwidth-bound. It's fine below about 100k vectors or after a selective filter. Beyond that, ANN trades a little recall for large gains in latency and memory.
- The indexes:
- HNSW is the default: a layered proximity graph with greedy descent and tunable ef. It's memory-hungry.
- IVF offers cluster-and-probe with nprobe as the knob.
- PQ and quantization compress vectors 4–64x, and need rescoring.
- DiskANN moves billion-scale graphs to SSD.
- LSH and Annoy fit hashing and static, memory-mapped cases.
- Filtering depends on selectivity: pre-filter when selective, post-filter when permissive, filtered traversal in between. Namespaces per tenant turn filters into routing.
- Hybrid search (BM25 plus vectors, fused with RRF) and cross-encoder reranking fix exact-term misses and lift quality.
- Writes are the hard part: hot/cold segments, soft deletes plus compaction, blue/green rebuilds, and eventual consistency fed by CDC.
- Scale: replicas add QPS, shards add data. Scatter-gather adds tail latency. Do the memory arithmetic (6 KB per 1,536-dim float32 vector).
- Tools: start with pgvector, Elasticsearch/OpenSearch kNN or Redis. Move to Pinecone, Milvus, Weaviate or Qdrant at about 100M+ vectors or for heavy filtering and multi-tenancy. The vector DB is an index, never the source of truth.
- Uses: RAG, recommendations (two-tower candidate generation, then ranking), semantic, image and audio search, deduplication, anomaly detection, and semantic caching.