Skip to content
Skip to lesson
Back to Topics
LearnAdvanced Agents & RetrievalVector DB Internals: HNSW & IVF
HardEmbeddings & Vector Search20 min read

Vector DB Internals: HNSW & IVF

Scan 100 million embeddings naively and every query touches 153.6 billion floats. Build HNSW, IVF, and Product Quantization from scratch, then tune recall, memory, and filtered search.

On this page

Suppose your search engine holds 100 million 1,536-dimensional , and a query arrives with a 15-millisecond latency budget. Exact scan streams 572 GiB of float32 numbers and scores 153.6 billion scalar components for a single request. Yet skipping 99.9% of the corpus risks missing the exact passage the user needed. How can an index ignore almost every vector in R1536\mathbb{R}^{1536} and still land in the right neighborhood?

Every modern vector database builds on three ideas: navigates a multi-layer proximity graph, partitions space into coarse Voronoi cells and opens only a few, and compresses vectors into short byte codes so billions fit in RAM.

The embedding lesson fixed the ranking rule (metric and normalization). A vector index approximates that exact ranking faster and in less memory; it cannot rescue weak embeddings, and its accuracy is always judged against exact search on the same vectors.

The brute-force problem

Exact search (flat search) scores query qq against every stored vector in work. Raw float32 storage alone requires:

100,000,000 vectors×1,536 dims×4 bytes≈614 GB≈572.2 GiB100{,}000{,}000 \text{ vectors} \times 1{,}536 \text{ dims} \times 4 \text{ bytes} \approx 614 \text{ GB} \approx 572.2 \text{ GiB}

Classic k-d trees partition one coordinate axis at a time and prune subtrees via bounding boxes, which works in 2D or 3D but collapses around 20 dimensions.[1] When many coordinates carry independent variance, distance concentration clusters pairwise distances tightly around their mean so bounding boxes overlap almost everywhere (whereas zero-padding 1D points into 768D leaves their true intrinsic distances unchanged).

inspects a tiny candidate subset and scores its accuracy against exact top-kk with :

Recall@k=∣Sapprox∩Sexact∣k\text{Recall@}k = \frac{\lvert S_{\text{approx}} \cap S_{\text{exact}} \rvert}{k}

If exact top-5 is [10, 21, 34, 55, 89], a fast setting returning [10, 21, 8, 13, 5] achieves 40% Recall@5, while a tuned setting returning [10, 21, 34, 55, 3] reaches 80%. Keep ANN recall distinct from relevance recall: an index can hit 100% ANN recall while faithfully reproducing a mediocre embedding model.

Two index mechanisms narrow the candidate pool handed to exact distance scoring. On the left, HNSW walks proximity-graph links from entry v7 through v4 and v6 to expand base-layer neighbors v8 and v3. On the right, IVF places query q at x=4.9 on the List 0 side of Voronoi boundary x=5, selecting List 0 (v0, v1, v2) and skipping List 1 (v3, v4). Both feed their narrowed candidate pool into exact metric scoring and top-k selection.
HNSW walks proximity-graph links while IVF opens selected Voronoi lists. Both shrink the candidate pool handed to exact distance scoring.

HNSW (Hierarchical Navigable Small World)

When your working set fits in RAM and you want low latency without offline clustering, HNSW is usually the first index to try.[3]

Skip-lists generalized to high-dimensional graphs

HNSW generalizes a 1D skip-list to a proximity graph in Rd\mathbb{R}^d.[3] Each inserted vector vv samples its maximum layer ℓ\ell from an exponential decay distribution. Setting mL=1/ln⁡(M)m_L = 1 / \ln(M) yields a geometric ladder:

P(level≥ℓ)=exp⁡(−ℓ/mL)=(1M)ℓP(\text{level} \ge \ell) = \exp(-\ell / m_L) = \left(\frac{1}{M}\right)^\ell

