SysDesignAtlas

Vector Search & ANN Indexes

HNSW, IVF, and product quantization — how approximate nearest neighbour search trades a little recall for a thousand-fold speedup, and the filtering problem nobody mentions.

HLDHard12 min readaivector-searchannhnsw
Confidence

#Why exact search doesn't work

Finding the nearest vectors to a query is trivially correct by brute force: compute the distance to every vector, keep the top k.

The escape is to give up exactness. Approximate nearest neighbour search returns most of the true nearest neighbours — 95–99% — for a 100–1,000× speedup. Since embeddings are themselves approximate representations of meaning, missing the 9th-best of 10 results is usually invisible.

Recall@k is the metric: of the true top-k, how many did we return? Recall 0.95 at k=10 means we found 9.5 of the true 10 on average.

#HNSW

The dominant algorithm, and its name describes it: hierarchical navigable small world. Connect each vector to its nearest neighbours so the whole collection becomes a graph you can walk, then keep stepping toward whichever neighbour is closest to your query.

The "hierarchical" part is the trick. Build several layers — a sparse top layer with long-range links for covering ground quickly, denser layers below for precision — so a search zooms in rather than crawling. It's the same idea as a skip list, in many dimensions.

   HIERARCHICAL NAVIGABLE SMALL WORLD

   Layer 2   ●──────────────●            few nodes, long links
             │              │            (coarse navigation)
   Layer 1   ●────●────●────●────●       more nodes, medium links
             │    │    │    │    │
   Layer 0   ●─●─●─●─●─●─●─●─●─●─●       ALL nodes, short links
                                          (fine navigation)

   SEARCH
     1. enter at the top layer
     2. greedily move to whichever neighbour is closer
        to the query, until no neighbour improves
     3. drop to the next layer down, continue from there
     4. at layer 0, keep a candidate list of size ef
        and return the best k

   Each layer roughly halves the remaining distance,
   giving O(log N) hops instead of O(N) comparisons.

The structure is a skip list generalised to metric space: sparse upper layers for fast coarse movement, a dense bottom layer for precision.

ParameterEffectTypical
MLinks per node. Higher = better recall, more memory16–64
ef_constructionCandidate list size while building. Higher = better graph, slower build100–500
ef_searchCandidate list size at query time. The runtime recall/latency dial50–500

HNSW's weaknesses, which matter in practice: memory is high (the graph is roughly M × 2 × 4 bytes per node on top of the vectors); build time is long; and deletion is awkward. You can't simply cut a node out, because other nodes' search paths run through it. Instead you tombstone it — mark it "deleted, skip in results" while leaving it in the graph — and as tombstones pile up, searches waste hops on dead nodes and recall slowly degrades until you rebuild.

#IVF and product quantization

The other major family, and the one that scales to memory-constrained deployments.

   IVF (inverted file) — partition, then search a few partitions

     Build:  k-means the vectors into nlist clusters (e.g. 4,096)
             store each vector in its cluster's list
     Query:  find the nprobe nearest centroids
             search only those lists exhaustively

     nlist = 4,096, nprobe = 32
       → search 32/4,096 = 0.8% of the data
       → ~128× speedup, some recall loss when the true
         neighbour sits in an unprobed cluster

Product quantization compresses the vectors themselves, and it's what makes billion-scale indexes fit in memory. The idea: chop each vector into short pieces, and for each piece keep only "which of these 256 standard pieces does it most resemble?" — one byte instead of thirty-two. You lose the exact values and keep enough to rank by.

IVF-PQ is the standard combination: partition with IVF, compress with PQ, and optionally re-rank the top candidates with full-precision vectors to recover most of the lost recall.

RaBitQ (Gao & Long, SIGMOD 2024) is the newer quantizer worth knowing. It applies a random rotation to each vector, then keeps about one bit per dimension — the same 32× saving as the PQ example — but with a proven bound on how wrong each distance estimate can be. That bound lets the search decide, candidate by candidate, whether the cheap estimate is good enough or the full vector has to be fetched, which gives PQ-level memory with steadier recall. Extended versions spend a few more bits per dimension for accuracy, and several vector databases adopted it in 2024–25.

#Choosing an index

IndexMemoryBuildQueryRecallBest for
Flat (brute force)1× vectorsNoneSlow1.00<1M vectors, or a re-ranking stage
HNSW1.5–2×SlowVery fast0.95–0.99The default up to ~100M in RAM
IVF-Flat~1×MediumFast0.90–0.98Large, memory available
IVF-PQ0.03–0.1×MediumFast0.85–0.95Billion-scale, memory-constrained
ScaNN~0.2×MediumVery fast0.93–0.98Anisotropic quantization; strong on MIPS (dot-product search, see below)
DiskANNSmall RAM + SSDSlowMedium0.94–0.98Billion-scale on one machine

DiskANN deserves a mention because it changes the cost structure: keep compressed vectors in RAM for navigation and the full graph on SSD, fetching only the nodes actually visited. A billion vectors on one machine with a few hundred gigabytes of SSD — a completely different infrastructure bill from a distributed in-memory index.

