Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Vector databases,
and approximate nearest neighbors.
Embeddings turn meaning into geometry — but finding the nearest vectors among millions, fast, is its own hard problem. A vector database is the answer: a specialized index that trades a sliver of accuracy for enormous speed. Here's how those indexes actually work.
The problem: nearest neighbors at scale
An embedding model maps text (or images) to a vector in a high-dimensional space where similar meanings sit close together. Semantic search, RAG, and recommendations all reduce to one operation: given a query vector, find the stored vectors nearest to it. That's a k-nearest-neighbor (kNN) query.
The naive way — brute force — compares the query against every stored vector and sorts by distance. That's exact, but it costs O(N × d) per query: with millions of vectors of hundreds or thousands of dimensions each, a single search touches billions of numbers. Far too slow for interactive use, and it only gets worse as your corpus grows. A vector database exists to make this fast.
You can have exact-but-slow (brute force) or approximate-but-fast. Vector databases choose the second: give up a tiny bit of accuracy (you might miss a true neighbor occasionally) to make queries orders of magnitude faster.
Distance: what "near" means
"Nearest" needs a distance metric. Three are common, and they must match how your embedding model was trained.
| Metric | Measures | Use when |
|---|---|---|
| Cosine similarity | Angle between vectors (direction, ignoring length) | Most text embeddings — meaning is in direction |
| Dot product | Direction and magnitude together | When vector length carries signal; fast on normalized vectors |
| Euclidean (L2) | Straight-line distance in the space | Some image/embedding spaces; geometric closeness |
For most modern text embeddings, vectors are normalized and cosine = dot product, so the choice collapses. The rule: use the metric your embedding model was trained with — mixing metrics quietly wrecks relevance.
Approximate nearest neighbor (ANN)
The key idea that makes vector search fast is approximate nearest neighbor search. Instead of guaranteeing the exact top-k, an ANN index cleverly organizes the vectors so a query only has to examine a small, promising subset rather than everything — returning the true neighbors almost always.
Quality is measured by recall: of the true top-k neighbors, what fraction did the index return? An index at 0.98 recall finds 98% of the real neighbors while examining a tiny fraction of the data. Every ANN index exposes knobs that trade recall against latency (and memory): search harder for higher recall but slower, or search less for speed. This recall–latency–memory triangle is the whole game.
Why exact search doesn't scale — and ANN does
The cost is not subtle. An exact (brute-force) search compares the query against every stored vector, so it's linear in the corpus:
Double your data, double the work — forever. A graph index like HNSW instead walks a proximity graph greedily, touching a small, query-dependent neighborhood that grows only logarithmically:
That is the difference between a linear scan and a sublinear walk — and it's the entire reason vector databases exist.
This isn't hand-waving. The runnable index below builds a real navigable graph and measures it: recall vs. the exact ground truth, and how many vectors each query actually touched. You'll watch recall climb from ~0.36 to ~0.94 as you raise the search effort — and watch the cost climb with it. That's the triangle, in numbers you can change.
The index types
Three families dominate. They organize vectors differently, and trade the triangle differently.
Graph
A multi-layer proximity graph. Search hops greedily toward the query, coarse layer to fine. Top recall & low latency — but high memory.
Clustering
Partition vectors into clusters; a query searches only the few nearest clusters. Lower memory, tunable via how many clusters you probe.
Compression
Product quantization compresses vectors into tiny codes so billions fit in RAM. Slashes memory; costs some recall.
HNSW (Hierarchical Navigable Small World) builds a graph where each vector links to nearby ones across layers; searching greedily walks the graph toward the query, which is remarkably fast and accurate — the default for many stores, at the price of holding the graph in memory. IVF (Inverted File) clusters the space and, per query, only scans the nearest clusters (you tune how many you probe: more = higher recall, slower). Product quantization compresses each vector into a small code, so you can hold vastly more vectors in memory and compare them cheaply — often combined with IVF (IVF-PQ) for billion-scale search. Real systems mix these; the choice depends on your scale, memory budget, and recall target.
Filtering by metadata
Real queries aren't pure similarity — you want "nearest chunks where tenant = X and date > last week." So vectors are stored with metadata, and search is filtered. This is subtler than it looks, because the ANN index navigates by geometry, not by your filter.
Post-filtering (retrieve top-k, then drop non-matches) is simple but can return too few results if the filter is selective — the matches might all be past the top-k. Pre-filtering (restrict the search to matching vectors) gives correct results but is harder to do efficiently inside an ANN index. Good vector databases integrate filtering into the index so it's both correct and fast; how well they do it is a key differentiator.
Naive post-filtering plus a selective filter can silently return far fewer than k results — the true matches were beyond the top-k the index looked at. Prefer engines with real filtered-ANN support for selective filters.
Updates, freshness & consistency
Corpora change: documents are added, updated, deleted. ANN indexes — especially graph-based ones — are optimized for search, not for constant mutation, so handling upserts and deletes efficiently is a real engineering concern. Vectors are typically written to a mutable buffer and periodically merged into the main index; deletes are often soft (marked, later compacted).
This introduces a freshness lag — a just-added vector may not be searchable for a moment — and the usual consistency questions. For search over a slowly-changing knowledge base this is fine; for real-time use you tune the refresh interval. And remember the embedding-consistency rule from RAG: if you change the embedding model, every vector must be re-embedded and the index rebuilt, since vectors from different models aren't comparable.
Scaling & hybrid search
Past one machine, vector databases shard the index across nodes and scatter-gather queries: each shard returns its local top-k, and the results are merged. Replicas add read throughput and availability. Because ANN indexes are memory-hungry (especially HNSW), the memory-vs-cost math often drives the architecture — which is exactly where PQ compression earns its keep.
Most production retrieval isn't pure vector search either. Hybrid search fuses vector similarity with keyword/BM25 to catch exact terms (names, codes) that embeddings miss, and pairs with a reranker for precision. A vector database is one component of a retrieval stack, not the whole thing.
Do you even need one?
Not every project needs a dedicated vector database. At modest scale — up to a few million vectors — a Postgres extension like pgvector keeps your vectors alongside your relational data and metadata in one system you already run, which is simpler and often plenty fast. Libraries like FAISS give you the raw ANN index in-process with no server at all.
Reach for a dedicated vector database when you hit real scale (tens of millions to billions of vectors), need high query throughput, want advanced filtering and hybrid search out of the box, or require horizontal scaling and operational features you'd otherwise build yourself. Start simple; upgrade when the numbers demand it — not because vector databases are fashionable.
Build an ANN index and measure its recall
"Approximate" sounds like a hand-wave until you measure it. This builds a real navigable proximity graph — the HNSW family — over 400 vectors, then runs greedy beam search and compares it to the exact brute-force answer. It reports two numbers that are the recall–latency–memory triangle: recall (did it find the true neighbors?) and distance-calls (how few vectors did it touch?). Raise efSearch and watch recall climb from ~0.36 toward ~0.94 — while the cost climbs too. There is no free lunch, only a dial.
The picture: how an HNSW search descends
efSearch candidates rather than one, which is the knob the runnable demo turns.Worked example: sizing 10 million vectors
Say you have 10 million chunks embedded at 768 dimensions, stored as 4-byte floats. The index settings are illustrative. Work out memory and the work per query.
| Step | Question | Arithmetic | Answer |
|---|---|---|---|
| 1 | Raw vectors | 10M × 768 × 4 bytes | 30.72 GB |
| 2 | Brute force, one query | 10M × 768 multiply-adds | 7.68 billion |
| 3 | HNSW links, M = 16 | 2M = 32 bottom-layer links × 4-byte ids × 10M | 1.28 GB on top of step 1 |
| 4 | HNSW query, if it takes 500 distance calls | 500 × 768 multiply-adds | 384,000: 20,000× less than step 2 |
| 5 | IVF, 4,096 clusters, probe 16 | 16 ÷ 4,096 of 10M, plus 4,096 centroids | ≈ 39,063 + 4,096 = 43,159 vectors |
| 6 | IVF speed-up vs brute force | 10M ÷ 43,159 | ≈ 232× fewer distances |
| 7 | PQ codes, 96 sub-vectors × 1 byte | 96 bytes × 10M | 0.96 GB, 32× smaller than step 1 |
Steps 1 and 3 are the bill people miss: HNSW wants the full vectors and the graph in RAM, about 32 GB here before replicas. Step 7 is why IVF-PQ exists. Each vector becomes 96 one-byte codes, each picking one of 256 centroids for its slice of 8 dimensions, and the whole corpus fits in under a gigabyte. The price is approximate distances, so systems re-rank the top few hundred PQ hits with the full vectors, kept on disk. Step 5 also shows IVF’s knob: probe 32 clusters instead of 16 and you scan twice as many vectors for higher recall.
Cost and trade-offs by index type
N vectors of d dimensions; M graph links per node; nlist IVF clusters, nprobe probed; m bytes per PQ code.
| Case | Time | Space | Why |
|---|---|---|---|
| Brute force (flat) | O(N·d) per query | N·d floats | Exact, no build, trivial to update. Fine to about a million vectors, or on a GPU. Also your ground truth for measuring recall. |
| HNSW | ~O(log N) hops × M·d each | N·d floats + about 2·M ids per node | Best recall per millisecond. Build is O(N log N); memory is the limit; heavy deletes leave tombstones that are still walked. |
| IVF (flat lists) | O(nlist·d + nprobe·(N/nlist)·d) | N·d + nlist·d | Cheap to build and to add to. Recall depends on clusters trained from a sample that still looks like today’s data. |
| IVF-PQ | O(nlist·d + nprobe·(N/nlist)·m) lookups | N·m bytes | Billions of vectors in RAM. Distances are approximate, so add a re-rank pass with exact vectors. |
| Filtered search | Rises as the filter gets more selective | Extra metadata index | Post-filtering wastes work and can return fewer than k; in-index filtering costs engine complexity. |
No index wins all three of recall, latency and memory. HNSW spends memory to buy latency, IVF-PQ spends recall to buy memory, and brute force spends latency to buy exactness. Pick the one whose cost you can afford, then tune its knob against a measured recall target.
Common mistakes
- Skipping normalisation
Cosine and dot product agree only when vectors are unit length. Put a cosine-trained model’s raw vectors into an inner-product index and long vectors win regardless of meaning. Normalise at write time and at query time, the same way both times.
- Never measuring recall
Default parameters are a guess about someone else’s data. Take a few hundred real queries, compute exact top-k with brute force, and measure recall at your chosen
efSearchornprobe. Without that number you cannot tell whether a relevance complaint is the index or the embeddings. - Sizing RAM on the vectors alone
Step 3 above adds 1.28 GB of graph, and replicas multiply everything. An HNSW index that spills out of RAM onto disk does not slow down gradually; latency jumps sharply. Size for vectors plus graph plus replicas plus headroom for the write buffer.
- Training IVF once and forgetting it
Clusters are learned from the data present at build time. When the corpus shifts, say a new product line or language, new vectors pile into a few lists, those lists get long, and probing them slows down while recall drops. Retrain centroids when list sizes skew.
- Retrieving exactly k for a re-ranker
Ask the index for 5 and a re-ranker or filter can only choose among 5. Retrieve a wider candidate set, often a few dozen, then cut to k after re-ranking. ANN recall at 50 is also higher than at 5, because a near-miss still makes the list.
Where this shows up in production and interviews
- RAG retrieval
The retriever in most RAG systems is this index plus a metadata filter for tenant and permissions, fused with BM25 for exact terms, then re-ranked. Its recall caps the answer quality: the LLM cannot cite a chunk that never came back.
- Recommendations and dedup
“More like this”, similar images and near-duplicate detection are the same kNN query with item vectors in place of chunks. Dedup runs it at write time: if the nearest existing vector is within a threshold, the new item is probably a copy.
- Library, extension or service
FAISS is an in-process library of exactly these indexes: flat, IVF, PQ and HNSW. pgvector adds IVFFlat and HNSW index types to Postgres, so a vector query can join your relational rows. Dedicated databases wrap the same index families with sharding, replication, filtering and upserts.
- The interview version
In “design semantic search”, do step 1 and step 3 out loud, pick an index and justify it by memory, say how you measure recall, and explain how deletes, filters and an embedding-model upgrade are handled. A re-embed of 10M chunks is a migration, so plan for two indexes running side by side.
Check yourself
You need 100 million vectors of 1,536 float32 dimensions searchable on machines with 64 GB of RAM. Can you use HNSW over full vectors on one machine?
No. Raw vectors alone are 100M × 1,536 × 4 bytes = 614.4 GB, before the graph. You either shard across about ten or more machines, or compress with PQ (and IVF-PQ) so the codes fit in RAM, re-ranking with full vectors from disk.
Raising IVF nprobe from 8 to 64 improves recall. What does it cost, roughly?
About 8× more vectors scanned per query, because work in the lists is proportional to nprobe·N/nlist. The centroid comparison stays fixed. Recall gains flatten out as nprobe grows, so the last few points of recall are the most expensive ones.
A filter matches 0.1% of documents. You retrieve the top 10 by similarity and then apply the filter. What usually happens?
You almost always get zero results. Only 1 in 1,000 candidates passes, so the chance that any of 10 does is about 1%. Raising k to thousands wastes work. Use an engine with filter-aware search, or, at this selectivity, brute-force the small matching subset directly.
You switch to a better embedding model and embed only new documents with it. Why do search results get worse?
Vectors from two models live in different spaces. Distances between an old-model vector and a new-model query mean nothing. Every stored vector must be re-embedded and the index rebuilt, usually as a parallel index you cut over to.
Quick answers
What is a vector database?
A store for high-dimensional embedding vectors that answers nearest-neighbor queries fast, using approximate-nearest-neighbor indexes. It powers semantic search, RAG, and recommendations over millions or billions of vectors.
Why not brute-force kNN?
Comparing a query to every vector is O(N·d) per query — too slow at millions of high-dimensional vectors. ANN indexes trade a little accuracy for orders-of-magnitude faster search.
HNSW vs IVF vs PQ?
HNSW is a graph index with top recall and low latency but high memory. IVF clusters the space and probes the nearest clusters. PQ compresses vectors to fit billions in RAM. They're often combined (e.g. IVF-PQ).
Dedicated vector DB or pgvector?
For a few million vectors, pgvector alongside Postgres is often enough. Go dedicated at large scale, high throughput, or when you need advanced filtering, hybrid search, and horizontal scaling.
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The RAG HandbookRetrieval-augmented generation end to end — why LLMs need it, chunking, embeddings and vector search, hybrid retrieval, two-stage reranking, grounded generation with citations, and how to evaluate a RAG system so a quietly-drifting index never fools you.Read →
- RAG vs Fine-TuningThe most common wrong turn in AI engineering — reaching for fine-tuning when you needed retrieval, or vice versa. The one distinction that decides it (knowledge vs behavior), a head-to-head table, when to use each, and why the strongest systems combine them: fine-tune for behavior, RAG for knowledge.Read →
- The Embeddings HandbookMeaning as geometry: how text and images become vectors so that similar meaning lands nearby, why cosine similarity measures direction not length, how L2-normalization makes the dot product equal cosine (so vector databases just take dot products), the curse of dimensionality, and how it all powers semantic search and RAG — with worked math and runnable code.Read →
- The Data Engineering for AI HandbookThe pipeline that turns raw documents into usable data for RAG and training — ingest, chunk, deduplicate, quality-filter. How overlapping chunking works, why deduplication restores diversity, and why the usable dataset is a compounding fraction of the raw pile (raw × dedup-rate × quality-rate) — because quality beats quantity for both retrieval and training. With worked yield math and a runnable pipeline.Read →
- RAG vs Long ContextA 1M-token window makes it tempting to skip retrieval entirely — but bigger context doesn’t mean the model reads it evenly, and it isn’t cheap. The "lost in the middle" attention problem, cost-at-scale math, and the retrieve-then-go-long pattern that combines both.Read →
- Embeddings vs Keyword SearchEmbeddings match meaning even with zero shared words; keyword search (BM25) matches exact terms with a precision embeddings can’t guarantee. Why the two fail in genuinely complementary ways, and why hybrid search with fusion is the modern RAG default.Read →