Every vector resides on Layer 0, roughly N/MN/M on Layer 1, N/M2N/M^2 on Layer 2, up to height ≈log⁡MN\approx \log_M N. Upper layers act as sparse express highways; Layer 0 is the dense local road network.

Search runs in two phases:

  1. Greedy descent on upper layers: From the global entry point on the top layer, hop to any closer neighbor until reaching a local minimum, then drop to the same vector on the next layer below.
  2. Beam search on Layer 0: A greedy walk on Layer 0 traps in local minima, so Layer 0 expands a beam of width ef_search using two heaps: a min-heap candidates (closest unexpanded node first) and a max-heap results (holding at most ef_search closest vectors found so far). Pop the closest candidate cc; if results is full and cc is farther than the worst item in results, stop and return the best kk items. Otherwise inspect cc's unvisited neighbors and push improvements onto both heaps.
Search greedily descends from the entry point across sparse upper layers (dashed arrows keep the same node ID), then runs a two-heap beam search of width ef_search on Layer 0.

Why HNSW prefers diverse neighbors over nearest neighbors

Three build parameters shape the graph: M (upper-layer link cap), M0 (Layer-0 cap, normally 2M2M), and ef_construction (insertion beam width). Wiring a new node vv blindly to its MM closest neighbors creates dense local cliques with poor inter-cluster bridges. HNSW's diversity heuristic (SELECT-NEIGHBORS-HEURISTIC) visits candidates in ascending distance to vv and keeps candidate ee only if it is closer to vv than to every already-selected neighbor nn:

d(e,v)<d(e,n)∀n∈selectedd(e, v) < d(e, n) \quad \forall n \in \text{selected}

Skipping candidates hidden right behind existing links forces edges to point outward in fresh directions.[3]

Tracing an insertion and building a working HNSW

Insertion mirrors search: sample top layer ℓ\ell, greedily descend layers above ℓ\ell, then run beam search of width ef_construction on layers ℓ\ell down to 00, adding reciprocal links and pruning adjacency lists exceeding 2M (Layer 0) or M (upper layers). The global entry point changes only if ℓ\ell strictly exceeds the current maximum layer.

This self-contained HNSW (using nearest-MM pruning for brevity) builds a 2-layer graph and shows why widening ef_search rescues a query whose only path to the true nearest neighbor crosses a farther bridge node:

hnsw-insert-and-search.py

def greedy_search(graph: MiniHNSW, query: tuple[float, ...], entry: int, level: int) -> int:
    current = entry
    while True:
        best = min([current, *graph.neighbors(current, level)], key=lambda n: sq_l2(query, graph.vectors[n]))
        if best == current:
            return current
        current = best

def search_layer(graph: MiniHNSW, query: tuple[float, ...], entry: int, level: int, ef: int) -> list[int]:
    visited = {entry}
    d0 = sq_l2(query, graph.vectors[entry])
    candidates, results = [(d0, entry)], [(-d0, entry)]  # min-heap & bounded max-heap
    while candidates:
        dist, current = heapq.heappop(candidates)
        if len(results) >= ef and dist > -results[0][0]:
            break
        for nb in graph.neighbors(current, level):
            if nb in visited:
                continue
            visited.add(nb)
            d = sq_l2(query, graph.vectors[nb])
            if len(results) < ef or d < -results[0][0]:
                heapq.heappush(candidates, (d, nb))
                heapq.heappush(results, (-d, nb))
                if len(results) > ef:
                    heapq.heappop(results)
    return [node for _, node in sorted((-neg, node) for neg, node in results)]

def insert(graph: MiniHNSW, node_id: int, vector: tuple[float, ...], level: int) -> None:
    graph.vectors[node_id] = vector
    for layer in range(level + 1):
        graph.edges.setdefault((node_id, layer), [])
    if graph.entry_point is None:
        graph.entry_point, graph.max_level = node_id, level
        return

    entry = graph.entry_point
    for layer in range(graph.max_level, level, -1):
        entry = greedy_search(graph, vector, entry, layer)
    for layer in range(min(level, graph.max_level), -1, -1):
        candidates = search_layer(graph, vector, entry, layer, graph.ef_construction)
        chosen = sorted(candidates, key=lambda i: sq_l2(vector, graph.vectors[i]))[: graph.M]
        cap = 2 * graph.M if layer == 0 else graph.M
        for nb in chosen:
            if nb != node_id:
                if nb not in graph.edges[(node_id, layer)]:
                    graph.edges[(node_id, layer)].append(nb)
                graph.edges.setdefault((nb, layer), [])
                if node_id not in graph.edges[(nb, layer)]:
                    graph.edges[(nb, layer)].append(node_id)
                prune(graph, nb, layer, cap)
        prune(graph, node_id, layer, cap)
        entry = min(candidates, key=lambda i: sq_l2(vector, graph.vectors[i]))
    if level > graph.max_level:
        graph.entry_point, graph.max_level = node_id, level

def search(graph: MiniHNSW, query: tuple[float, ...], k: int = 2, ef_search: int = 4) -> list[int]:
    if ef_search < k:
        raise ValueError("ef_search must be at least k")
    current = graph.entry_point
    assert current is not None
    for layer in range(graph.max_level, 0, -1):
        current = greedy_search(graph, query, current, layer)
    return search_layer(graph, query, current, 0, ef_search)[:k]
Output
mL for M=16: 0.361, P(level >= 1) = 6.2%, first upper draw after 36 samples
HNSW top-2:  [1, 2]
Exact top-2: [1, 2]
bridge ef=1: [0]
bridge ef=3: [2]

With ef_search = 1, node 1 is farther than entry 0 so the beam stops immediately and misses node 2; raising ef_search to 3 crosses the bridge. Always keep ef_search >= k (results holds at most ef_search items, and engines like hnswlib reject ef < k).[4][2]

Key HNSW knobs and memory budget

ParameterRoleStarting valueTrade-off
MUpper-layer link cap per node16Higher M boosts recall at extra RAM and build time.
M0Layer-0 adjacency cap2 * MDenser base layer improves local routing.
ef_constructionBuild-time beam width200Cleaner graph at slower indexing speed.
ef_searchQuery-time beam width (>= k)64 (for k=10)Tunable per query without rebuilding; higher raises recall and latency.
mLLayer-sampling scale1/ln⁡(M)1 / \ln(M)Controls upper-layer density.

At high float32 dimensions, raw vectors dominate RAM rather than graph links: for d=1,536d = 1{,}536 and M=16M = 16, each vector takes 6,1446{,}144 bytes while 2M=322M = 32 4-byte Layer-0 neighbor IDs take only 128128 bytes (98.0% vector, 2.0% Layer-0 links). Links become a large share only after compression or at low dimensions. Tune ef_search at query time by sweeping recall against p95 latency and choosing the fastest setting that clears your floor (for example, choosing ef_search = 48 at 0.97 recall and 6.8 ms p95 over ef_search = 24 at 0.91 recall or 96 at 12.4 ms against a 0.96 recall / 10 ms target).

Graph traversal shines in RAM, yet it still requires adjacency lists and lacks a fixed scan fraction. Partitioning space into cells solves both.

IVF (Inverted File Index)

IVF replaces graph links with coarse geometric partitions. Offline learns K=nlistK = \text{nlist} cluster centroids c1,…,cKc_1, \dots, c_K (the coarse quantizer), dividing Rd\mathbb{R}^d into KK Voronoi cells:

Vi={x∈Rd∣∥x−ci∥2≤∥x−cj∥2    ∀j≠i}V_i = \{x \in \mathbb{R}^d \mid \|x - c_i\|^2 \le \|x - c_j\|^2 \;\; \forall j \ne i\}

