Most vector databases run on a 2016 insight from Yury Malkov and Dmitry Yashunin: instead of pairing a proximity graph with a separate tree or quantizer for coarse routing, separate the graph’s own edges by length scale into nested layers. Hierarchical Navigable Small World (HNSW) assigns each vector a random maximum layer from an exponentially decaying distribution, turning flat polylogarithmic graph routing into logarithmic O(log N) search in arbitrary metric spaces.

Nearly a decade later, HNSW remains the default in-memory index in pgvector, Qdrant, Weaviate, Milvus, Apache Lucene, and Faiss. Its longevity comes from eliminating two failures at once: the hub-degree bloat that crippled flat small-world graphs on low-dimensional data, and the cluster boundaries that trap naive nearest-neighbor graphs at high recall.

  • Logarithmic scaling without auxiliary trees: Sampling each node’s top layer via floor(-ln(unif(0,1)) * mL) with mL = 1/ln(M) bounds expected greedy hops per layer to a dataset-independent constant 1 / (1 - exp(-mL)), yielding O(log N) search and O(N log N) construction on low-dimensional data.
  • Nearly 1,000x fewer distance checks on low-dimensional metrics: On 2M wiki-8 topic histograms under Jensen-Shannon divergence, where flat NSW collapsed, HNSW cuts distance evaluations by almost three orders of magnitude.
  • Faster builds and sub-millisecond queries on 200M SIFT: HNSW (M = 16, efConstruction = 500) indexes 200M 128-d vectors in 5.6 hours (42 minutes at efConstruction = 40) versus 11 to 12 hours for Faiss OPQ/IMI/PQ, delivering higher 1-NN recall in sub-millisecond latency at 64 GB peak RAM versus 23.5 to 30 GB for Faiss.
  • Bounded graph-link overhead: With M between 6 and 48, Mmax = M, and Mmax0 = 2 * M, 4-byte node IDs (up to roughly 4 billion vectors) keep link storage around 60 to 450 bytes per object before counting vector data.
How HNSW separates edge scales across layers
Upper layers (lc = L … 1)
Sparse subsets with long characteristic link radii and Mmax = M.
Greedy zoom-in (ef = 1)
Start from the fixed top enter point, walk greedily to the layer’s local minimum, and hand that node down to lc - 1.
Ground layer (lc = 0)
Every indexed element lives here with doubled degree cap Mmax0 = 2 * M.
Beam search (ef >= K)
Maintain a dynamic list W of the best ef candidates; stop as soon as the closest unvisited candidate beats no element in W.
Edge wiring (all layers)
Executed at insertion time using efConstruction candidates.
RNG diversity heuristic
Keep candidate e only if e is closer to the new node than to any already chosen neighbor, preserving bridges across clusters.

Architecture from Malkov and Yashunin (2016), Sections 3 and 4.

Why flat proximity graphs hit a scaling wall

Proximity graphs approximate the Delaunay graph, where simple greedy routing always finds the exact nearest neighbor. Unfortunately, exact Delaunay construction requires geometric priors and its average degree explodes exponentially with dimension d.

Building a plain k-NN graph by connecting each point to its M nearest neighbors breaks down immediately: greedy traversal scales as a power law with dataset size N, and links stay trapped inside dense pockets, severing paths between disconnected clusters. Hybrid systems patched this with vector-only trees or quantizers just to pick coarse starting points.

Malkov’s earlier Navigable Small World (NSW) graph avoided auxiliary trees by inserting points in random order and wiring bidirectional edges to M nearest neighbors. Early nodes accumulated long-range bridges and became hubs. Yet Section 3 shows why flat NSW still stalls:

  • The zoom-out trap: Starting greedy search at a random low-degree node forces a climb to longer links before zooming in, risking false local minima. Even starting at the highest-degree hub leaves high-dimensional search slower than a hierarchy.
  • Polylogarithmic degree bloat: Distance checks scale roughly as (average hops) * (average degree along the path). In NSW, greedy walks pass through the same hubs whose degrees grow as O(log N), turning O(log N) hops into polylogarithmic O(log^2 N) work. On low-dimensional datasets, tree structures beat NSW by orders of magnitude.
