# How Does HNSW Work?

> How HNSW builds a layered graph of vectors and searches it fast, with its memory trade-off, explained simply for your AI interview.

**In short:** HNSW finds the nearest stored vectors quickly by linking each vector to its close neighbours in a layered graph. A search starts at a sparse top layer, hops towards the match, and drops to denser layers, and the whole graph must sit in memory.

AI and LLM interview question Q120, Retrieval-augmented generation (RAG). Advanced, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-does-hnsw-work

## Say it in 30 seconds

HNSW stands for Hierarchical Navigable Small World. It is a graph index for vector search. Each stored vector links to a few close neighbours, and the links sit in layers. A search starts on a sparse top layer, takes big hops towards the question, then drops to denser layers to refine the result. It checks a small part of the stored vectors, so it is far quicker than comparing with all of them. The costs are memory, because the graph has to sit in the computer's working memory (RAM), and build time. I would tune its settings against real questions.

## Say it in 2 minutes

Start with the problem. A search index holds millions of chunks (pieces of documents), each stored as a list of numbers. Checking a question against every one is exact but slow. HNSW avoids that by linking each vector to a few close neighbours, so a search only visits a small part of the data.

The links are arranged in layers. Each new vector is drawn into a top layer by chance, and most stay on the bottom layer. The top layer is sparse, with long links that cover the whole map. The bottom layer is dense, with short links. A search starts at the top, hops to the closest point it can reach, then drops a layer and repeats. The top gets it into the right area, and the bottom finds the closest matches.

The costs are real. The vectors and the graph must sit in memory, so RAM is the first limit to plan for. Two settings matter most: m, how many links each vector keeps, and efSearch, how long the candidate list is during a search. Bigger values raise recall, but they cost memory, build time or query time.

In an interview, say how you would tune it. For a bank's support assistant, I would build a test set of real questions with known right chunks, raise efSearch until the right chunk comes back often enough, and check RAM before touching m. I would also say HNSW is approximate, so it can miss a true match.

## What is HNSW, in plain words?

HNSW is a fast way to find the stored vectors closest to a question, without checking every one of them. A vector is a list of numbers that stands for what a piece of text means. Checking millions of them one by one is exact but slow, so HNSW builds a map of links between them ahead of time.

Think of a field dispatcher at a utility company, sending the nearest crew to a fault. She checks the national road map first, then the regional roads, then the street map for the last few turns. HNSW searches the same way: long hops across the map first, short steps at the end.

Here is a real case. A mid-size bank's support assistant holds 2 million chunks (pieces of documents, cut small enough to search) of fee schedules and product terms. When a customer asks about a monthly fee, HNSW finds the handful of chunks closest in meaning, without scoring all 2 million of them.

- **Vector:** A list of numbers that stands for the meaning of a piece of text, an image or a sound.
- **Nearest neighbour:** The stored vector that sits closest to the question's vector.
- **Graph:** Points joined by links. In HNSW each vector is a point, and its links are the edges.
- **Layer:** One level of the stack. Higher layers hold fewer points with longer links.
- **Recall:** The share of the true closest matches that the search actually finds.

Two researchers, Yu. A. Malkov and D. A. Yashunin, posted the method in 2016. The name comes from their paper's own abstract: navigable small world graphs with controllable hierarchy.

## How is the layered graph built?

HNSW stacks several graphs on top of each other. Every vector sits on the bottom layer, and a few also reach the layers above. The paper's abstract describes how the top layer is chosen:

> "The maximum layer in which an element is present is selected randomly with an exponentially decaying probability distribution." (Malkov and Yashunin, arXiv abstract)
>
> "Each node is connected to up to m neighbors that are nearby." (Microsoft Learn, vector search)

So most vectors stay low, and only a few reach the sparse upper layers. When a new vector arrives, the index runs a short search from the top, finds its close neighbours, and links it to up to m of them. The value m is the link count per vector. A second setting, efConstruction, controls how many candidates the build considers before it picks those links.

1. **Draw its top layer:** A random draw decides how high the new vector reaches. Most stay on the bottom layer.
2. **Search down from the top:** Hop towards the new vector from the top layer, then go down a layer and repeat.
3. **Link to close neighbours:** Keep up to m of the closest points found, and link the new vector to them.

*Diagram, How one new vector joins the graph: Each new vector is added in turn. A random draw gives it a top layer, then a short search finds its close neighbours and links them in. The graph grows this way, so new chunks can go in without starting again.*
1. A random draw sets the top layer, so most vectors stay low.
2. The search for neighbours starts at the top and works down.
3. The new vector links to up to m of the close points it found.
4. The graph grows one vector at a time, with no full rebuild.

Worked example: the bank loads its 2 million chunks in batches, as new fee schedules are published (made-up numbers). Each new chunk runs this same short search, so the index grows one vector at a time instead of being rebuilt from scratch.

## How does a search walk the graph?

A search starts at a fixed entry point on the top layer. It hops to the neighbour closest to the question, and keeps hopping while a neighbour is closer. When it stops improving, it drops one layer and repeats with finer links. The paper says that starting from the upper layer, together with scale separation, allows a logarithmic complexity scaling, so search cost grows slowly as the data grows.

