Katkat

Vector Search: HNSW, IVF and Approximate Nearest Neighbours

By the Katkat team · Updated · 10 min read

Quick overview

Learn how HNSW, IVF and product quantization trade recall for latency and memory, how filtering breaks ANN indexes, and how to pick a vector database.

Lesson 17 of 88 · AI Engineering Interview Course

After this lesson you should be able to explain why vector search uses approximate nearest neighbour (ANN) indexes instead of exact search, and how HNSW and IVF each get their speed-up. You should also be able to reason about the recall/latency trade-off, estimate an index's memory footprint with real arithmetic, and say what goes wrong when you combine ANN with metadata filters. Finally, you should be able to justify a choice between a library, a database extension and a dedicated vector database.

Why exact search stops scaling

A retrieval system turns a query into an embedding and looks for the stored vectors closest to it (see Embeddings). The exact approach is brute force: compare the query against every vector. You can write it in a few lines (Top-k Retrieval with Cosine Similarity), and it is perfectly accurate.

The cost grows linearly with the collection. Take 10 million vectors with 768 dimensions stored as float32:

  • Storage: 10,000,000 × 768 × 4 bytes = 30.72 GB.
  • Work per query: 10,000,000 × 768 = 7.68 billion multiply-adds, about 15 GFLOPs.
  • Memory traffic: every query reads all 30.72 GB. At roughly 100 GB/s of memory bandwidth (approximate, server-dependent), that is about 0.3 seconds for one query.

Brute force is memory-bound, so a faster CPU barely helps. For an interactive app serving many queries per second, you need to look at a small fraction of the data. ANN indexes do this by accepting that the true nearest neighbour is occasionally missed.

If your vectors are L2-normalised, cosine similarity equals the dot product, and ranking by dot product, cosine, or Euclidean distance gives the same order. Most systems normalise once at ingest and use the cheapest metric.

Index types at a glance

IndexIdeaNeeds trainingMemory vs raw vectorsStrengthsWeaknesses
Flat (brute force)Compare against everythingNo1×Exact, simple, good for small sets or filtered subsetsLinear cost
HNSWLayered proximity graph, greedy walkNoAbove 1× (graph links added)High recall at low latency, supports incremental insertsHigh RAM, slow build, awkward deletes
IVF (IVF-Flat)Cluster vectors, search only the nearest clustersYes (k-means)About 1×Cheap build, tunable, easy to combine with compressionRecall depends on cluster quality, centroids drift
IVF-PQIVF plus product quantizationYesOften 10–50× smallerFits huge collections in RAMLossy distances, usually needs re-ranking
Disk-based graphGraph kept on SSD, compressed copy in RAMVariesSmall RAM footprintBillion-scale on modest RAMHigher latency, more complex

The "memory vs raw" column describes the shape of the trade-off, not a guarantee. Exact numbers depend on parameters and implementation.

How the approximate indexes work

HNSW

HNSW (Hierarchical Navigable Small World) builds a multi-layer graph. Every vector lives in layer 0, where each node links to nearby vectors. Each node is also assigned a random maximum layer, with the probability dropping off exponentially, so higher layers contain few nodes and act like a motorway network over the dense local roads below.

Search works like this:

  1. Enter at a fixed entry point in the top layer.
  2. Greedily hop to whichever neighbour is closer to the query until no neighbour improves.
  3. Drop down a layer, starting from where you stopped, and repeat.
  4. At layer 0, run a best-first search that keeps a candidate list of size efSearch and returns the best k.

The main parameters are:

  • M: the number of links per node. Higher M gives better recall and a denser graph, at the cost of more memory and slower builds.
  • efConstruction: the candidate list size while inserting. Higher values give a better graph and slower builds.
  • efSearch: the candidate list size at query time. This is the knob you tune online.

Insertion reuses the same search procedure to find neighbours, so there is no training step and you can add vectors continuously. Deletions are harder: removing a node can break paths, so many implementations mark nodes as deleted and rebuild later.

IVF and product quantization

IVF (inverted file index) first runs k-means over the vectors to produce nlist centroids. Each vector is assigned to its nearest centroid's list. At query time you compare the query to all centroids, pick the nprobe closest, and scan only those lists.

