Tune approximate vector search against an exact baseline while separating construction, traversal and filter effects.
HNSW retrieval: candidate budgets, graph cost and recall curves
Approximate search trades work for missed neighbors
An HNSW index connects vectors in a layered graph so a search can follow promising neighbors instead of scoring every vector. The returned top-K is approximate: a closer vector may remain unexplored. Increasing the search candidate budget often improves recall but adds distance computations, memory traffic and tail latency. The exact baseline is a full similarity scan over the eligible corpus. A graph result should be measured against that baseline using the same embedding version and permission filters. Filtered ANN covers the additional difficulty of finding neighbors after an access or metadata filter.
Separate build knobs from query knobs
The graph connection limit controls how many edges a node retains, while a construction search width controls how broadly neighbors are considered as the index is built. Larger values can improve connectivity but raise memory and ingestion work. The query-time candidate budget controls exploration for one search; changing it does not rebuild a poor graph. Implementations use different parameter names and defaults, so record the actual backend version and settings with each benchmark. Embedding version must be held fixed while tuning the graph.
Measure recall by query slice
For each judged query, compare approximate top-K IDs with exact top-K IDs and compute overlap or labeled relevant-document recall. Include dense clusters, rare outliers, near duplicates and recently inserted vectors. Report p50 and p95 latency, distance computations, graph bytes and index build time for each budget. An average score can hide a recall collapse on filtered or rare-identifier queries. If vectors are quantized, isolate compression loss by comparing exact search on compressed vectors with exact search on original vectors. Quantization is a separate source of error.
Do not confuse global recall with authorized recall
An unrestricted graph can find nearby documents that a user cannot view. Removing them after top-K may leave too few eligible hits. Raise the exploration budget, use an engine with filter-aware traversal, or search a suitable tenant partition; benchmark each choice at a fixed latency cap. The final result must pass a fresh authorization check even when traversal used an authorized partition. Tenant layout changes both recall and security boundaries.
Use a controlled sweep, then freeze a gate
Sweep several search budgets while keeping corpus, queries, model, K and hardware fixed. Reject settings that fail a minimum recall slice or p95 latency budget. Re-run after large ingestion batches, graph rebuilds and backend upgrades, because segment layout and deleted-node patterns can change traversal. Use a smaller candidate budget only when measured savings matter and the lost evidence is acceptable. Release gates should capture that decision rather than one attractive benchmark chart.
Worked contract
from math import sqrt
def cosine(left: tuple[float, ...], right: tuple[float, ...]) -> float:
numerator = sum(a * b for a, b in zip(left, right))
left_norm = sqrt(sum(value * value for value in left))
right_norm = sqrt(sum(value * value for value in right))
if left_norm == 0 or right_norm == 0:
raise ValueError("zero vector has no cosine similarity")
return numerator / (left_norm * right_norm)
def exact_top_k(query: tuple[float, ...],
vectors: dict[str, tuple[float, ...]],
allowed_ids: set[str], k: int) -> list[str]:
if k < 1 or not query or not all(len(v) == len(query) for v in vectors.values()):
raise ValueError("invalid vector dimensions or K")
scored = [(item_id, cosine(query, vector))
for item_id, vector in vectors.items() if item_id in allowed_ids]
return [item_id for item_id, _ in sorted(
scored, key=lambda item: (-item[1], item[0]))[:k]]
vectors = {"pump-p47": (.9, .1), "pump-p48": (.5, .5),
"pump-p49": (.1, .9), "private-plan": (1.0, 0.0)}
gold = exact_top_k((1.0, .1), vectors,
{"pump-p47", "pump-p48", "pump-p49"}, 2)
approximate = ["pump-p48", "pump-p47"]
recall_at_two = len(set(gold) & set(approximate)) / len(gold)
assert gold == ["pump-p47", "pump-p48"]
assert recall_at_two == 1.0Performance and operating cost
For N eligible vectors of dimension D, the exact baseline takes O(ND + N log N) time with full sorting and O(N) space for scores; top-K selection can reduce the ranking term. HNSW typically visits far fewer vectors, but its practical work depends on graph connectivity, candidate budget, filtering and segment layout rather than a universal constant bound. The code computes an exact benchmark, not an HNSW implementation. The candidate list represents output from an ANN engine and must be obtained from that engine in a real sweep.
Common Mistakes
- Calling a larger query budget a fix for an incompatible embedding version.
- Measuring overlap against an unrestricted exact baseline when users have access filters.
- Reporting only average latency while p95 degrades.
- Attributing quantization errors to graph traversal without a separate exact comparison.
Validation drill
For 97 labeled queries, sweep four candidate budgets with K fixed at 12. Report exact-overlap recall and judged recall by tenant and rare-query slice, plus p95 latency, build time and graph memory.
Read next
- Filtered vector search: measure ANN recall inside the permitted set
- Vector compression: spend memory without losing the answer
- Embedding migrations: keep query and document vectors in one space
- Retrieval release gates: evaluate slices before changing an index