The list of candidates the search keeps is set by efSearch. A longer list explores more candidates before the search stops, so the answers improve and each query takes longer.

*Diagram, How one search walks the layers: A search starts on the sparse top layer, takes big hops towards the question, and drops to denser layers to refine. It stops once no candidate can improve the best matches, and returns them.*
1. The search enters at a fixed starting point on the top layer.
2. It hops to the closest neighbour it can reach, then drops down.
3. Shorter, finer links at this layer narrow the search.
4. It stops when no candidate can beat the best matches so far.

Worked example: a customer asks whether a joint account can skip the monthly fee. The top layer gets the search into the fees part of the map in a few hops. The bottom layer then returns the fee-waiver chunks and leaves out the overdraft-charge chunk that only looks similar (made-up example).

## What are the trade-offs?

HNSW is approximate, so it can miss a true nearest match. It trades a little accuracy for a lot of speed. The price is memory: the vectors and the graph have to be ready in RAM, so the search can reach any point quickly.

> "HNSW requires all data points to reside in memory for fast random access, which consumes vector index size quota." (Microsoft Learn, vector search)
>
> "Increasing this parameter may improve search results, at the expense of slower search." (Microsoft Learn, HNSW parameters)

- **Raise m: More links, better recall.** Each vector keeps more links. Recall can rise, but memory and build time go up.
- **Raise efSearch: Longer candidate list.** Each search checks more candidates. Better results, slower each query.

Numbers, made up for this answer: 2 million chunks, each stored as 768 numbers at 4 bytes each (32-bit floats), need about 6 GB for the vectors alone, before any links. So a bank sizes its server RAM first, then picks m.

Amazon's OpenSearch documentation says performance can suffer if graph memory usage goes over the value it sets.

### How would you tune HNSW for a bank's support search?

Start with a test set of real customer questions, each with the chunk that should answer it. Then tune in this order, because each step changes the next one.

1. **Measure recall first:** Count how often the right chunk appears in the top results. Without this number you are guessing.
2. **Raise efSearch:** Try a longer candidate list. Stop when recall is good enough and queries still feel fast.
3. **Check RAM before m:** Work out the memory for the vectors and links. Raise m only if the RAM budget allows it.
4. **Re-test after every change:** Run the same test set again, so the numbers stay comparable.

> **Tip:** If an answer is wrong, check the chunking and the filters before you blame HNSW. The index can only return chunks that were stored and split well.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: a layered graph that hops towards close vectors.
- [ ] Why it is fast: it visits a small part of the data.
- [ ] It is approximate, so it can miss a true match.
- [ ] The layers: a sparse top for big hops, a dense bottom for detail.
- [ ] The costs: RAM for the graph, plus build time, m and efSearch.
- [ ] How you would tune it: measure recall first, then change settings.

**Common traps**

- Trap: "HNSW checks every vector, so it is always exact." Better: It is approximate. It skips most vectors, so a true match can be missed. Measure recall.
- Trap: "A bigger m is always better." Better: More links cost RAM and build time. Tune m against recall and the memory budget.
- Trap: "The graph can sit on disk, so RAM does not matter." Better: The vectors and links must be ready in memory for fast access. Plan RAM first.

## Can you spot the wrong claim?

**Spot the wrong claim:** Which statement about HNSW is false?

A. It is approximate, so it can miss a true nearest match.
B. It builds layers, and a search starts on the sparse top layer.
C. It checks every stored vector on each search, so it is always exact.
D. Its vectors and links need to be ready in memory.

**Answer:** C. HNSW walks a graph instead of scanning everything. That is why it is fast, and why it can miss a true match. The other three statements are correct.

**Quick check:** Chunking and filters look fine. Your support search keeps missing the right chunk. Which change should you try first?

A. Switch to a bigger generation model
B. Raise efSearch, then re-test recall on real questions
C. Lower m to save memory
D. Add duplicate copies of the same policy

**Answer:** B. Once chunking and filters are ruled out, a miss in the search is a search problem, so a longer candidate list is the first try. A bigger model cannot read a chunk the index never returned. Lowering m cuts links and usually lowers recall.

## Can you answer these from memory?

**Flash cards**

- **What does HNSW stand for?** Hierarchical Navigable Small World: a layered graph for approximate nearest-neighbour search.
- **What does the top layer do?** Holds few, far-apart points, so the search makes big hops first.
- **What is m?** The most links each vector keeps to its close neighbours.
- **What is efConstruction?** How many candidate neighbours the build considers before it links a new vector.
- **What is efSearch?** The length of the candidate list during a search. Bigger means better recall, slower queries.
- **What is the main cost of HNSW?** Memory: the vectors and the graph must sit in RAM. Build time also rises.

## Likely follow-up questions

- Q119 What is approximate nearest-neighbour search? https://designervenkat.online/interview/ai/what-is-approximate-nearest-neighbour-search
- Q121 How does IVF indexing work? (full answer coming)
- Q122 What is product quantization? (full answer coming)
- Q117 What is a vector database? https://designervenkat.online/interview/ai/what-is-a-vector-database
- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search