Worked example with 10M vectors, nlist = 4,096 and nprobe = 16:

  • Average list size: 10,000,000 / 4,096 ≈ 2,441 vectors.
  • Vectors scanned: 16 × 2,441 ≈ 39,062, which is 0.39% of the data.
  • Plus 4,096 centroid comparisons, so about 43,158 distance computations in total.
  • Versus 10,000,000 for brute force: roughly 232× fewer.

The weakness is the boundary problem. If the query sits near the edge of a cell, its true neighbour may be in a cell you did not probe. Raising nprobe fixes this at linear cost. Because centroids are trained on a snapshot, large shifts in the data distribution can leave lists unbalanced, so you may need to retrain.

Product quantization (PQ) compresses vectors. Split each vector into m sub-vectors, learn a small codebook for each (typically 256 entries, so one byte per sub-vector), and store only the codebook indices. Distances are approximated using lookup tables. See Quantization for the related idea applied to model weights.

Recall versus latency

The quality metric for an ANN index is recall@k: of the true top-k neighbours (found by brute force on a sample), what fraction did the index return? If the exact top 10 contains 10 items and the index returns 9 of them, recall@10 is 0.9.

Every index exposes a dial that moves along the same curve:

KnobRaising it doesCost
HNSW efSearchExplores more candidates, higher recallMore distance computations per query
HNSW M, efConstructionBetter graph qualityMore memory, slower build
IVF nprobeScans more lists, higher recallLatency grows roughly linearly
IVF nlistSmaller lists, faster scans per probeMore centroid comparisons, more training
PQ code sizeMore bytes per vector, less distortionMore memory

Recall gains flatten out. Going from low to decent recall is cheap, while going from 0.98 to 0.99 can cost a lot of extra latency. The right way to choose is to measure: build a ground-truth set with brute force on a representative sample, sweep the knob, and plot recall against p50/p95 latency and throughput on your own data and hardware. Do not copy parameters from a blog post.

Also ask whether recall in the index is your real bottleneck. A downstream reranker or an LLM can often tolerate missing the 7th-best chunk, but not an irrelevant top 3. For end-to-end diagnosis, see Your RAG System Gives Wrong Answers.

Filtering

Real queries rarely ask for "nearest vectors" alone. They ask for nearest vectors where tenant_id = 42 or date > 2024-01-01. This is where ANN indexes get awkward, because graphs and clusters were built on geometry, not on your metadata.

There are three strategies:

  • Post-filtering: run ANN, then drop results that fail the filter. It is simple but can return too few results.
  • Pre-filtering: compute the set of allowed IDs first, then search only within it. This is accurate, but a graph restricted to allowed nodes may become disconnected, and the search can stall.
  • Filtered traversal: the index checks the filter during the search, skipping non-matching nodes in results but still walking through them. This is what good implementations do, but it needs more exploration when the filter is selective.

Worked example of post-filtering: you want 10 results and the filter matches 1% of the data. Each retrieved candidate passes with probability 0.01, so you need about 10 / 0.01 = 1,000 candidates to expect 10 survivors. Asking the index for k = 10 would return about 0.1 matching items on average.

Practical rules:

  • For very selective filters (a few thousand matching rows), skip the ANN index and brute-force the filtered subset. It is exact and fast.
  • For hard isolation, such as per-tenant data, use separate indexes, partitions, or namespaces rather than a filter.
  • Index the metadata fields you filter on, and test recall with the filters on, because recall measured without filters can be misleading.

Keyword matching is another kind of "filter" that vectors handle poorly; see Hybrid Search and Reranking.

Memory footprint

Memory is usually the constraint that decides the index. Using the same 10M × 768 collection:

RepresentationBytes per vectorTotal for 10M vectors
float32 raw768 × 4 = 3,07230.72 GB
int8 scalar quantization768 × 1 = 7687.68 GB (4× smaller)
PQ, m = 96, 8 bits each960.96 GB (32× smaller)

For HNSW, add the graph. With M = 16, layer 0 typically allows up to 2 × M = 32 links per node. At 4 bytes per link, that is 128 bytes per vector, so 10M × 128 = 1.28 GB, plus a small amount for upper layers. Total with float32 vectors is about 32 GB, so at 768 dimensions the graph is a modest overhead. With heavily compressed vectors the graph becomes the dominant cost.