Each indexed vector appends to its nearest centroid's inverted list. A query scores all nlist centroids, picks the closest nprobe cells, and scans only those lists.[5][6] With 1 million vectors, nlist = 1,024, and nprobe = 5, balanced IVF scores 1,0241{,}024 centroids plus 5×(106/1,024)≈4,8835 \times (10^6 / 1{,}024) \approx 4{,}883 list vectors (≈5,907\approx 5{,}907 total comparisons, 169x less work than brute force).

Why nprobe = 1 misses neighbors across cell edges

When a query lands near the dividing plane between two Voronoi cells, its true nearest neighbor can sit just across the line in the neighboring cell. Raising nprobe opens adjacent cells and recovers it:

Top left: equal-unit 2D Voronoi map showing centroids C0=(0,0) and C1=(10,0), their dividing line x=5, query q=(4.9,0), and vectors v0, v1, v2, v3, v4. Top right: magnified view of the x=5 boundary showing distances 0.30 from q to v2=(4.6,0) and 0.50 from q to v3=(5.4,0) across the boundary. Bottom: aligned distance-rank comparison strips showing nprobe=1 (List 0 only) returning v2 and v1 for 50% Recall@2, while nprobe=2 (List 0 + List 1) recovers v2 and v3 for 100% Recall@2.
Query q = (4.9, 0) falls on the List 0 side of the Voronoi dividing line x = 5. Probing List 0 alone misses v3 = (5.4, 0) (distance 0.50); probing both lists recovers the exact top-2.
ivf-nprobe-edge-miss.py

def ivf_search(query: tuple[float, ...], nprobe: int, k: int = 2) -> list[int]:
    probed = sorted(centroids, key=lambda c: sq_l2(query, centroids[c]))[:nprobe]
    scored = [(sq_l2(query, vectors[vid]), vid) for cid in probed for vid in lists[cid]]
    return [vid for _, vid in sorted(scored)[:k]]
Output
inverted lists: {0: [0, 1, 2], 1: [3, 4]}
exact top-2:    [2, 3]
nprobe=1:       [2, 1]
nprobe=2:       [2, 3]

With balanced lists, IVF scans roughly nprobe / nlist of the corpus. In IVF-Flat, probing all nlist cells recovers exact search; in IVF-PQ, quantization error remains even at full scan.

Distance metrics and centroid geometry

Every index ranks under one metric: squared L2, Inner Product (IP) (⟨x,y⟩\langle x, y \rangle), or (L2-normalize stored vectors and queries, then run IP).[7] On unit vectors, L2 and IP induce identical rankings because ∥x−y∥2=2−2⟨x,y⟩\|x - y\|^2 = 2 - 2\langle x, y \rangle:

verify-cosine-inner-product-ranking.py
import numpy as np

vectors = np.array([[3.0, 0.0], [1.0, 1.0], [0.0, 2.0]])
query = np.array([1.0, 0.8])
unit_v = vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
unit_q = query / np.linalg.norm(query)

print("IP rank on unit vectors:", np.argsort(-(unit_v @ unit_q)).tolist())
print("L2 rank on unit vectors:", np.argsort(np.sum((unit_v - unit_q) ** 2, axis=1)).tolist())
Output
IP rank on unit vectors: [1, 0, 2]
L2 rank on unit vectors: [1, 0, 2]

HNSW vs. IVF-Flat at a glance

FeatureHNSWIVF-Flat
StructureMulti-layer proximity graphCoarse centroids + inverted lists
Offline trainingNoneRequired (kk-means centroids)
MemoryRaw vectors + ~2M2M Layer-0 IDsRaw vectors + IDs (no graph edges)
Updates & driftIncremental inserts; deletes vary by engineEasy inserts; distribution drift stales centroids
Main query knobef_searchnprobe
Best fitLow-latency, high-recall in-RAM searchPredictable scan fraction or base for PQ

