Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  The Vector Databases Handbook
Handbook~15 min readIntermediate
Deep Dive

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.

01

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.

→ The core trade

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.

02

Distance: what "near" means

"Nearest" needs a distance metric. Three are common, and they must match how your embedding model was trained.

MetricMeasuresUse when
Cosine similarityAngle between vectors (direction, ignoring length)Most text embeddings — meaning is in direction
Dot productDirection and magnitude togetherWhen vector length carries signal; fast on normalized vectors
Euclidean (L2)Straight-line distance in the spaceSome 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.

03

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:

exact scan:  O(N) distance evals / query   →   N = 1,000,000  means  1,000,000 comparisons, every query

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:

HNSW search:  ~O(log N)  →  at 1,000,000 vectors, a few hundred distance evals reach ≥0.95 recall — not a million

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.

04

The index types

Three families dominate. They organize vectors differently, and trade the triangle differently.

HNSW

Graph

A multi-layer proximity graph. Search hops greedily toward the query, coarse layer to fine. Top recall & low latency — but high memory.

IVF

Clustering

Partition vectors into clusters; a query searches only the few nearest clusters. Lower memory, tunable via how many clusters you probe.

PQ

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.

05

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.

→ The filtering gotcha

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.

06

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.

07

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.

08

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.

Smallpgvector / FAISS — up to a few million vectors, alongside existing data. Simplest.
LargeDedicated vector DB — tens of millions+, high QPS, filtering, hybrid, horizontal scale.
AlwaysMatch the metric to your embedding model, and re-index when the model changes.
RUN IT YOURSELF

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.

CPython · WebAssembly
The picture

The picture: how an HNSW search descends

start at the top, hop greedily toward q, drop a layer layer 2: sparselayer 1layer 0: all N entry point query q: nearest is the node above 6 nodes visited, not N
Every vector lives on layer 0; a random, shrinking fraction is also copied into each layer above. Upper layers are sparse, so their links are long jumps. A search enters at the top, hops to whichever neighbour is closer to the query until none is, then drops to the same node one layer down and repeats. Layer 0’s short links finish the job. Real searches keep a beam of the best efSearch candidates rather than one, which is the knob the runnable demo turns.
By the numbers

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.

StepQuestionArithmeticAnswer
1Raw vectors10M × 768 × 4 bytes30.72 GB
2Brute force, one query10M × 768 multiply-adds7.68 billion
3HNSW links, M = 162M = 32 bottom-layer links × 4-byte ids × 10M1.28 GB on top of step 1
4HNSW query, if it takes 500 distance calls500 × 768 multiply-adds384,000: 20,000× less than step 2
5IVF, 4,096 clusters, probe 1616 ÷ 4,096 of 10M, plus 4,096 centroids≈ 39,063 + 4,096 = 43,159 vectors
6IVF speed-up vs brute force10M ÷ 43,159≈ 232× fewer distances
7PQ codes, 96 sub-vectors × 1 byte96 bytes × 10M0.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.

Trade-offs

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.

CaseTimeSpaceWhy
Brute force (flat)O(N·d) per queryN·d floatsExact, 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 eachN·d floats + about 2·M ids per nodeBest 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·dCheap to build and to add to. Recall depends on clusters trained from a sample that still looks like today’s data.
IVF-PQO(nlist·d + nprobe·(N/nlist)·m) lookupsN·m bytesBillions of vectors in RAM. Distances are approximate, so add a re-rank pass with exact vectors.
Filtered searchRises as the filter gets more selectiveExtra metadata indexPost-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.

Watch for

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 efSearch or nprobe. 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.

In the wild

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.

Self-check

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.

Frequently asked

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.

Finished this one? 0 / 209 Handbooks done
NextEmbeddings vs Keyword Search Next on the “Retrieval” ladder · rung 3 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks