Skip to content
derpx06.dev
WritingExplainersNotesAbout
works on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisationworks on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisation

Learning in public.

A student's notebook on system design, distributed systems and databases. Shared as I learn.

ReadWritingExplainersNotesAbout
ElsewhereGitHubLinkedInHugging FaceLeetCode
Say hellomanaskhairnar1511@gmail.com
derpx06
NORMALmain© 2026 Derpx06Pune, Indiatop ↑
Explainers/Retrieval

How does vector search work? (HNSW explained)

HNSW finds nearest vectors fast by walking a layered graph of links, trading a little recall for large speed gains.

Derpx0628 Sept · 7 min read
Contents
The idea in one sentenceHow it worksStep 1: a graph you can walkStep 2: layersStep 3: searchingStep 4: inserting a pointStep 5: the three settingsWhat the paper foundWhat to be careful aboutSources
0% read · 7 min leftBack to top ↑
On this page0%
Contents
The idea in one sentenceHow it worksStep 1: a graph you can walkStep 2: layersStep 3: searchingStep 4: inserting a pointStep 5: the three settingsWhat the paper foundWhat to be careful aboutSources

Many AI tools turn text or images into long lists of numbers called vectors. Similar items get vectors that are close together. To search, you turn the question into a vector and find the nearest stored vectors. Comparing with every stored vector is exact but slow for millions of them. This paper finds the nearest vectors fast, with a small chance of missing one.

Paper

Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs. Yu. A. Malkov and D. A. Yashunin. First posted on arXiv in March 2016, last revised August 2018. Link: arxiv.org/abs/1603.09320.

The idea in one sentence

Link each point to a few nearby points, stack sparser copies of that network on top, and search by walking from the top layer down, always stepping to whichever neighbour is closer to the query.

The top layers have few points, so you cross the space in big steps. The bottom layer has every point, so you finish with small steps.

How it works

First, some terms.

  • Nearest-neighbour search: given a query point, find the K stored points with the smallest distance to it.
  • Approximate: the search may miss a true neighbour now and then. The share of true neighbours it finds is the recall. Recall 0.9 means 9 of every 10 true neighbours are found.
  • Graph: points (called nodes) joined by links. Two joined nodes are neighbours.

Step 1: a graph you can walk

Give every point links to a few points near it. To search, start at any node, look at its neighbours, and move to the one closest to the query. Repeat. Stop when no neighbour is closer than where you stand. This is greedy search.

A graph with a mix of short and long links, where greedy search reaches any target in few steps, is called a navigable small-world graph. The earlier NSW method used one flat graph like this. HNSW adds layers.

Step 2: layers

Each point gets a top layer number, picked at random. Most points get 0, so they appear only in the bottom layer. A few get 1 or more, so they appear in that layer and in every layer below it. Each layer is a graph over the points that reached it. The paper compares this to a skip list, a sorted list with "express lanes".

The paper picks the layer as floor(-ln(u) * mL), where u is a random number between 0 and 1 and mL is a constant. A good choice is mL = 1/ln(M). Then each point goes up one more layer with probability 1/M.

Toy example: how many points reach each layer

Take M = 16 and 1,000,000 points. A point reaches layer 1 or higher with probability 1/16, layer 2 or higher with probability 1/256, and so on.

LayerExpected points
0 (all points)1,000,000
1 or higher62,500
2 or higherabout 3,900
3 or higherabout 244
4 or higherabout 15

So a million points need only about 5 layers. These numbers come from the formula, not from measurements.

Top layer: few points, long links
Middle layers: more points, medium links
Layer 0: every point, short links
Every point in a higher layer is also in all the layers below it.

Step 3: searching

To find the nearest neighbours of a query:

  1. Start at the fixed entry point in the top layer.
  2. Move greedily inside that layer until no neighbour is closer to the query.
  3. Drop down one layer, starting from the node where you stopped.
  4. Repeat until layer 0. In the upper layers the search keeps just the single best node.
  5. In layer 0, keep a list of the ef best nodes found so far and keep exploring from the closest unexplored one. Stop when the closest unexplored node is farther than the worst node in the list. Return the best K.
Toy example: a search on a line

Eight points on a number line, where distance is the difference. Layer 0 holds 2, 9, 15, 21, 30, 38, 47, 55, and each links to its two nearest points. Layer 1 holds only 15 and 47, linked to each other. The query is 40.

Layer 1: 15
Layer 1: 47
Layer 0: 47
Layer 0: 38

Start at the entry point 15 in layer 1. Its distance to 40 is 25

Step 1 of 5
Toy example. The answer matches a full scan: 38 is the closest to 40.

