Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

14.2 Vector Indexing & DB Solutions

After choosing an embedding, the next question is how to find useful neighbors within a latency and memory budget. Exact search is an important quality reference and can be practical with batching or a selective filter. Approximate nearest-neighbor (ANN) indexes reduce search work at the cost of a workload-dependent recall trade-off. Neither “sub-millisecond” latency nor negligible recall loss follows from choosing an index name.

1. Start with an Exact Reference

For NN vectors of dimension dd, a flat distance scan performs O(Nd)O(Nd) coordinate work. Real latency also depends on memory traffic, metric, batching, hardware and concurrency. A billion FP32 vectors with d=768d=768 need Nd×4=3.072N d\times4=3.072 TB for the vectors alone, before identifiers, replicas, metadata and temporary buffers.

Use exact top-k results to define ANN recall on a sampled, authorized corpus, and use human relevance labels to assess whether embedding neighbors are useful. High ANN recall only means agreement with the exact metric search; it does not validate the embedding, evidence freshness, or answer quality.

2. HNSW: Hierarchy and a Candidate Budget

HNSW builds nested proximity graphs, with all vectors in the bottom layer and progressively fewer in upper layers [1]. Bottom-layer connectivity remains sparse, not a complete dense graph. Search uses sparse upper layers to approach a promising region, then explores a bounded candidate set near the bottom.

M influences how many links the graph stores per node. efConstruction controls how widely the builder searches for links to a new node. At query time, efSearch sets the size of the list of best candidates the layer search keeps. The algorithm can expand more nodes than fit in that list. Measure recall against an exact scan and record the latency on your own queries as you vary efSearch [1] [5].

Why take a step away from the query?

Place the query at (100,180)(100,180). The upper layers lead to node 25, which is 97.74 units from the query. Of the bottom-layer neighbors of 25, the one nearest the query is node 24 at 105.44 units. A walk that only moves closer stops at 25. Yet node 24 connects to 16, and 16 connects to 17. Node 17 is just 9.49 units from the query, the closest of all 40 points.

Start again at 25. Keep a priority queue of discovered nodes whose neighbors you have yet to inspect. At each expansion, open the closest queued node, choosing the smaller node ID on a tie. Add its unseen neighbors to the queue and update the closest point found so far. After expanding 24 you can already return 16. After expanding 16 you can return 17 without expanding 17 itself. Use the slider to see which answer is available after one, two or three expansions. Then switch to (480,250)(480,250) and see whether the extra expansions change the answer.

Search the same graph two ways

Query coordinates and selected routeNode 0Node 1Node 2Node 3Node 4Node 5Node 6Node 7Node 8Node 9Node 10Node 11Node 12Node 13Node 14Node 1516Node 1617Node 17Node 18Node 19Node 20Node 21Node 22Node 2324Node 2425Node 25Node 26Node 27Node 28Node 29Node 30Node 31Node 32Node 33Node 34Node 35Node 36Node 37Node 38Node 39

The cross marks the query. The green ring marks the nearest of all 40 points. The large blue dot marks the current node. Click the graph to move the query.

From node 25, 3 nodes expanded. The line traces the route to the closest node discovered so far, 17.

Bottom-layer search from node 25 · distance to the query in parentheses
StepNode expandedClosest discovered
125 (97.74)25 (97.74)
224 (105.44)16 (65.73)
316 (65.73)17 (9.49)

To check why the greedy rule refuses the detour, calculate all four Euclidean distances with Python’s standard library. The first step would make the distance increase.

from math import dist

query = (100, 180)
route = [(25, (112, 277)), (24, (39, 266)), (16, (36, 195)), (17, (109, 183))]
for node, point in route:
    print(node, round(dist(query, point), 2))

On each layer, each point selects up to three nearest peers. The links work in both directions, so a point selected by other peers can have more than three neighbors. The three-expansion limit lets you count exactly whose neighbors were inspected. HNSW constructs links during insertion and uses the distance to the worst retained candidate in its stopping rule. Setting efSearch=3 on a database will therefore give a different search procedure [1].

3. Quantization, IVF and ScaNN

Different index mechanisms can be combined; “graph” and “quantized” are not mutually exclusive categories.

MechanismWhat it changesEngineering cost to measure
Flat exact scanEvaluates every eligible vectorVector traffic, batching, candidate population
HNSW graphVisits connected candidate neighborhoodsGraph links, construction, exploration, update behavior
IVF partitioningSearches selected coarse clustersTraining, cluster imbalance, number of probes, missed clusters
Product quantization (PQ)Stores codebook indices instead of full vectorsCodebooks, approximate distances, optional exact refinement
ScaNN-style searchCombines search stages with quantization tailored to scoringTraining, scoring/refinement budget, hardware and metric