Graph search and compression are orthogonal (IndexHNSWFlat, IndexHNSWSQ, IndexHNSWPQ, IndexIVFPQ in Faiss).[6] Yet raw float32 vectors still break RAM at billion scale: 109×768×4 bytes≈3.07 TB10^9 \times 768 \times 4\text{ bytes} \approx 3.07\text{ TB}. Fitting a billion vectors into RAM requires shrinking each vector.

Product Quantization (PQ)

Product Quantization (PQ) splits a dd-dimensional vector into mm disjoint subvectors x=[u1,…,um]x = [u_1, \dots, u_m] (uj∈Rd/mu_j \in \mathbb{R}^{d/m}) and runs kk-means independently on each subspace to learn a codebook CjC_j of K∗=256K^* = 256 centroids.[8] Because 256=28256 = 2^8, each centroid ID fits in one uint8 byte:

codej(x)=arg⁡min⁡k∈{0,…,255}∥uj−cj,k∥2\text{code}_j(x) = \arg\min_{k \in \{0, \dots, 255\}} \|u_j - c_{j,k}\|^2

For d=768d = 768 and m=96m = 96 (d∗=8d^* = 8), a 3,072-byte float32 vector shrinks to 96 bytes (32x code-only compression; adding an 8-byte ID gives 104 bytes per record). The 96 shared codebooks use only 96×256×8×4=768 KiB96 \times 256 \times 8 \times 4 = 768\text{ KiB} globally while spanning 25696256^{96} reconstructed points. In L2 IVF-PQ, PQ normally encodes the residual r=x−clistr = x - c_{\text{list}} around each coarse centroid so residuals cluster near zero and quantize more accurately.[9] Optimized Product Quantization (OPQ) learns an orthogonal rotation RR jointly with the codebooks to balance variance across subspaces while preserving L2 distance (OPQ96,IVF4096,PQ96).[10][11]

Product quantization splits a 768-dimensional float32 vector into 96 eight-dimensional subvectors. Each subvector maps to one of 256 centroids in its own codebook and contributes one byte, reducing 3,072 bytes to 96 bytes (32x compression). At query time, an uncompressed query builds a 96 by 256 float32 distance table. Asymmetric Distance Computation sums 96 precomputed centroid distances without reconstructing the full vector.
Each 8D subvector maps to one byte (a 32x code reduction from 3,072 B to 96 B). At query time, ADC precomputes a 96 x 256 lookup table so scoring a compressed vector requires only 96 table lookups and additions.

Asymmetric Distance Computation (ADC)

At query time, leaves the query qq uncompressed and never reconstructs stored vectors. Slice q=[q1,…,qm]q = [q_1, \dots, q_m], precompute one cache-resident m×256m \times 256 lookup table T[j][k]=∥qj−cj,k∥2T[j][k] = \|q_j - c_{j,k}\|^2 (96 KiB for m=96m = 96), and score any code [c1,…,cm][c_1, \dots, c_m] with mm indexed additions:[9]

d(q,y)2≈∑j=1mT[j][cj]d(q, y)^2 \approx \sum_{j=1}^{m} T[j][c_j]

The script below implements ADC and shows code collision: two distinct vectors sharing one PQ code cannot be ordered until you overfetch and rerank against full-precision originals.

asymmetric-distance-computation-adc.py
import numpy as np

def adc_search(query: np.ndarray, codes: np.ndarray, codebooks: np.ndarray, k: int = 2) -> list[int]:
    m, _, d_sub = codebooks.shape
    q_subs = query.reshape(m, d_sub)
    tables = np.sum((codebooks - q_subs[:, None, :]) ** 2, axis=2)  # (m, K*) lookup table
    dists = np.sum(tables[np.arange(m), codes], axis=1)             # m additions per code
    return sorted(range(len(codes)), key=lambda i: (float(dists[i]), i))[:k]
Output
768D float32: 3072 B -> PQ96: 96 B (32x), +8B ID = 104 B
ADC top-2 for origin: [0, 1]
collision top-1 without overfetch: [0] | after overfetch+rerank: [1]

