Vector DBs & RAG (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Approximate Nearest Neighbor (ANN) Algorithms: HNSW vs IVF-Flat vs IVF-PQ benchmarks and recall-vs-latency tradeoffs.
senior LevelHTTP & REST APIs
In Simple Words: Exact nearest neighbor search (kNN) requires calculating distance against every vector in the database ($O(N)$), which is unacceptably slow for millions of vectors. ANN algorithms trade a tiny fraction of accuracy (< 1%) for orders-of-magnitude faster queries:
- HNSW (Hierarchical Navigable Small World):
- Multi-layer graph structure where upper layers have long-range skip edges and lower layers have dense local connections (like an express train subway network).
- Highest recall (> 98%) and lowest search latency (< 5ms).
- Tradeoff: Consumes significant RAM to store graph edge lists.
- IVF-Flat (Inverted File Flat):
- Partitions vector space into Voronoi cells using k-means clustering. At query time, only vectors inside the nearest $n$ centroids (
nprobe) are checked. - Low memory overhead, fast index build time; slightly lower recall than HNSW under high dimensionality.
- Partitions vector space into Voronoi cells using k-means clustering. At query time, only vectors inside the nearest $n$ centroids (
- IVF-PQ: Combines IVF partitioning with Product Quantization to compress vectors, fitting billions of vectors into limited RAM.