Greedy search can get stuck at a point that is closer than its neighbours but is not the true nearest. That is why layer 0 keeps a list of ef candidates instead of one.

Step 4: inserting a point

A new point uses the same walk to find its place.

1Pick a random top layer l
2Walk down from the entry point to layer l
3In each layer from l to 0, find the efConstruction closest points
4Choose M of them as neighbours
5Link both ways and trim
Inserting one point.

If a neighbour then has more than its maximum number of links, it drops some. Which ones it drops matters.

The paper's neighbour-selection heuristic looks at candidates from nearest to farthest. It keeps a candidate only if it is closer to the new point than to every neighbour already kept. This spreads the links in different directions. Plain "keep the M nearest" can put all links inside one cluster, so a search that starts elsewhere cannot get in.

Toy example: the heuristic on a line

The new point is at 0. The candidates are at -1, 2 and 3, and we want M = 2.

  • -1: nothing is kept yet, so keep it.
  • 2: distance 2 to the new point, distance 3 to -1. It is closer to the new point, so keep it.
  • 3: distance 3 to the new point, distance 1 to 2. It is closer to 2, so skip it.

The result is -1 and 2, one on each side, instead of the two nearest on one side.

Step 5: the three settings

SettingWhat it controlsLarger value
MHow many links each new point makesBetter recall, more memory
efConstructionHow many candidates are examined while insertingBetter graph, slower build; search speed is not affected directly
efHow many candidates are kept while searchingBetter recall, slower search

M is fixed when you build. ef can change on every query. The paper says good values of M are usually between 6 and 48, and that layer 0 gets up to twice as many links as the others (Mmax0 = 2*M).

What the paper found

The paper argues that search cost grows like log(N), where N is the number of points. Cost scales that way for low-dimensional data in its tests. On 128-dimensional SIFT data the cost deviated from a pure logarithm, possibly because of the higher dimension. Building the whole index costs about O(N log N).

Memory is mainly links: about 60 to 450 bytes per point on top of the data, for M between 6 and 48.

The authors compare HNSW with other open-source methods from the same benchmark library (nmslib) and with the Faiss library on 200 million SIFT vectors. Their Table 3 for the Faiss comparison:

MethodBuild timePeak memorySettings
HNSW (1)5.6 hours64 GBM=16, efConstruction=500
HNSW (2)42 minutes64 GBM=16, efConstruction=40
Faiss (1)12 hours30 GBOPQ64, IMI2x14, PQ64
Faiss (2)11 hours23.5 GBOPQ32, IMI2x14, PQ32

The authors report that HNSW reached much higher accuracy and searched much faster than Faiss here. On 10 million SIFT vectors, efConstruction=100 gave a reasonable index in about 3 minutes on a 40-core server. HNSW also beat the original NSW on every tested set, by almost 3 orders of magnitude on one low-dimensional set.

What this shows: for the tested data, HNSW gives a better speed and recall trade-off than the compared methods, at the cost of more memory. What it does not show: that HNSW is best for your data, or on hardware and software versions newer than the paper's.

What to be careful about

  • It needs a lot of memory. Table 3 shows HNSW using 64 GB where the compressed Faiss indexes used 23.5 to 30 GB.
  • The log(N) result is a guarantee only under assumptions. The proof assumes exact Delaunay graphs and a bounded average number of links. The paper says whether this holds in higher dimensions needs more analytical evidence.
  • Distributing it is harder. Every search starts at the top layer, so the plain structure cannot be split across machines the way flat NSW can. The paper suggests workarounds such as splitting the data into parts.
  • Deleting and filtering are not covered. The paper describes only inserting. Check how your library handles them, and measure recall on your own data.
Key takeaways
  • HNSW finds near neighbours by walking a graph, not by comparing against every point.
  • Random layers give long links at the top and short links at the bottom, so the walk takes few steps.
  • The neighbour heuristic spreads links in many directions, which helps on clustered data.
  • ef sets the speed and recall trade-off at query time. M and efConstruction are set when building.

Sources

  • Malkov, Yashunin. Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs. arXiv:1603.09320 (v4, 2018). Algorithms 1 to 5, Section 4, Table 3 and Section 6.
ShareXLinkedInEmail
Written by Derpx06A developer who builds AI search tools and the code around them. I explain what I got wrong first, so you can skip it. Spotted a mistake? Tell me — corrections get credited.
Inference · 6 minSpeculative decoding explained: making AI answer fasterLLM Systems · 7 minWhy do AI chatbots make things up?Distributed Systems · 7 minHow does Raft work? Getting computers to agreeResearch Papers · 5 minMamba explained: an alternative to Transformers
Start here
01Why do AI chatbots make things up?02How does Raft work? Getting computers to agree03Mamba explained: an alternative to Transformers