Vector indexes on object storage are the newest point on that curve. Amazon S3 Vectors (generally available December 2025, up to 2 billion vectors per index) stores and searches vectors directly in object storage: queries take around 100 ms on frequently used indexes and up to about a second otherwise, at a small fraction of the cost of keeping vectors in RAM. That suits large corpora queried occasionally — archives, long-term agent memory. Hot, latency-critical search still belongs in memory, and a common design tiers between the two.

#The filtering problem

The part that breaks most naive designs. Real queries aren't "find similar documents" — they're "find similar documents that this user can access, in English, from the last 90 days."

   PRE-FILTER — filter first, then search
     apply the predicate, then brute-force the survivors
     ✓ exact, correct
     ✗ if 2% survive, that's still 2M vectors to scan
     ✗ the ANN index is useless — the graph's links run
       through filtered-out nodes too, so you can't walk
       it using only the survivors

   POST-FILTER — search first, then filter
     get top 1,000 by similarity, drop those failing the predicate
     ✓ uses the index normally
     ✗ if the predicate is selective (0.1% match), you may
       get ZERO results back from 1,000 candidates
     ✗ recall is unpredictable and depends on the predicate

   FILTERED SEARCH — evaluate the predicate during traversal
     walk the graph, skip nodes failing the predicate,
     keep walking
     ✓ one pass, good recall
     ✗ the graph can become disconnected under a selective
       filter — you get stranded in a region with no
       passing neighbours

#Distance metrics and one sharp edge

Cosine, dot product, and Euclidean, as in embeddings. For normalised vectors they rank identically.

The edge case: maximum inner product search (MIPS) is not the same problem as nearest neighbour. With unnormalised vectors, the highest dot product may be far away in Euclidean distance — a large-magnitude vector at a wide angle can beat a close one. Graph-based indexes assume the triangle inequality — "if A is near B and B is near C, then A is near C" — because that's what makes walking from neighbour to neighbour lead you toward the answer. Inner product doesn't obey it, so HNSW on unnormalised vectors can walk away from the best result and silently lose recall.

The fixes: normalise and use cosine (usual answer), or use an index built for MIPS (ScaNN). If your recommendation system deliberately encodes popularity in the magnitude — popular items get longer vectors so they score higher — you need the second, because normalising would erase that signal.

#Operations

Building costs real time. HNSW on 100M × 768-dim vectors is hours on a large machine. Plan for it; parallelise across shards; and never make it part of a request path.

Updates are the awkward part. HNSW handles insertion well and deletion badly — tombstones accumulate and recall degrades. The standard pattern is a large immutable base index plus a small in-memory delta index that holds only recent changes. Every query searches both and combines the results, and the delta is merged into a fresh base periodically. Exactly the LSM tree pattern, applied to vectors.

Memory is the binding cost. Compute the full budget — vectors, graph overhead, metadata, and double it for the rebuild window, because the old index keeps serving queries while the new one is built, so both sit in memory at once. That last term is the one people forget until the rebuild runs out of memory and crashes.

#Check yourself

When does brute-force vector search stop working?Show answer
Around a million vectors at low QPS: 100M × 768 dims is ~77 GFLOPs per query — seconds on a core, hundreds of cores at 1,000 QPS.
What does approximate nearest-neighbour search trade?Show answer
A few percent of recall (returning ~95–99% of the true top-k, measured as recall@k) for a 100–1,000× speedup — invisible since embeddings are approximate anyway.
How does HNSW search?Show answer
A layered proximity graph like a skip list: start at the sparse top layer, greedily move toward the query, drop a layer, and keep an ef-sized candidate list at the dense bottom — about O(log N) hops.
Why is ef_search the important HNSW knob?Show answer
It's set per query, unlike M and ef_construction — so you can trade recall for latency per use case and lower it under load as graceful degradation.
How do IVF and product quantization scale to billions?Show answer
IVF clusters vectors and searches only the nprobe nearest lists (e.g. 0.8% of the data); PQ stores each sub-vector as a 1-byte centroid ID — 32× compression with table-lookup distances. Re-rank the top with full vectors.
What do RaBitQ, DiskANN and object-storage indexes change?Show answer
RaBitQ: ~1 bit per dimension with proven error bounds. DiskANN: compressed vectors in RAM and the graph on SSD, a billion vectors on one machine. S3 Vectors: search from object storage at ~100 ms–1 s for a fraction of the cost.
How do you choose a filtering strategy?Show answer
By selectivity: above ~10% post-filter with over-fetch; below ~1% pre-filter and brute-force; in between, filtered traversal. For a dominant filter like tenant ID, partition the index.
Name two operational traps in vector search.Show answer
Inner-product search on unnormalised vectors breaks graph indexes (normalise or use ScaNN), and deletions degrade HNSW — use a base index plus a delta index, and budget double memory for rebuilds.

#What to carry forward

  • Brute force dies around 1M vectors. ANN trades a few percent recall for 100–1,000×.
  • HNSW is the default: ef_search is a per-query recall/latency dial, usable for graceful degradation.
  • IVF-PQ gets 32× compression with lookup-table distances — how billion-scale fits in memory.
  • DiskANN moves the graph to SSD, changing the cost structure entirely.
  • Filtering strategy is decided by selectivity. Partition the index on your dominant filter where you can.
  • MIPS is not NN — normalise, or use an index built for it.
  • Budget memory for the rebuild window, when two indexes are live at once.
00:00
/ 12m