Why earlier proximity graphs break down
Plain k-NN (mL=0, Mmax0=M)

Suffers power-law hop growth with dataset size and loses global connectivity between isolated clusters.

Flat NSW (mL=0, Mmax0=inf)

Requires shuffled insertion, mixes long and short edges in hubs, and scales polylogarithmically as hub degrees grow.

HNSW (mL=1/ln(M))

Caps degree per layer, starts every search at the coarsest scale, and keeps cross-cluster edges via RNG pruning.

Parameter unification from Malkov and Yashunin (2016), Section 4.1.

Scale separation and the neighbor-diversity heuristic

HNSW generalizes William Pugh’s 1D probabilistic skip list by replacing linked lists at each level with proximity graphs over nested point subsets.

During INSERT, each new element q receives an integer top level l = floor(-ln(unif(0, 1)) * mL). Because levels are randomized independently of spatial order, HNSW needs no upfront dataset shuffling and handles streaming ingestion cleanly. An element assigned level l lives in layers 0 through l, and the highest-level node serves as the fixed enter point.

K-NN-SEARCH enters directly in the zoom-in phase at that top node. Across layers L down to 1, SEARCH-LAYER runs with ef = 1 (pure greedy search), passing each layer’s local minimum down to the next finer layer. Because each node on the path belongs to the upper layer with fixed probability p = exp(-mL), expected hops per layer stay bounded by S = 1 / (1 - exp(-mL)), independent of N under an exact Delaunay assumption. Across O(log N) expected layers, total search work scales as O(log N).

At ground layer 0, SEARCH-LAYER expands a dynamic candidate list W of size ef >= K, backed by a visited set v and candidate min-heap C. Rather than halting after a fixed distance budget, it stops as soon as the closest unevaluated candidate in C is farther from the query than the furthest point in W, avoiding queue bloat.

Even with layers, Figure 2 exposes why naive neighbor wiring fails on clustered data: if q sits on the border of Cluster 1, its M nearest points all lie inside Cluster 1, dropping edges to Cluster 2 and trapping queries. SELECT-NEIGHBORS-HEURISTIC (Algorithm 4) prevents this. Iterating candidates closest-first, it accepts e into neighbor set R only if e is closer to q than to every already-selected neighbor in R. Once one nearby Cluster 1 node is linked, nearby peers are shadowed, leaving a slot for node e2 across the gap in Cluster 2. This recovers the Relative Neighborhood Graph (RNG) as a subgraph using distances alone (and collapses to an exact skip list in 1D), with extendCandidates and keepPrunedConnections handling extreme cluster gaps and degree minimums.

Tuning the budget: recall, build time, and RAM

Unifying k-NN, NSW, and HNSW into one framework leaves three practical tuning knobs (Section 4.1):

  1. Level multiplier mL: Setting mL = 1 / ln(M) minimizes inter-layer neighbor overlap while keeping per-layer greedy hops small, matching a skip-list promotion rate p = 1 / M. Moving mL above 0 delivers massive speedups on 10M d = 4 random vectors and clear gains even at d = 1024.
  2. Degree parameters M and Mmax0: M (6 to 48) trades memory for high-recall navigation. Smaller M favors lower recall or low dimensions; larger M helps high recall or high dimensions while scaling link RAM linearly. Setting Mmax0 = M badly hurts high-recall latency; Mmax0 = 2 * M is near optimal across tested recalls before higher caps waste RAM and slow traversal.
  3. Build breadth efConstruction: Choosing efConstruction for roughly 0.95 construction recall maximizes query speed without bloated builds. Insertions synchronize only briefly when updating bidirectional neighbor lists, so building 10M 128-d SIFT vectors (M = 16, efConstruction = 100) takes just 3 minutes across 40 Xeon cores.

