Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 26/ 160
02. RAG

HNSW Indexes

Hierarchical navigable small-world graphs for fast approximate nearest neighbor search.

AdvancedGraph ANN · efSearch3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The index is a network of connections between similar items; to find a match, you hop from item to item, always towards the question.

Think of it like…

Finding a house in an unfamiliar country: first use a map of motorways to get to the right region, then main roads to the right city, then local streets to the exact address. Each step zooms in, so you never check every house.

Where you’ve seen it

A team indexes 20 million 1,024-dimension vectors. With M = 16 and efSearch = 40, queries take 3 ms at 91 percent recall@10. Raising efSearch to 120 costs 8 ms and reaches 98 percent. Raising M to 32 and rebuilding improves recall at the same efSearch but increases index size by about 30 percent and build time by 2×. They choose M = 16, efSearch = 100 as the cheapest setting that meets their 97 percent target.

Words you’ll hear

M
Maximum links per node per layer (layer 0 allows about 2M); higher improves recall and raises memory and build time.
efConstruction
How many candidates are explored when inserting a node; higher builds a better graph but slows indexing.
efSearch
How many candidates are explored per query; must be at least k; higher raises recall and latency.
Recall@k
Fraction of the true k nearest neighbours the index returns.

Visual diagram

Loading interactive diagram

Theory & deep dive

How build and search work

When a vector is inserted, it's assigned a random maximum layer (exponentially fewer nodes reach higher layers). Starting from the top entry point, the algorithm greedily descends to that layer, then at each layer from there down it finds the efConstruction nearest candidates and connects the new node to up to M of them, pruning links with a heuristic that keeps diverse directions. This yields a "navigable small world": any node can be reached from any other in few hops.

A query descends greedily through the upper layers using a single best candidate, then at layer 0 runs a best-first search keeping a priority queue of size efSearch, expanding the closest unvisited node each step until no candidate improves the result. Cost grows roughly logarithmically with the number of vectors, which is why 100 million vectors can still answer in tens of milliseconds, provided the graph and vectors are in memory (random access over disk is slow).

Memory estimate

20M vectors × 1,024 dims × 4 bytes ≈ 82 GB for vectors. With M = 16, layer-0 links ≈ 32 × 4 bytes ≈ 128 bytes per node, about 2.6 GB more, so the graph is small relative to the vectors; M = 64 would add roughly 10 GB.

Key takeaway: Greedy layered graph search: logarithmic hops, memory-bound, tunable by ef.

Tuning, filters and limits

Tune empirically: build one index with reasonable settings (M 16 to 32, efConstruction 100 to 200), then sweep efSearch and plot recall@k against latency using a sample of real queries and exact search as ground truth; pick the smallest efSearch that meets your recall target with headroom for growth. Increase M or efConstruction only if recall plateaus below target. Keep efSearch ≥ k, and for reranking pipelines retrieve more candidates (k = 50 to 100) cheaply and rerank them.

Weak spots: heavily filtered queries (the graph is built over all vectors, so a selective filter leaves disconnected regions and can lower recall; engines mitigate this with filter-aware traversal, extra links or iterative scans), deletes and updates (tombstones accumulate and need compaction or rebuild), build time (single-threaded insertion is slow, so use parallel builds and bulk loading) and memory (the index should be resident in RAM). Quantisation (scalar, product or binary) shrinks vectors and speeds search at some recall cost, and disk-based variants (DiskANN, Vamana) serve datasets larger than RAM.

An efSearch sweep

efSearch 20 → recall 0.86, 2 ms; 50 → 0.94, 4 ms; 100 → 0.975, 7 ms; 200 → 0.99, 13 ms. If the target is 0.97, choose 100, then re-run the sweep after the corpus doubles.

Key takeaway: Sweep efSearch against exact ground truth; watch filters, deletes and RAM.

How it works, step by step

Step 1 of 4
Evaluation

1. Build ground truth

Take 200–1,000 real queries and compute exact nearest neighbours by brute force to measure recall against.

exact top-10 for each query
Key numbers at this step
Sample
real queries

When to use it & trade-offs

What it is

HNSW (Hierarchical Navigable Small World) is the most widely used index for approximate nearest-neighbour search. It builds a layered graph: each vector is a node linked to a few nearby nodes, the sparse top layers act like express lanes that jump across the space, and the dense bottom layer holds every vector. A query enters at the top, greedily moves to whichever neighbour is closer to the query, drops a layer, and repeats, examining only a few hundred nodes out of millions. Three knobs matter: M (links per node), efConstruction (build-time search width) and efSearch (query-time search width).

Why it matters: HNSW is the default in pgvector, Qdrant, Weaviate, OpenSearch, Milvus and others because it delivers high recall at millisecond latency without a training step. But its memory use, build time and recall behaviour under filters surprise teams that treat it as a black box. Understanding the knobs lets you hit a recall target at minimum cost and explain regressions.

When to reach for it

  • Low-latency semantic search over millions of vectors
  • RAG retrieval with a reranker behind it
  • Systems that need incremental inserts

When to avoid or be careful

  • Setting efSearch below k
  • Judging recall without exact ground truth
  • Letting the index spill out of RAM and expecting the same latency

ANN index families

HNSW (graph)
Best for: General low-latency, high-recall search

Strengths: Excellent recall-speed trade-off; incremental inserts.

Watch out: RAM-hungry; slow builds; deletes are awkward.

IVF / IVFPQ (clusters)
Best for: Very large datasets and tight memory

Strengths: Smaller; quantisation shrinks vectors.

Watch out: Needs training; lower recall at the same speed.

Disk-based graphs (DiskANN)
Best for: Billions of vectors beyond RAM

Strengths: SSD-resident; high recall.

Watch out: More complex; higher latency than in-memory.

Interview signals & numbers to know

When this topic comes up

  • “How does HNSW work?”
  • “Recall dropped after we added filters”
  • “Build is slow / index is big”
  • efSearch tuning
  • Approximate vs exact search

Benchmarks & rules of thumb

16 – 32 -
typical M
O(log N) -
approximate search cost growth
≥ k -
minimum efSearch

Common mistakes & follow-ups

Common interview mistakes

  • Tuning efSearch by eye on three queries and shipping 85 percent recall.
  • Raising M to fix recall when the real cause was a selective filter.
  • Deleting millions of rows and never compacting, so searches wade through tombstones.

Likely interviewer follow-ups

  • Walk me through an HNSW search.
  • What do M, efConstruction and efSearch control?
  • Why can filters hurt recall in HNSW?
Interview tip: Describe search as a greedy descent through layers and name the three knobs with one effect each. That compact explanation covers most interview questions.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply HNSW Indexes with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
pgvector
Next topic
Metadata Filtering