Approximate Nearest Neighbor Search

By Ludovico Bessi, Senior ML Engineer at Google · Updated

Approximate nearest neighbor (ANN) search finds the item embeddings closest to a query vector without comparing against every item, trading a little recall for orders-of-magnitude speedups. The main families are graph indexes (HNSW), partition indexes (IVF) and quantization (PQ, ScaNN); production systems combine them.

The Problem

After a two-tower model turns a request into a query vector, retrieval needs the top-K items with the highest inner product (or cosine similarity) among all item vectors. Exact search compares the query with every item: O(N·d) per query. At 100 million items with 128 dimensions, that is about 13 billion multiply-adds per request — too slow and too expensive at thousands of queries per second on CPUs.

Approximate nearest neighbor (ANN) search accepts missing a few true neighbors in exchange for orders-of-magnitude speedups. For recommendations this is almost always a good trade: the ranker downstream does not care whether the 300th candidate is exactly the 300th-best item.

Measuring ANN Quality

  • Recall@K: fraction of the true top-K (from exact search) that the ANN index returns. Typical targets are 0.9–0.99.
  • Latency (p50 and p99) and throughput (queries per second per machine).
  • Memory per vector and build time.
  • Update cost: how expensive it is to add or delete items.

Every index lives on a trade-off surface between these. Always measure recall against brute force on real queries.

Maximum Inner Product Search

Two-tower models often score with an unnormalized dot product, which is maximum inner product search (MIPS), not nearest neighbor search in Euclidean distance. MIPS is harder because the inner product is not a metric. Common approaches:

  • Normalize embeddings in training so inner product equals cosine similarity.
  • Transform MIPS into nearest neighbor search by appending an extra dimension to each vector so that all items have the same norm.
  • Use libraries with native MIPS support (FAISS inner-product indexes, ScaNN's anisotropic quantization, which was designed for inner products).

Index Families

Partition-based (IVF)

Cluster the item vectors with k-means into nlist cells. At query time, find the nprobe closest centroids and only search items in those cells.

  • nprobe is the main recall/latency knob.
  • Memory-light and easy to shard.
  • Recall drops for queries near cell boundaries; more probes fix that at higher cost.

Graph-based (HNSW)

Build a graph where each item links to its near neighbors, with a hierarchy of sparser layers on top for long jumps. Search greedily walks the graph toward the query, from the sparse top layer down to the dense bottom layer.

  • Very high recall at low latency; the default in most vector databases.
  • Main knobs: M (links per node), ef_construction (build quality), ef_search (query-time recall/latency).
  • Memory-hungry, and deletions are awkward.

Quantization-based (PQ, ScaNN)

Product quantization (PQ) splits each vector into sub-vectors and replaces each with the ID of its nearest centroid in a small codebook, compressing vectors 10–50×. Distances are computed with lookup tables. PQ is usually combined with IVF (IVF-PQ) for billion-scale indexes, followed by re-ranking the shortlist with full-precision vectors.

ScaNN (Google) uses anisotropic vector quantization, which penalizes quantization error in the direction that matters most for inner products, improving recall for MIPS at the same compression.

Tree and hashing methods

Random projection trees (Annoy, from Spotify) and locality-sensitive hashing (LSH) are simple and were widely used, but graph and quantization methods usually dominate them on recall per unit of compute today.

Practical Concerns for Recommendations

Freshness

Items arrive continuously. Options:

  • Rebuild the index periodically (simple; fine for hourly freshness).
  • Incremental inserts into HNSW or IVF (supported by most libraries).
  • A small fresh index for the newest items, searched alongside the main index and merged.

Filtering

Products need constraints: language, country, age-appropriateness, "not already watched". Strategies:

  • Post-filtering: retrieve more than needed, then filter. Simple, but restrictive filters can leave too few results.
  • Pre-filtering / filtered search: apply the filter inside the search (supported natively by several engines).
  • Separate indexes per common partition (per language, for example).

Model version alignment

Every item embedding must come from the same item-tower version as the query tower in use. Rebuild the index for every model version, keep old and new indexes side by side during rollout, and switch atomically.

GPU and exhaustive search

With GPUs, exact brute-force search over tens or hundreds of millions of vectors becomes feasible with batched matrix multiplication. Some companies now prefer exhaustive GPU retrieval because it removes ANN recall loss and makes complex filtering easy. The trade-off is hardware cost.

Choosing an Index

Situation Starting point
Under ~1M items Brute force or HNSW
1M–100M items, RAM available HNSW
100M+ items, memory-constrained IVF-PQ with re-ranking
Inner-product scoring, CPU serving ScaNN or FAISS inner-product indexes
Heavy filtering, GPU budget Exhaustive GPU search

For a broader treatment, see HNSW and ANN Search Explained.

Key Takeaways

  1. ANN trades a little recall for orders-of-magnitude faster retrieval; measure recall against brute force.
  2. Two-tower retrieval is often inner-product search; normalize embeddings or use MIPS-aware indexes.
  3. IVF partitions, HNSW graphs and PQ compression are the main index families; ScaNN optimizes quantization for inner products.
  4. Freshness, filtering and version alignment are the real production challenges.
  5. GPU exhaustive search is a serious option when filtering is complex and budgets allow.