All articles

HNSW Explained: What Is the HNSW Algorithm and How the Index Works

HNSW (Hierarchical Navigable Small World) finds approximate nearest neighbours by hopping through a layered proximity graph. This explainer covers how the layers work, what M, efConstruction and efSearch control, how much memory the graph costs and where it breaks.

A blue search path descends through sparse upper graph surfaces to a small neighbourhood on a broad, densely connected base.

HNSW, short for Hierarchical Navigable Small World, stores vectors as nodes in a layered graph. To answer a query, it follows links toward nearby vectors, usually visiting a small fraction of the collection. The trade-off is that it can miss the true nearest neighbours. It is widely used in vector databases and search engines.

The algorithm comes from Malkov and Yashunin's paper, later published in IEEE TPAMI. Its layers explain how it avoids a full scan; three parameters control most of the trade-off between recall, memory and search time.

How does an HNSW search work?

Every vector in an HNSW index is a node, linked to a small set of neighbours chosen for proximity and useful routes through the graph. The simplest way to search is a greedy walk: start at the entry node and move to whichever neighbour is closest to the query. Stop when none of its neighbours is closer. HNSW uses this walk on its upper layers and a broader candidate search at the bottom.

On a flat graph of mostly short links, getting started can take many hops if the entry node is far from the query. HNSW adds layers to shorten that journey. Layer 0 holds every vector. Each higher layer holds a random subset of the layer below, so upper-layer links tend to span larger distances. A search starts at the top, follows greedy hops, then drops down at the node it reached and repeats. At layer 0, it keeps several candidates to explore the neighbourhood more thoroughly.

The figure below shows the descent through three layers of a toy graph. The orange path is the search: dashed lines are the drops between layers, solid lines are hops.

A toy graph with three layers (3, 10 and 70 nodes) and one query (the blue cross, drawn on every layer). Layer assignments and links are simplified compared with the paper. Requires JavaScript.

A greedy walk can stop at a node that is closer to the query than all of its neighbours without being the closest node overall. Keeping more candidates at layer 0 helps the search escape these local minima, but does not guarantee the exact result.

What do M, efConstruction and efSearch control?

The hnswlib parameter reference describes the three main settings:

Parameter Set at What it controls Raising it
M Build Links selected for a new node; commonly also the upper-layer degree limit, with 2 * M at layer 0 Usually better recall, more memory, slower builds
efConstruction Build Size of the retained candidate set used to choose a new node's neighbours Usually better graph quality and slower builds; more temporary memory, without raising the link limit
efSearch Query Size of the retained candidate set at layer 0 Usually better recall, higher latency and more distance computations

M and efConstruction affect how the graph is built. Applying new values throughout an existing index requires a rebuild. efSearch can change at query time, where the engine exposes it, so start there when tuning against a recall target. It must be at least the number of neighbours requested, k.

In the figure below, click anywhere on the plane to move the query and switch efSearch between 1, 4 and 16. At 1, the default query lands in a local minimum: the walk stops at a node closer than all of its neighbours, but not the closest overall. At 4, layer 0 keeps a short list of candidates and finds the true nearest neighbour. For this query, a few more distance computations are enough.

The same toy graph. Orange nodes are the ones whose distance to the query was computed. The dashed ring marks the true nearest neighbour when the search misses it. Requires JavaScript; illustrative, not a benchmark.

Each new vector draws a maximum layer from an exponentially decaying distribution. With the usual level multiplier, 1 / ln(M), each layer contains about 1 / M as many nodes as the layer below it, in expectation. The expected number of layers grows logarithmically with the collection size.

How much memory does HNSW need?

For an in-memory HNSW index, budget for both the graph and the vectors. The Faiss index guidelines estimate uncompressed HNSW memory at (4 * d + 8 * M) bytes per vector, where d is the dimensionality of float32 vectors. At 768 dimensions, the vector payload dominates: 3,072 bytes per vector, plus roughly 256 bytes for links at M = 32. Change the inputs below to see how much memory different collection sizes need.

VectorsEstimated memory at d = 768, M = 32
1 million3.3 GB
100 million333 GB
1 billion3.3 TB
Calculated from the Faiss formula, not measured. Real engines add per-node metadata, deleted-node markers and allocator overhead, and many can quantize the stored vectors to cut the payload. Our companion post, The Next Generation of Vector Search Won't Fit in RAM. It Shouldn't Have To., covers a billion-vector version with compressed alternatives.

Where does HNSW struggle?