Real retrieval filters by tenant, region, or date (region = 'EU'). Three strategies behave very differently under selective filters:

  1. Pre-filter then exact scan: Resolve metadata first via B-tree or bitmap, then run flat search on the matching rows. Fast and exact when only a few thousand rows match; too slow when millions match (and stripping disallowed nodes from an HNSW graph beforehand can disconnect it).
  2. Post-filtering: Fetch an unfiltered buffer of LL ANN candidates, then discard non-matches. With selectivity s=0.005s = 0.005 and L=100L = 100, expected matches are E[M]=L⋅s=0.5E[M] = L \cdot s = 0.5, and the probability of zero results is (1−s)L=0.995100≈60.6%(1 - s)^L = 0.995^{100} \approx 60.6\% under independence (or 1−s=99.5%1 - s = 99.5\% when nearby vectors share excluded metadata).
  3. Filter-aware traversal and iterative scans: expands iterative ANN scans (hnsw.max_scan_tuples, ivfflat.max_probes) until kk matches are collected or a scan cap hits.[2] sweeps across disallowed nodes without returning them and supports ACORN traversal, skipping distance computation on non-matches with multi-hop jumps from eligible entry points.[12][13]
post-filter-starvation.py
L, s = 100, 0.005
print(f"expected matches:              {L * s:.2f}")
print(f"independent empty probability: {(1 - s) ** L:.1%}")
print(f"correlated empty probability:  {1 - s:.1%}")
Output
expected matches:              0.50
independent empty probability: 60.6%
correlated empty probability:  99.5%
buffer L=3: ['eu-1']
buffer L=5: ['eu-1', 'eu-2']
Side-by-side 2D vector neighborhoods compare post-filtering versus pre-filtered ACORN traversal for query q=(5,5) with predicate region=EU and k=3. On the left, the unfiltered top-3 circle captures eu-1, us-1, and us-2; dropping disallowed US points leaves only eu-1 (1/3 underfilled). On the right, filter-aware ACORN traversal skips US nodes and steps cleanly through eligible EU vectors eu-4, eu-2, eu-1, and eu-3 to fill all 3/3 slots.
Post-filtering a fixed global top-3 neighborhood drops disallowed US neighbors and underfills at 1/3 (`eu-1` only); pre-filtered ACORN traversal skips excluded US nodes inside the index to fill all 3/3 eligible EU slots.

Scaling to billions and choosing an index

Beyond single-machine RAM, three architectures dominate:

  1. IVF-PQ in RAM: Faiss's IndexIVFPQ stores ceil(m_pq * nbits / 8) + 8 bytes per vector (code + 64-bit ID): ~40 GB for 1B vectors at 32-byte codes, or ~104 GB at 96-byte codes.[6]
  2. SSD-backed graphs (DiskANN): Keeps a compact compressed index in RAM and stores full vectors and adjacency lists on NVMe SSD to minimize random reads, achieving >5,000 QPS at <3 ms mean latency and 95%+ 1-recall@1 on SIFT1B on one 16-core, 64 GB RAM + SSD machine.[14]
  3. Horizontal sharding (scatter-gather): Partition the corpus across SS disjoint shards, query all SS shards, and merge local top-kk lists on comparable scores. When every shard runs exact search with consistent tie-breaking and all SS shards respond, the S⋅kS \cdot k candidates are guaranteed to contain the exact global top-kk (any omitted item already trails kk items on its own shard); dropping a slow shard or using approximate per-shard search breaks that guarantee.
Four-shard scatter-gather timeline on one shared 0 to 95 ms axis. Shard 1 returns 5 local candidates at 44 ms, Shard 2 at 58 ms, Shard 3 at 86 ms, and Shard 4 at 51 ms. The coordinator waits for the slowest shard at 86 ms before running a 3 ms merge that reduces 20 local candidates to the global top 5 at 89 ms.
A scatter-gather coordinator waits for the slowest shard (86 ms) before running the final merge (3 ms, finishing at 89 ms).

