ANN Search at Scale
After this lesson, you will be able to:
- Explain why exact nearest-neighbor search is impossibly slow at scale and the recall–latency tradeoff that ANN algorithms exploit
- Pick HNSW for general-purpose, IVF-PQ for memory-constrained, ScaNN for very large scale, and tune ef_search / nprobe to hit your latency target
- Use product quantization to compress 1.5KB float32 vectors to 32 bytes at a recall cost that depends on the dataset and settings
- Build a billion-vector serving system with the right index, sharding strategy, and recall@k targets
Before you start
Open the /play/vector-search playground to see HNSW search hop from the sparse top layer down to the dense bottom layer. Push ef_search up and watch latency rise while recall@10 climbs from 0.85 → 0.99 — that's the knob production teams tune for their SLA.
#The Recall-Latency-Memory Triangle
The cost of exact search is simple counting. Open the derivation to see where the 400 GB and the O(N d) come from.
#HNSW: The Production Default
The number of layers is not a design choice: it falls out of the random rule that gives each new point its top layer. Open the derivation to see why the layers thin out by a factor M and why there are about log base M of N of them.
HNSW knobs to tune
M(edges per node): higher = better recall, more memory. Default 16-32.efConstruction(build-time exploration): higher = better graph quality. Default 100-400.efSearch(query-time exploration): higher = better recall, slower. Most-tuned param. Sweep 50-500 to hit latency target.
#IVF-PQ: Memory-Optimized at Billion Scale
nprobe nearest cells. Reduces search space by N/K.The speed-up K / nprobe ignores one cost, the scan of the centroids. Open the derivation to see the exact count, why K is chosen near the square root of N, and what uneven cells cost.
Both the memory and the speed of product quantization come from counting. Open the derivation to see the bytes per vector and why the approximate distance is a sum of table lookups.
OPQ (Optimized PQ) to recover most of the lost recall via learned rotations.#ScaNN: Google's Anisotropic Quantization
ScaNN is open source (see Google Research's release for the current packaging).
#Decision Rubric
You have 500M vectors, each 1024-dim float32. You need 50ms p95 latency, 95% recall@10, and have a budget of 256GB RAM total across your serving fleet. What index?
nprobe to hit the 95% recall target.| Setting | Recommended index | Knobs |
|---|---|---|
| Up to 10M vectors, ample RAM | HNSW (Flat) | M=32, efSearch sweep |
| 10M–100M, RAM constrained | HNSW + scalar quantization (int8) | Same + 4× compression |
| 100M–1B, tight memory | IVF-PQ or IVF-OPQ | nlist=√N, nprobe=16, m=d/32 |
| 1B+, latency-critical | ScaNN or DiskANN | Domain-specific tuning |
#Sharding for Horizontal Scale
- Random sharding: vectors distributed uniformly across K nodes. Query goes to all K nodes; results merged. Linear scale-out, no hotspots.
- Semantic sharding: cluster vectors first; query routed to relevant clusters only. Lower latency, harder to maintain at scale.
Production systems (Pinecone, Vespa, custom built-on-Cassandra) use random sharding with replica fanout for redundancy.
#The Math of Quantization Error
2^nbits, subvector count m, and reconstruction error on synthetic embeddings, then sweeps the recall@10 vs memory Pareto frontier.#Hands-On
The cell below builds an IVF index in plain numpy so it runs on this page. It clusters the vectors with k-means, then at query time searches only the nprobe nearest clusters and reports how much of the data it scanned and how much recall it kept.
Tests: Verify that recall@10 rises as nprobe rises, that nprobe=64 gives recall 1.000 because every cluster is searched, and that the scanned share rises with nprobe.
The real library (faiss) adds HNSW graphs and product quantization, and it needs a package that is not available on this page. The version below is read-only. Copy it to Google Colab (run the pip line first).
# Copy to Colab: needs faiss, so it cannot run on this page.
# Compare brute-force, HNSW, and IVF-PQ on a 100K-vector corpus
# !pip install faiss-cpu
import numpy as np
import faiss
import time
# --- Generate synthetic data ---
np.random.seed(42)
N, dim = 100_000, 256
xb = np.random.randn(N, dim).astype('float32')
xb /= np.linalg.norm(xb, axis=1, keepdims=True)
xq = np.random.randn(10, dim).astype('float32')
xq /= np.linalg.norm(xq, axis=1, keepdims=True)
# --- 1. Exact (brute force) ---
flat = faiss.IndexFlatIP(dim)
flat.add(xb)
t = time.time()
D_true, I_true = flat.search(xq, k=10)
print(f"Brute force: {(time.time()-t)*1000:.1f}ms (this is the ground truth)")
# --- 2. HNSW ---
hnsw = faiss.IndexHNSWFlat(dim, 32, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 200
hnsw.add(xb)
for ef in [50, 100, 200]:
hnsw.hnsw.efSearch = ef
t = time.time()
D_h, I_h = hnsw.search(xq, k=10)
elapsed = (time.time()-t)*1000
recall = np.mean([
len(set(I_h[i]) & set(I_true[i])) / 10 for i in range(len(xq))
])
print(f"HNSW efSearch={ef}: {elapsed:.1f}ms, recall@10={recall:.3f}")
# --- 3. IVF-PQ ---
nlist = 256
m = 16 # PQ subvectors → 16 bytes per vector vs 1024 raw
quantizer = faiss.IndexFlatIP(dim)
ivfpq = faiss.IndexIVFPQ(quantizer, dim, nlist, m, 8)
ivfpq.train(xb)
ivfpq.add(xb)
for nprobe in [4, 16, 64]:
ivfpq.nprobe = nprobe
t = time.time()
D_p, I_p = ivfpq.search(xq, k=10)
elapsed = (time.time()-t)*1000
recall = np.mean([
len(set(I_p[i]) & set(I_true[i])) / 10 for i in range(len(xq))
])
print(f"IVF-PQ nprobe={nprobe}: {elapsed:.1f}ms, recall@10={recall:.3f}")
print(f"\nMemory:")
print(f" Raw vectors: {xb.nbytes / 1e6:.0f} MB")
print(f" IVF-PQ index: ~{N * m / 1e6:.1f} MB ({xb.nbytes / (N * m):.0f}× compression)")
print("\nCHALLENGE: Try faiss.index_factory(dim, 'OPQ16,IVF256,PQ16').")
print("OPQ rotates vectors before PQ to recover part of the recall lost to plain PQ.")#Key Takeaways
- HNSW is the production default for general-purpose ANN — fast, accurate, easy to tune (M, efSearch)
- IVF-PQ wins when memory is tight. Trade some recall (an amount that depends on the dataset and settings) for 128× memory compression
- ScaNN targets very large scale through anisotropic quantization that preserves query-relevant inner products
- Tune
efSearch(HNSW) ornprobe(IVF) to hit your recall@k target — sweep these, not the build-time params - Sharding scales horizontally when one machine isn't enough — random sharding is the default
#Quick Check
You're storing 1B 1024-dim float32 embeddings. Raw size is ~4TB. Which index lets you serve from a single 64GB-RAM machine?