HNSW is a strong choice when the index fits in memory and you need high recall at low latency. Four costs deserve attention before you commit to it.

  1. Memory residency. Graph hops involve scattered reads. If the working set does not fit in RAM, cache misses can turn those hops into disk accesses, and the access pattern is hard to prefetch.
  2. Build cost. Inserting a node searches the graph to find its neighbours, so every insert pays for a graph search, and the cost grows with efConstruction.
  3. Deletes and updates. Removing a node requires dealing with its graph links. Some implementations mark nodes deleted and reclaim space during a rebuild or compaction; others support replacement or repair. Heavy churn can add traversal and maintenance work. hnswlib, for example, supports marking deletions and replacing deleted entries.
  4. Filters. Restricting traversal to matching nodes can disconnect the walk. Traversing non-matching nodes preserves routes but can mean more work to find enough results. Engines use filter-aware traversal or fall back to exact search; Elasticsearch's documentation describes this trade-off. Test the selectivity of your own filters.

What are the alternatives to HNSW, and what does WarpSearch use?

HNSW uses graph memory to avoid scanning most vectors. Other approaches reduce the index footprint or move more of it to cheaper storage. The latency cost depends on the data, hardware and recall target.

Approach How it narrows the search Where the index lives Main trade-off
HNSW Greedy upper-layer walk, broader search at layer 0 Usually RAM for low-latency traversal Strong high-recall performance; memory grows with vectors plus links
IVF with compressed codes (PQ or RaBitQ) Route the query to nearby clusters and scan their lists Contiguous lists can be stored in RAM or read from SSD or object storage More probes mean more work; data drift can require retraining centroids
DiskANN Graph search designed for SSD reads SSD, with compressed vectors in RAM Still a graph, so graph maintenance remains
SPANN Centroids in memory, posting lists on disk Disk Cluster-style index with a memory-resident routing layer
Exact scan Compare against every vector Anywhere Linear cost; right for small collections

WarpSearch's default approximate index is the second row: an inverted-file (IVF) index with RaBitQ codes, exact rescoring of selected candidates, and no HNSW. This suits our storage model for four reasons.

  1. Routing memory scales with clusters. Centroids tell a query which lists to read, without a resident graph link set for every vector. The full index still grows with the vector count, and queries need memory for scanned lists, candidates and caches. Avoiding full residency matters at a billion vectors, where uncompressed HNSW with 768-dimensional vectors needs terabytes, mostly for the vectors themselves.
  2. Lists are contiguous. IVF lists can be read sequentially, though a list may span several storage requests. That makes them practical to serve from object storage with a local cache. Bytes fetched and requests made become central costs alongside the active memory footprint.
  3. Codes are small. One-bit RaBitQ stores one bit per dimension plus correction factors. The lists a query scans are a fraction of the original vectors' size. Exact rescoring then reads full-precision vectors for the candidates that survive; it cannot recover a neighbour that candidate selection missed.
  4. No graph to maintain. Building trains cluster centroids, assigns vectors to lists and encodes them. There are no neighbour lists to repair after deletes, and small segments can skip the index and use an exact scan.

An HNSW index in RAM can be faster at very high recall. IVF recall depends on how many lists you probe, and data drift can leave those lists unbalanced or the centroids less representative until retraining. RaBitQ's distance estimates have probabilistic error bounds, so recall needs to be measured on your data, with your filters. We chose IVF for a serverless engine where storage should be cheap and idle indexes should cost almost nothing. Those requirements make a memory-resident graph a poor default for us. The forthcoming post Measure Vector Indexes in Bytes, Not Probes goes into how we measure that trade-off.

Before choosing HNSW

The sparse upper layers get a query into the right neighbourhood; layer 0 searches it more thoroughly. That usually avoids comparing against most vectors, without guaranteeing the nearest one. Choose M and efConstruction when building, then tune efSearch against the recall and latency you need.

Budget roughly (4 * d + 8 * M) bytes per vector for float32 HNSW before engine overhead. At the dimensions used here, the vectors account for most of that memory, so compressing them makes the largest difference. Allow for rebuilds, deletes and filters as well as steady-state queries. IVF with compressed codes, WarpSearch's default, keeps routing memory tied to clusters and lets the bulk of the index live on storage, with a latency trade-off to measure on your workload.

Next, our IVF explainer follows a query through centroid routing, list scans and rescoring, and explains how compression changes the memory budget.

Cookie settings

Optional tracking stays off until you choose it. Your choice applies to this browser for 180 days. Read the details.

Essential storage keeps you signed in, protects forms, and remembers this choice. It is always available.