Sub topic 13
Measuring recall and latency and tuning index parameters
This chapter assumes you know what an embedding is, how cosine, dot product and Euclidean distance work, and how HNSW, IVF and product quantization organize vectors. It also assumes you can read basic Python and SQL. Here you will measure how well an approximate index performs and then adjust its parameters with evidence instead of guesses.
Why measurement comes first
An approximate nearest neighbor (ANN) index returns results that are close to the true nearest neighbors, but not always identical to them. Every index parameter moves three quantities at the same time:
- Recall: how many of the true neighbors the index finds.
- Latency: how long a query takes.
- Memory and build cost: how much RAM the index needs and how long it takes to build.
You cannot tune one without watching the others. A setting that raises recall from 0.90 to 0.99 may double latency. A setting that halves memory may drop recall by ten points. Measurement tells you which trade is worth making for your workload.
Recall@k
Recall@k compares the ids an index returns with the ids an exact search returns for the same query.
recall@k = |approximate top-k ∩ exact top-k| / kIf the exact top 10 contains ten ids and the index returns seven of them, recall@10 for that query is 0.7. You then average over many queries.
Some details matter:
- The ground truth comes from brute-force search over the same vectors with the same metric. If the ground truth uses a different metric from the index, the numbers mean nothing.
- Recall@k only counts overlap. It does not check order. If order matters to you, add a rank-aware measure such as mean reciprocal rank.
- Ties in distance can make ground truth ambiguous. With duplicate vectors, two different id lists can both be correct.
- Recall measures agreement with exact search. It does not measure whether the results are useful to users. A perfect-recall index over a poor embedding model still returns poor answers.
Building a test set
Your measurements are only as good as your queries and your data.
- Use realistic queries. Take a sample of real queries if you have them. Queries drawn from random noise behave differently from real ones, because real data has clusters and random vectors do not.
- Keep queries out of the index. The example below uses the first 100 indexed vectors as queries for simplicity. Each query then finds itself as its nearest neighbor, which makes recall look better than it is. For real evaluation, hold out queries that are not in the index.
- Use enough queries. A few hundred is a minimum. Report an average and also look at the worst queries, since a mean of 0.97 can hide a group of queries with recall near zero.
- Use realistic scale. Parameters that work at 10,000 vectors often behave differently at 10 million. Test at or near production size before you commit.
Measuring recall and latency together
The following script builds an exact index and an HNSW index, then sweeps efSearch and reports recall and latency for each value. Queries are held out from the indexed data.
import time
import numpy as np
import faiss
d = 64
k = 10
rng = np.random.default_rng(0)
xb = rng.normal(size=(10000, d)).astype("float32")
xq = rng.normal(size=(200, d)).astype("float32") # held-out queries
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
hnsw = faiss.IndexHNSWFlat(d, 32)
hnsw.hnsw.efConstruction = 200
hnsw.add(xb)
def recall_at_k(approx, truth):
return np.mean([len(set(a) & set(t)) / len(t) for a, t in zip(approx, truth)])
for ef in (10, 20, 40, 80, 160):
hnsw.hnsw.efSearch = ef
hnsw.search(xq[:10], k) # warm up
start = time.perf_counter()
_, ann_ids = hnsw.search(xq, k)
elapsed = time.perf_counter() - start
ms = 1000 * elapsed / len(xq)
print(f"efSearch={ef:4d} recall@{k}={recall_at_k(ann_ids, true_ids):.3f} {ms:.3f} ms/query")Random Gaussian vectors in 64 dimensions are hard for graph indexes, because there is no cluster structure to exploit. Expect lower recall than on real embeddings at the same settings. The shape of the result is what matters: recall rises with efSearch and flattens, while latency keeps rising.
Measuring latency correctly
- Warm up first. The first queries load memory pages and fill caches. Discard them.
- Report percentiles. Average latency hides tail behavior. Measure per-query times and report p50, p95 and p99.
- Separate batch from single-query timing. The script above times one batched call and divides. A production service answers one query at a time under concurrent load, so measure that case too.
- Measure under load. Latency with one client is not latency with fifty. Test at the query rate you expect.
- Include the full path. Network, serialization, filtering and re-ranking add time that a library benchmark leaves out.
The recall and latency curve
When you plot recall against latency for a sweep, you get a curve that rises steeply and then flattens. Early increases in the search parameter buy a lot of recall. Later increases buy little and cost a lot.
The numbers in this chart are illustrative. Your own sweep will give different values. The useful habit is to find the knee of the curve, the point past which extra latency buys little recall, and then choose a setting near it that meets your target.
Parameters that matter
Each index family has a few parameters that control the trade-off. Some act at build time and some at query time. Query-time parameters are cheap to change. Build-time parameters require rebuilding.
| Index | Parameter | When set | Raising it gives | Cost |
|---|---|---|---|---|
| HNSW | `M` (links per node) | Build | Higher recall, especially in high dimensions | More memory, slower build |
| HNSW | `efConstruction` | Build | Better graph quality | Slower build |
| HNSW | `efSearch` (`hnsw.ef_search` in pgvector) | Query | Higher recall | Higher latency |
| IVF | `nlist` (number of clusters) | Build | Smaller lists to scan per cluster | Slower training, more centroids to compare |
| IVF | `nprobe` | Query | Higher recall | Higher latency |
| PQ | number of sub-vectors `m`, bits per code | Build | Better distance accuracy | More memory |
| Any | Re-rank candidate count | Query | Recovers accuracy lost to compression | Extra work and full vectors kept |
Tuning HNSW
Start with M between 16 and 48 and efConstruction between 100 and 400, then tune efSearch at query time. Since efSearch must be at least k to return k results, set it higher than k. A higher M helps most with high-dimensional or hard data, but it grows the graph in memory. Raise efConstruction if recall plateaus below your target even at a large efSearch. That plateau signals a weak graph, which no query-time setting can repair.
Tuning IVF
A common starting point for nlist is on the order of the square root of the number of vectors. Then sweep nprobe. With nprobe equal to nlist, IVF scans everything and matches exact search, which makes a useful sanity check. Recall depends on how the query falls relative to cluster boundaries. A query near a boundary has true neighbors in the next cluster, so a low nprobe misses them.
Tuning product quantization
Compression lowers memory by storing short codes in place of full vectors. It also adds error to every distance. A standard remedy is to fetch more candidates than you need, then re-rank them with distances computed from the original full-precision vectors. This costs extra memory or disk reads for the originals, and it recovers much of the lost recall. Treat the re-rank count as another parameter in your sweep.
A tuning procedure
Work through the parameters in a fixed order so that you change one thing at a time.
- Fix the metric and the embedding model. Changing either invalidates earlier results.
- Compute ground truth with exact search on a realistic query set.
- Set a target, for example recall@10 of at least 0.95 at p95 latency under 20 ms.
- Pick sensible build parameters and build once.
- Sweep the query-time parameter and record recall and latency.
- If no query-time value reaches the target, change a build parameter and rebuild.
- If memory is the limit, add compression, then add re-ranking, then repeat the sweep.
- Record the final settings together with the data size they were tested on.
Tuning in a database
In pgvector you set the query-time parameter per session or per transaction, so you can sweep it with ordinary SQL.
SET hnsw.ef_search = 100;
SELECT id
FROM items
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 10;To get ground truth in the same database, force a sequential scan so the planner ignores the index.
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id
FROM items
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 10;
COMMIT;Compare the two id lists for many queries, exactly as in the Python script. Use EXPLAIN ANALYZE to confirm which plan ran.
Common errors
- Testing with queries that are in the index. Each query finds itself, which inflates recall.
- Mismatched metrics. Ground truth uses L2 while the index uses cosine, or the vectors were not normalized the same way.
- Tuning on a small sample. Settings found at 10,000 vectors often under-deliver at 10 million.
- Reporting only mean latency. The tail is what users notice.
- Chasing recall without a target. Going from 0.98 to 0.999 can cost far more than it is worth, and your embedding model may not distinguish those neighbors anyway.
- Forgetting filters. With metadata filters, an index can return fewer than
krows or lower recall than unfiltered tests suggest. Test with your real filters. - Not rechecking after data changes. Many inserts and deletes can shift recall. Re-run the evaluation periodically.
Exercises
Exercise
An HNSW index reaches recall@10 of 0.93 at efSearch=100 and 0.94 at efSearch=400, while latency quadruples. Recall is still below your 0.97 target. Which parameter should you change next, and why?
Show answer
Change a build parameter, such as raising M or efConstruction, and rebuild. The flat curve shows that query-time effort is no longer helping, which points to a weak graph. Raising efSearch further would only add latency.
Exercise
You evaluate an IVF index using the first 200 indexed vectors as queries and get recall@10 of 0.99. Why might this number mislead you, and how do you fix the test?
Show answer
Each query is itself in the index, so it is trivially its own nearest neighbor, and its cluster is likely to be probed. This inflates recall. Hold out queries that are not in the index, ideally drawn from real traffic, and compute ground truth for them with exact search.
Exercise
Why should you report p95 or p99 latency in addition to the average?
Show answer
The average hides slow outliers caused by cache misses, large result scans or contention. Users experience the slow queries, and a service-level target is usually stated in percentiles.