Vector Search at Scale: HNSW Graphs, IVF-PQ & Semantic Caching
How vector databases search 100M+ embeddings in <10 ms via HNSW multi-layer skip-list graphs, how IVF-PQ compresses RAM by 64×, and how Semantic Caching cuts LLM latency & API bills by 50%+.
Vector Databases accelerate nearest-neighbor search over millions of embeddings using Approximate Nearest Neighbor indexes (HNSW graphs, IVF-PQ) and Semantic Caching.
Brute-force scanning 50 million embeddings takes seconds per query; HNSW retrieves top-K matches in ~5ms, and semantic caches skip redundant LLM calls entirely.
Every vector database (pgvector, Qdrant, Pinecone, Milvus, FAISS) runs HNSW or IVF-PQ under the hood — knowing their 3 tuning knobs saves thousands of dollars in RAM and latency!
Tuning efSearch at query time lets you dial Recall@10 from 92% to 99% on the fly, while adding a Semantic Cache before your LLM can cut repeat FAQ spend by 40%–70%!
Understanding why τ = 0.82 causes catastrophic Semantic Cache False Hits ('reset password' vs. 'delete account') keeps user-facing AI safe.
Classic systems design question: 'How does HNSW achieve O(log N) search, how much RAM does 10M 1536-d vectors need, and how would you add Semantic Caching?'
In a Semantic Cache for a customer support bot, you lower the cosine hit threshold from τ = 0.94 down to τ = 0.80 to get more cache hits. What is the biggest risk?
- Explain why exact brute-force O(N·d) search breaks at millions of vectors and how ANN trades 1% recall for 100× speedup
- Trace HNSW multi-layer navigation and tune its 3 key knobs: M (edges/node), efConstruction, and efSearch
- Contrast HNSW (fast, RAM-heavy) with IVF-PQ (disk/RAM-compact, 64× compression via sub-vector centroids)
- Design a Semantic Cache with threshold τ (0.92–0.96) and explain the False-Hit danger when τ is set too low
Think of HNSW like flying from New York to a café in Tokyo: Layer 2 is an international airport (1 giant hop across the ocean), Layer 1 is the bullet train (zooming into the right district), and Layer 0 is walking down the street to the exact café door! You reach the exact destination in hops without ever visiting every building on Earth!
1. HNSW: Hierarchical Navigable Small World Graphs
Trace the dashed red path below: HNSW enters at the sparse top expressway layer, greedily jumps closer, and drops down to Layer 0 for local refinement.
The 3 Knobs Every Vector DB Exposes
M(16–64): Max bi-directional edges per node. HigherM→ better recall on high-dim vectors, more RAM & slower index build.efConstruction(100–400): Search width during index building. Higher = cleaner graph (build-time cost only!).efSearch(32–256): Dynamic query-time beam width. RaiseefSearchto push Recall@10 from 94% → 99% without rebuilding the index!
2. Scaling to Billions: IVF Clustering + Product Quantization (PQ)
HNSW holds full vectors + graph links in RAM (~80 GB for 10M 1536-d FP32 vectors). When RAM runs out, IVF-PQ compresses vectors by 32×–64×!
How Product Quantization Achieves 64× Compression
- Split a 1536-d FP32 vector (6,144 bytes) into sub-vectors of 16 dims each.
- Run K-Means ( centroids → fits in 1 byte!) on each slice.
- Replace each slice with its 1-byte centroid ID → 96 bytes total (64× smaller!).
- Pro Tip (Two-Step Rescore): Search PQ codes to fetch Top-100 fast, then rescore Top-100 using exact FP16/FP32 vectors from disk/NVMe (DiskANN / Qdrant oversampling) for ~99% recall!
3. Semantic Caching: Turning Repeat Queries into 15 ms Hits
Slide threshold τ in the mini-lab below to see the exact razor's edge between catching valid paraphrases and triggering dangerous False Hits!
Production Semantic Cache Best Practices
- Threshold : High enough to block
'reset password'vs.'delete account'. - TTL + Invalidation: Always attach a Time-To-Live (e.g., 24h) and invalidate when underlying RAG docs update.
- Scope by Metadata: Partition cache by
(tenant_id, model_version, prompt_version)so private answers never leak across users!
Worked Example: Estimating HNSW RAM for 1 Million 1536-d Vectors
1,000,000 documents, 1536-dim FP32 (4 bytes/float), HNSW M = 16.
.
Semantic Cache Threshold τ Tuner
Which HNSW parameter can you increase AT QUERY TIME (without rebuilding the index) to trade slightly higher latency for higher Recall@10?
In pgvector or Qdrant, your HNSW recall dropped when you added a strict WHERE category = 'legal' SQL filter (pre-filtering vs. post-filtering). Why?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
No! Below ~50,000 vectors, exact brute-force dot product (IndexFlatIP) takes <2 ms, gives 100% exact recall, and has zero index-build or graph-RAM overhead!
Multi-Layer HNSW Graph Descent Animator (O(log N) Search)
Watch greedy beam search start on sparse highway Layer 2 and zoom straight into the target neighborhood in Layer 0.
pgvector / Qdrant / Milvus Production RAG
HNSW + scalar INT8 quantization gives 4× RAM reduction with <0.5% recall loss.
Enterprise Support Semantic Cache
Intercepts 40%–65% of high-frequency queries in ~15 ms before touching expensive frontier LLMs.
import torch
import torch.nn.functional as F
# Semantic Cache: Skip Expensive LLM Generation When Cosine Similarity >= Threshold
class SemanticCache:
def __init__(self, threshold: float = 0.92):
self.threshold = threshold
self.keys: list[torch.Tensor] = []
self.values: list[str] = []
def put(self, emb: torch.Tensor, response: str):
self.keys.append(F.normalize(emb, dim=-1))
self.values.append(response)
def get(self, query_emb: torch.Tensor) -> str | None:
if not self.keys:
return None
q = F.normalize(query_emb, dim=-1)
sims = torch.stack(self.keys) @ q
best_sim, idx = sims.max(dim=0)
return self.values[idx.item()] if best_sim.item() >= self.threshold else None
cache = SemanticCache(threshold=0.92)
e1 = torch.randn(32)
cache.put(e1, "Cached answer: FlashAttention tiles Q, K, V in GPU SRAM.")
print("Cache hit:", cache.get(e1 + 0.05 * torch.randn(32)))
(user_id, entity_id, TTL)!IndexFlatIP) preferable to building an HNSW index?