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)withmL = 1/ln(M)bounds expected greedy hops per layer to a dataset-independent constant1 / (1 - exp(-mL)), yieldingO(log N)search andO(N log N)construction on low-dimensional data. - Nearly 1,000x fewer distance checks on low-dimensional metrics: On
2Mwiki-8topic 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
200MSIFT: HNSW (M = 16,efConstruction = 500) indexes200M128-d vectors in 5.6 hours (42 minutes atefConstruction = 40) versus 11 to 12 hours for Faiss OPQ/IMI/PQ, delivering higher1-NNrecall in sub-millisecond latency at 64 GB peak RAM versus 23.5 to 30 GB for Faiss. - Bounded graph-link overhead: With
Mbetween6and48,Mmax = M, andMmax0 = 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.
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 asO(log N), turningO(log N)hops into polylogarithmicO(log^2 N)work. On low-dimensional datasets, tree structures beat NSW by orders of magnitude.
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):
- Level multiplier
mL: SettingmL = 1 / ln(M)minimizes inter-layer neighbor overlap while keeping per-layer greedy hops small, matching a skip-list promotion ratep = 1 / M. MovingmLabove0delivers massive speedups on10Md = 4random vectors and clear gains even atd = 1024. - Degree parameters
MandMmax0:M(6to48) trades memory for high-recall navigation. SmallerMfavors lower recall or low dimensions; largerMhelps high recall or high dimensions while scaling link RAM linearly. SettingMmax0 = Mbadly hurts high-recall latency;Mmax0 = 2 * Mis near optimal across tested recalls before higher caps waste RAM and slow traversal. - Build breadth
efConstruction: ChoosingefConstructionfor roughly0.95construction recall maximizes query speed without bloated builds. Insertions synchronize only briefly when updating bidirectional neighbor lists, so building10M128-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.
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 heuristicWhen 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.
Low-dimensional & non-metric spaces (2M wiki-8 JS-div, 30M d=4)
Layer hierarchyFlat NSW suffered multi-order-of-magnitude slowdowns on low-dimensional datasets that previously forced engineers back to trees.
- Why flat NSW breaks
- Mixing long and short links in one graph forces polylogarithmic hub-degree growth and zoom-out detours into false local minima.
- Paper's mechanism
- Separating link scales with mL = 1/ln(M) and starting at the top layer restricts each layer to bounded degree and constant expected hops.
- Measured evidence
- On 2M wiki-8 topic histograms (Jensen-Shannon divergence), HNSW beats flat NSW by almost 3 orders of magnitude in distance checks.
- Production impact
- Works across L2, cosine, edit distance, and non-metric divergences without vector-only tree or quantization fallbacks.
200M SIFT subset vs. Faiss OPQ/IMI/PQ (1-NN)
RAM vs compressionAgainst billion-scale product quantization on 200M 128-d SIFT vectors, HNSW wins on speed and build time at roughly 2x the RAM.
- Why PQ lags at high recall
- Quantization compresses vectors to 32 or 64 bytes, introducing approximation error and taking 11 to 12 hours to index 200M vectors.
- Paper's mechanism
- Standalone integer-optimized HNSW (M=16) indexes 200M vectors in 5.6 hours (efConstruction=500) or 42 minutes (efConstruction=40).
- Measured evidence
- Table 3 and Fig. 15: HNSW reaches higher 1-NN recall far faster per query, using 64 GB peak RAM vs. 30 GB (PQ64) and 23.5 GB (PQ32).
- Production impact
- Choose HNSW when vectors fit in RAM for high recall and speed; move to IVF-PQ or SSD graphs once memory budget dominates.
Zero-layer cap Mmax0 and per-layer M (5M SIFT, d=128)
Memory budgetMemory scales linearly with Mmax0 + mL * M, yet starving layer 0 wrecks high-recall latency.
- Why Mmax0=M breaks
- Capping ground-layer edges at M creates a rigid k-NN-like bottom graph that requires huge ef backtracking above 0.9 recall.
- Paper's mechanism
- Double the zero-layer allowance to Mmax0 = 2 * M, keeping M between 6 and 48 (60 to 450 bytes of link metadata per vector).
- Measured evidence
- Figure 6 on 5M SIFT confirms Mmax0 = 2 * M sits near optimal query time across 0.4 to 0.94 recall; larger caps hurt speed and RAM.
- Production impact
- Budget roughly 60 to 450 bytes/vector for links on top of raw embeddings before sizing cluster RAM.
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)) cutswiki-8distance 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 = Mhurts high-recall latency;Mmax0 = 2 * Mbalances 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.