Full fan-out amplifies tail latency (Tquery≥max⁡(T1,…,TS)+TmergeT_{\text{query}} \ge \max(T_1, \dots, T_S) + T_{\text{merge}}). If each shard independently clears its threshold t99t_{99} with probability 0.990.99, all SS shards clear it with probability 0.99S0.99^S: 96.1% across 4 shards, dropping to 81.8% across 20 shards (where cluster p99 is driven by the single-shard 0.991/20≈99.95th0.99^{1/20} \approx 99.95\text{th} percentile). Use replica hedging or per-shard deadlines with explicit partial-result flags to rein in tails.

Index family comparison

Index familyCore mechanismStrengthMain costReach for it when
HNSWHierarchical proximity graphFast, high-recall in-RAM searchRaw-vector RAM, build time, deletesVectors fit in RAM and low latency matters
IVF-FlatCoarse Voronoi cells + exact list scanPredictable scan fractionOffline training, raw-vector RAMYou want fixed scan budgets without graph edges
IVF-PQIVF + subspace byte codes + ADC~10x-32x smaller footprintQuantization error, rerank tuningRAM capacity is the primary bottleneck
DiskANNSSD-resident graph + compact RAM guideBillion-scale on one NVMe nodeStorage-layout and I/O engineeringCorpus exceeds RAM but single-node SSD fits

When evaluating any vector engine, check four fundamentals: which ANN families it exposes, how it executes filtered search, where the index lives (RAM, NVMe, object storage), and what compression plus full-precision reranking knobs it supports.

When vector indexes break

SymptomLikely root causeConcrete fix
IVF recall drops over monthsEmbedding distribution drifted from stale centroidsRetrain centroids on recent data and rebuild lists
HNSW exhausts RAMFloat32 vectors + links + allocator overhead exceed memoryMeasure bytes/vector; adopt SQ, PQ, or IVF-PQ
Fast queries miss obvious matchesToo-small ef_search / nprobe, PQ error, or metric mismatchCheck exact baseline first; separate recall from reranking
Cosine switch tanks IVF recallCentroids trained on unnormalized L2 vectorsNormalize all vectors and retrain centroids for IP
Deleted docs still appearTombstones, dead tuples, or lagging replicasTest delete visibility; run compaction or index rebuild
Adding shards spikes p99Full fan-out waits on slowest shardPrune shard routing, hedge requests, or cap shard deadlines

Hands-on: metric migration and deletion in Faiss

Run this self-contained Faiss script with uv run vector-index-replay.py to see metric geometry and deletion behavior directly.[6][7] Under raw L2, [1, 1] beats [10, 0] for query [1, 0.1]; after L2 normalization and inner-product indexing, [10, 0] aligns along the query and wins. Removing ID 101 leaves Faiss's -1 sentinel in the unfilled second slot:

vector-index-replay.py
vectors = np.array([[10.0, 0.0], [1.0, 1.0]], dtype="float32")
ids = np.array([101, 202], dtype="int64")
query = np.array([[1.0, 0.1]], dtype="float32")

raw_l2 = faiss.IndexIDMap2(faiss.IndexFlatL2(2))
raw_l2.add_with_ids(vectors, ids)
_, raw_ids = raw_l2.search(query, 1)

unit_vectors, unit_query = vectors.copy(), query.copy()
faiss.normalize_L2(unit_vectors)
faiss.normalize_L2(unit_query)
cosine = faiss.IndexIDMap2(faiss.IndexFlatIP(2))
cosine.add_with_ids(unit_vectors, ids)
_, cosine_ids = cosine.search(unit_query, 1)

removed = cosine.remove_ids(np.array([101], dtype="int64"))
_, after_delete = cosine.search(unit_query, 2)
Output
Raw L2 winner: 202
Cosine winner after rebuilding: 101
Removed records: 1
Results after delete: [202, -1]