Across ann-benchmarks (1M SIFT, 1.2M GloVe, 1M DEEP, 2M CoPhIR, 60k MNIST, 30M d = 4 random) and non-metric NMSLIB spaces (4M sparse TF-IDF, 1M DNA edit distance, 2M wiki-8 and wiki-128 Jensen-Shannon divergence, 1M ImageNet SQFD), prefetch-friendly C-style HNSW outperformed FLANN, Annoy, VP-tree, FALCONN, NAPP, and flat NSW.

Four operating regimes that test the graph

Average recall-vs-QPS curves hide where HNSW dominates and where memory dominates. Compare the four empirical regimes from Sections 4 and 5 below.

Four stress tests from the HNSW paper

Select a regime (or use Left and Right arrow keys) to compare the naive baseline, HNSW's design choice, and the measured result.

100 isolated clusters (10M vectors, d=10, 10-NN)

Neighbor heuristic

When data sits in separated clusters, linking only to nearest neighbors strands queries inside the wrong cluster.

Why naive selection breaks
SELECT-NEIGHBORS-SIMPLE fills all M slots with points inside Cluster 1, severing Delaunay bridges and stalling recall well below 0.9.
Paper's mechanism
SELECT-NEIGHBORS-HEURISTIC (Alg. 4) with extendCandidates prunes redundant in-cluster neighbors and retains cross-cluster RNG bridges.
Measured evidence
Figure 7 shows the baseline collapsing on 100 clusters while the heuristic achieves even faster high-recall search than on unclustered data.
Production impact
Real embeddings form topic and modality islands; always keep the RNG diversity heuristic enabled when building HNSW indexes.

Source: Malkov and Yashunin (2016), Sections 4.1, 5.3, and 5.4.

If you prefer the short version without clicking through each tab:

  • Clustered data: naive closest-neighbor wiring stalls at cluster borders; the RNG heuristic (SELECT-NEIGHBORS-HEURISTIC) retains cross-cluster bridges.
  • Low-dimensional and non-metric spaces: flat NSW suffers polylogarithmic hub bloat; scale separation (mL = 1 / ln(M)) cuts wiki-8 distance checks by nearly three orders of magnitude.
  • 200M SIFT vs. Faiss PQ: HNSW builds faster (42 minutes to 5.6 hours vs. 11 to 12 hours) and achieves higher recall faster, trading 64 GB peak RAM against 23.5 to 30 GB.
  • Ground-layer degree cap: Mmax0 = M hurts high-recall latency; Mmax0 = 2 * M balances 60 to 450 bytes per item of link overhead against search speed.

Caveats and modern context

Three boundaries in the original 2016 paper explain nearly every vector index built since.

First, HNSW is RAM-bound. Storing embeddings plus 60 to 450 bytes of links per vector hits single-host memory walls around tens or hundreds of millions of points, pushing billion-scale deployments toward GPU Faiss IVF-PQ or NVMe SSD graphs like DiskANN.

Second, the 2016 algorithm omitted deletes, updates, and distributed sharding. Deleting hubs silently breaks routing paths, requiring tombstone filtering and background graph repair as in FreshDiskANN, while routing every query through one top enter point bottlenecks naive distributed indexes unless you shard datasets or adopt distributed skip-graph routing.

Third, pure O(log N) scaling relies on bounded Delaunay degree. Because exact Delaunay degree grows exponentially with dimension d, empirical query times on 200M 128-d SIFT vectors bend slightly above a straight logarithm, and selective metadata filters can still disconnect paths unless label awareness is baked into construction like Filtered-DiskANN.

For engineers building today, HNSW remains the strongest default when your corpus and 60 to 450 bytes/vector of link metadata fit in RAM and you need 0.95+ recall in single-digit milliseconds: start with M = 16, Mmax0 = 32, mL = 1/ln(M), and sweep query ef on your real filtered traffic.