Why tuning HNSW can improve retrieval without changing your embedding model or LLM.
Many AI engineers improve RAG systems by switching embedding models, adding rerankers, or upgrading LLMs.
But sometimes the real bottleneck is inside the vector index.
Even when the correct document exists in your vector database, approximate nearest-neighbor search can fail to return it.
Today, let’s look at how HNSW configuration affects retrieval quality, latency, and production cost.
Exact vs. approximate search
Exact nearest-neighbor search compares the query vector with every stored vector.
It gives you the true nearest neighbors, but becomes expensive as your corpus grows.
Approximate Nearest Neighbor (ANN) search trades a small amount of recall for much faster retrieval.
One of the most widely used ANN algorithms is HNSW — Hierarchical Navigable Small World.
Instead of scanning every vector, HNSW builds a multi-layer graph and navigates through it to find nearby candidates efficiently.
What research says
Malkov and Yashunin introduced HNSW as a graph-based approach to approximate nearest-neighbor search.
The method balances retrieval recall, search latency, memory consumption, and index construction time.
The important engineering question is not:
“Which HNSW setting is fastest?”
It is:
“Which setting retrieves the right evidence within my latency budget?”
Three HNSW parameters
| Parameter | What it controls | Trade-off |
|---|---|---|
m | Graph connectivity | More memory and slower builds for potentially better recall |
ef_construction | Candidate exploration during index building | Longer build time for a higher-quality graph |
ef_search | Candidate exploration during queries | Higher recall at the cost of higher query latency |
m defines the maximum number of links per node. ef_construction is the candidate-list size during index construction. ef_search is the candidate-list size during search. docs.pgedge
Increasing ef_search generally improves recall, but each query has to explore more candidates. arxiv
Practical pgvector setup
For cosine similarity, create an HNSW index like this:
CREATE INDEX documents_embedding_idx ON documents USING hnsw (embedding vector_cosine_ops) WITH ( m = 16, ef_construction = 64 ); Then tune query-time exploration:
SET hnsw.ef_search = 100; Retrieve the ten nearest documents:
SELECT id, content FROM documents ORDER BY embedding <=> :query_embedding LIMIT 10; The major advantage of ef_search is that it can be changed without rebuilding the index.
By contrast, changing m or ef_construction requires rebuilding the HNSW index.
Start with defaults
Do not begin by copying a “high-performance” configuration from the internet.
Start with pgvector’s defaults:
m = 16 ef_construction = 64 ef_search = 40 These are common defaults: m = 16, ef_construction = 64, and ef_search = 40. docs.pgedge
Then measure retrieval quality and latency on your own data.
A practical starting progression is:
| Configuration | Expected effect |
|---|---|
ef_search = 40 | Fast baseline; may miss relevant neighbors |
ef_search = 80 | Better recall; moderate latency increase |
ef_search = 100 | Often a strong production starting point |
ef_search = 200 | Higher recall potential; higher latency and compute cost |
These are expected trends, not guaranteed benchmark results.
Actual performance depends on corpus size, vector dimensionality, embedding model, query distribution, hardware, index size, and concurrent load.
Evaluate the right way
A meaningful benchmark compares approximate search with exact search using the same:
- Queries
- Embedding model
- Vector dimensions
- Distance metric
- Top-k setting
- Filtering rules
Track both vector-search metrics and RAG-level metrics.
| Metric | What it tells you |
|---|---|
| ANN Recall@10 | How many exact top-10 neighbors HNSW recovered |
| Relevant Recall@10 | How many human-labeled relevant documents were retrieved |
| P50 latency | Typical query latency |
| P95 latency | Tail latency users are more likely to notice |
| Queries per second | Search throughput |
| Answer quality | Whether the final RAG response is correct and grounded |
ANN Recall@10 measures whether approximate search recovers the same top ten vectors as exact search.
But retrieving the nearest vectors does not always mean retrieving the most relevant evidence.
That is why you also need relevance labels and end-to-end RAG evaluation.
A production RAG pipeline
User Query ↓ Query Understanding ↓ Embedding Model ↓ HNSW Vector Search ↓ Retrieved Chunks ↓ Reranking ↓ LLM Generation ↓ Final Answer If the necessary evidence never enters the candidate set, the reranker cannot recover it.
A stronger LLM cannot solve that problem either.
Before upgrading your generation model, investigate your retrieval pipeline.
How to tune in production
Use this sequence:
- Build a representative evaluation set from real user queries.
- Label the relevant documents or chunks for each query.
- Run exact search to establish ground truth.
- Measure ANN Recall@10 and relevance Recall@10.
- Tune
ef_searchfirst, because it does not require an index rebuild. - Record P50 and P95 latency, QPS, memory usage, and answer quality.
- Only increase
moref_constructionif recall remains inadequate. - Re-evaluate after changes to embeddings, chunking, filters, or corpus distribution.
Set a recall floor and a latency ceiling.
For example:
“Maintain at least 95% ANN Recall@10 while keeping P95 vector-search latency below 50 ms.”
Then choose the least expensive configuration that meets both constraints.
Common mistakes
- Tuning HNSW without a labeled retrieval evaluation set.
- Optimizing only average latency instead of P95 latency.
- Treating ANN recall as proof of retrieval relevance.
- Changing
moref_constructionbefore testingef_search. - Ignoring metadata filters, tenant isolation, recency rules, and permissions.
- Assuming a reranker can compensate for missing retrieved evidence.
- Changing embedding models without rebuilding and re-evaluating the index.
Key takeaway
A production-ready RAG system is not just a powerful embedding model connected to a vector database.
It requires understanding the relationship between:
- Retrieval accuracy
- Index configuration
- Latency
- Memory
- Cost
- Downstream answer quality
Don’t optimize only for faster retrieval. Optimize for retrieving the right evidence within your latency budget.
Research and references
Malkov & Yashunin — Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs
https://arxiv.org/abs/1603.09320pgvector — HNSW documentation
https://github.com/pgvector/pgvectorThe Impacts of Data, Ordering, and Intrinsic Dimensionality on HNSW
https://arxiv.org/html/2405.17813v1
How do you balance retrieval recall and latency in your production RAG applications?