Guo et al.’s anisotropic quantization penalizes components of reconstruction error differently to better preserve high inner-product scores [2]. This is more specific than saying that keeping a vector’s direction always preserves ranking: norms matter in unnormalized maximum-inner-product search. Cosine similarity is equivalent to inner product only with appropriate normalization. Compare full systems at matched recall and throughput rather than declare one algorithm universally faster.

For a storage example, PQ with M=96M=96 subspaces and 256 centroids uses 8 bits per subspace, hence 96 code bytes per vector. One million vectors require 96 MB for codes. With dimension 768 and FP32 codebooks, centroids add 96×256×8×4=786,43296\times256\times8\times4=786{,}432 bytes. IDs, coarse centroids, graph links, alignment, metadata, replicas, and optional full-vector refinement are additional. A code-size reduction is not the same as a total service-memory reduction.

4. Filters Are Part of Retrieval and Authorization

A relevant HR document must not reach a user who lacks permission. Keep tenant identity, ACL version and retention/deletion state attached to the source and every derived representation. A metadata field alone does not enforce authorization: the query service must verify and apply the policy before content, snippets, caches or logs become visible.

Post-filtering a fixed ANN candidate list can leave too few eligible results. Restricting traversal to eligible graph nodes can disconnect useful paths. Implementations may traverse ineligible nodes without returning their content, use filter-aware edges, choose a filtered exact scan, or adapt their search plan. Qdrant’s discussion illustrates implementation-specific techniques; it is not evidence that all databases share one filtering algorithm [4].

Evaluate recall within the eligible population, result completeness, latency and information leakage across low/high-selectivity filters. Test negative permissions, stale ACL caches, tenant isolation, deletion, replicas, and restored snapshots. A correct top-k list with unauthorized evidence is still a failed retrieval system.

5. From an Index to a Service

As of 2026-10-25, the FAISS maintainers’ selection guide distinguishes exact, graph, partitioned and compressed choices by constraints such as training, storage and search work [3]. A library provides algorithms; a managed or self-hosted service must additionally provide durability, concurrent updates, filtering, backup/restore and operational visibility. Product names alone do not establish those guarantees.

Benchmark the intended corpus, query distribution, dimensions, metric, batch size, concurrent load, hardware, filters and update churn. Record index version, build seed/order, embeddings/tokenizer, distance settings and search parameters. Report recall–latency curves, p50/p95/p99 latency, build time, memory/storage with replicas, ingestion lag, deleted-record exposure and error rates. Include a filtered exact baseline where feasible.

Promote a new index using a shadow route and a versioned cutover. Require paired quality evidence, critical authorization/deletion gates and an owner with explicit abort thresholds. Keep the last-known-good route and rehearse restore and rollback with deletion tombstones preserved. Section 14.3 then combines retrieval signals and spends reranking computation on the resulting candidates.

Quizzes

Quiz 1: Why retain an exact baseline for ANN? It isolates index approximation error from embedding relevance error. Compare eligible populations under the same metric and filters.

Quiz 2: Why does opening node 24 help even though it is farther from the query than node 25? Opening 24 reveals node 16. Opening 16 reveals the exact nearest node, 17. A greedy walk stops before it can inspect the first of those edges.

Quiz 3: Does a 32× reduction in PQ code bytes imply 32× less service memory? No. Codebooks, identifiers, graph/coarse index data, metadata, replicas, buffers and optional refinement vectors remain.

Quiz 4: Why can filtering change ANN recall? Post-filtering can exhaust candidates, while constrained graph traversal can lose routes. Evaluate the implementation within the eligible population and enforce authorization separately.

Quiz 5: What must a rollback preserve besides vectors? Versioned embeddings, metric and search settings, ACLs, provenance and deletion tombstones must remain consistent. Restoring a snapshot must not resurrect deleted or unauthorized evidence.

References

  1. Malkov, Y. A., & Yashunin, D. A. (2018 revision). Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs. Paper.
  2. Guo, R., et al. (2020). Accelerating Large-Scale Inference with Anisotropic Vector Quantization. ICML. Paper.
  3. FAISS maintainers. Guidelines to choose an index. Verified 2026-10-25. Official wiki.
  4. Qdrant. Filterable HNSW Without Recall Loss. Verified 2026-10-25. Implementation-specific discussion. Technical article.
  5. hnswlib maintainers. Algorithm parameters, search parameter ef. Implementation notes.