Check for -1 sentinels when fewer than k matches exist, propagate deletes across replicas before cutover, and benchmark ef_search or nprobe against an exact top-kk baseline under real queries and metadata filters.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A collection holds 20 million vectors with 1,024 float32 dimensions. Before index overhead, what raw bytes and component comparisons does an unfiltered exact query require?
2.Exact top-4 IDs are [2, 7, 11, 19]. Candidate A returns [2, 7, 30, 31] in 6 ms; candidate B returns [2, 7, 11, 31] in 14 ms. The target requires at least 70% recall and at most 15 ms. Which result qualifies?
3.An HNSW graph reaches layer 3. A new node samples layer 1 with M=12 and construction beam 80. Which insertion trace matches standard HNSW construction?
4.An HNSW search requests k=12 with ef_search=6. What should the caller do before running the query?
5.A flat-coarse IVF-Flat index stores 2 million vectors in 512 balanced lists. Moving nprobe from 3 to 12 changes which comparison counts?
6.An IVF index trained on raw vectors under L2 is switched to cosine by normalizing only queries. Recall drops. Which migration restores cosine geometry?
7.A 1,024-dimensional float32 vector uses 128 PQ subspaces with 256 centroids each. Excluding record IDs and shared codebooks, what code size and raw-to-code compression ratio result?
8.Two ADC lookup rows are [0, 9] and [0, 16]. A stored code is [1, 0]. What is the squared-L2 ADC score?
9.An ANN query fetches 100 candidates, then application code filters for region = EU. Only 1% of rows match EU and final k is 10. What are the two problems with this setup?
10.Six disjoint shards use exact scoring with a consistent tie order. Each shard returns its local top-4. If every shard responds, what can the coordinator conclude?

10 questions remaining.

References

SciPy KDTree: High-Dimensional Search Caveat

SciPy Contributors · 2026

https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html

pgvector

pgvector contributors · 2026 · GitHub

https://github.com/pgvector/pgvector

Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs

Malkov, Y. A., & Yashunin, D. A. · 2018 · IEEE Transactions on Pattern Analysis and Machine Intelligence

https://arxiv.org/abs/1603.09320

HNSW algorithm parameters

nmslib/hnswlib Contributors · 2026

https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md

Billion-scale similarity search with GPUs.

Johnson, J., Douze, M., & Jégou, H. · 2017 · arXiv preprint

https://arxiv.org/abs/1702.08734

Faiss indexes

Meta, Faiss Contributors · 2026

https://github.com/facebookresearch/faiss/wiki/Faiss-indexes

MetricType and distances

Meta/Faiss Contributors · 2026

https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances

Product Quantization for Nearest Neighbor Search.

Jégou, H., Douze, M., & Schmid, C. · 2011 · IEEE TPAMI 2011

https://doi.org/10.1109/TPAMI.2010.57

Faiss Implementation Notes

Faiss Developers · 2026

https://github.com/facebookresearch/faiss/wiki/Implementation-notes

Optimized Product Quantization for Approximate Nearest Neighbor Search

Ge, T., He, K., Ke, Q., & Sun, J. · 2013

https://openaccess.thecvf.com/content_cvpr_2013/html/Ge_Optimized_Product_Quantization_2013_CVPR_paper.html

The index factory

Faiss Contributors · 2026

https://github.com/facebookresearch/faiss/wiki/The-index-factory

ACORN: Performant and Predicate-Agnostic Search Over Vector Embeddings and Structured Data

Patel, L., Kraft, P., Guestrin, C., & Zaharia, M. · 2024

https://arxiv.org/abs/2403.04871

Filtering

Weaviate · 2026

https://docs.weaviate.io/weaviate/concepts/filtering

DiskANN: Fast Accurate Billion-point Nearest Neighbor Search on a Single Node.

Subramanya, S. J., et al. · 2019 · NeurIPS

https://proceedings.neurips.cc/paper/2019/hash/09853c7fb1d3f8ee67a61b6bf4a7f8e6-Abstract.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.