Practical consequences:

  • If the index must be in RAM and does not fit, compress (scalar quantization or PQ), shard across machines, or use a disk-based index.
  • Compression loses precision. A common pattern is to search the compressed index for, say, 100 candidates, then re-rank them using full-precision vectors stored on SSD.
  • Embedding dimension matters directly. Halving dimensions halves storage and distance cost.
  • Leave headroom for replicas, the write path, and metadata. Real deployments need more than the raw vector arithmetic.

Choosing a vector database

Start from your scale, your ops constraints, and what else you already run.

OptionGood fitWatch out for
Library (FAISS, hnswlib)Prototypes, batch jobs, embedded search, full control over index parametersYou build persistence, replication, filtering and updates yourself
Relational DB extension (pgvector)Moderate scale, you already use Postgres, need transactions and joins with metadataLarge-scale throughput and index build times; tune and test
Search engine with vector supportYou need keyword and vector search together, with mature filteringVector features may lag purpose-built systems
Dedicated vector databaseLarge scale, high query rates, managed scaling, rich filteringAnother system to operate or pay for, possible lock-in

Questions that settle most decisions:

  1. How many vectors now, and in a year? Under a few million, almost anything works.
  2. What are the latency and throughput targets, and what recall is acceptable?
  3. How often do vectors change? Frequent updates and deletes favour designs that handle them well.
  4. How selective and complex are the filters? Is there multi-tenancy?
  5. Do you need hybrid search, and what does your team already know how to run?

Do not pick by a published benchmark alone. Load a realistic sample of your data, run your real queries, and compare recall, latency under load, and cost. For the wider pipeline see Retrieval-Augmented Generation, End to End.

How does this come up in interviews?

1. Why not just use brute-force search? Brute force is exact but costs O(N × d) per query and is memory-bandwidth-bound: 10M × 768 float32 vectors is about 31 GB read per query. It is fine for small collections or already-filtered subsets. Beyond that, an ANN index trades a little recall for scanning only a small fraction of the data.

2. Compare HNSW and IVF. HNSW is a layered graph searched greedily. It has no training step, gives strong recall at low latency, and supports incremental inserts, but it uses more RAM and builds slowly. IVF clusters the data and scans only the nearest nprobe lists, so it is cheaper to build, combines well with PQ for compression, and depends on centroid quality. I would choose HNSW when RAM allows and IVF-PQ when memory is the constraint.

3. How do you tune an index for recall and latency? Build a ground-truth set with brute force on a representative sample, then sweep efSearch or nprobe and plot recall@k against p95 latency. Choose the cheapest setting that meets the product's recall target. Re-check after data growth, because the curve shifts.

4. A query filters on a field matching 1% of documents, and results come back empty. Why? Likely post-filtering: ANN returned the top 10 and almost none passed the filter, since you need about 1,000 candidates to expect 10 matches. Fixes are filter-aware traversal, over-fetching candidates, partitioning by the filter field, or brute-forcing the small filtered subset.

5. Estimate the memory for 50M 1,024-dimension vectors. Float32 is 1,024 × 4 = 4,096 bytes per vector, so 50M × 4,096 = 204.8 GB before any graph overhead. Int8 gives about 51.2 GB, and PQ with 128 one-byte codes gives 6.4 GB. I would pick compression plus full-precision re-ranking from disk, or shard across machines, depending on recall needs.

Common mistakes

  • Treating ANN output as exact and never measuring recall against a brute-force baseline.
  • Copying M, efSearch or nprobe values from a tutorial instead of tuning on your own data.
  • Measuring recall without the production filters applied.
  • Using post-filtering with a small k and a selective filter, then wondering why results are sparse.
  • Forgetting the memory overhead of the graph, replicas and metadata when sizing hardware.
  • Mixing metrics: indexing with one distance metric and querying with another, or forgetting to normalise vectors.
  • Changing the embedding model without re-indexing everything; vectors from different models are not comparable.
  • Blaming the vector index for bad answers when the real problem is chunking, embedding quality or missing keyword matching.
  • Choosing a dedicated vector database for a few hundred thousand vectors, or pgvector for a billion, without testing either.