hnswlib developer on retainer: set_ef() not persisted by save_index() — ef resets to 10 on load_index() — recall@10 drops 95.3% to 62.1% — 3 weeks silent degradation — $60,000 — 2 months
hnswlib 0.7.0; Python 3.11; index.set_ef(200) at build time for 95.3% recall@10; save_index() persists graph structure (M, ef_construction, vectors) but does NOT persist ef; load_index() on deployment server resets ef to default 10; recall@10 drops from 95.3% to 62.1%; 2.1 million document embeddings (1536-dim); 500 queries/hour returning incorrect top-10 results for 3 weeks; no error; fix: index.set_ef(200) after every load_index() call • Northfield HNSWLib Search Ltd. (4-person; 2 months; 1.5h)
Northfield HNSWLib Search Ltd. is a 4-person legal document search startup that built a semantic search API over 2.1 million court filings, contracts, and case law documents. They embedded the corpus using OpenAI’s text-embedding-ada-002 (1536 dimensions) and indexed it with hnswlib for approximate nearest neighbor retrieval. During index construction, they tuned M=16 and ef_construction=200, then called index.set_ef(200) before benchmarking. The build-time recall benchmark on 1,000 held-out queries showed 95.3% recall@10 — comfortably above their 90% SLA. save_index() wrote the 14 GB index to disk. On deployment, recall dropped to 62.1%. The same 1,000-query benchmark returned incorrect top-10 documents for 38% of queries, with no error, no warning, and correct response shapes from the API.
The team spent three weeks investigating the wrong root cause. They attributed the recall drop to the OpenAI embedding model having changed its output distribution (OpenAI had released an updated ada-002 version around that time), and re-embedded 100,000 high-traffic documents as a test — recall improved by 0.3%, well within noise. They adjusted cosine similarity thresholds and tried switching to inner product distance — recall dropped further to 48%. They opened an issue with their cloud vector store provider suspecting infrastructure-level quantization. At no point did anyone print index.ef in the deployed environment and compare it to the build-time value. The deployed value was 10. The build-time value was 200.
# index_build.py — Northfield HNSWLib Search Ltd.
# hnswlib 0.7.0; Python 3.11; 2.1M embeddings (1536-dim text-embedding-ada-002)
import hnswlib
import numpy as np
import json
DIM = 1536
N = 2_100_000
index = hnswlib.Index(space="cosine", dim=DIM)
index.init_index(
max_elements=2_200_000,
ef_construction=200, # saved to disk ✓
M=16, # saved to disk ✓
random_seed=42,
)
index.add_items(vectors, labels, num_threads=16)
# Set search-time ef for benchmarking
index.set_ef(200)
# print(index.ef) → 200
# Benchmark recall@10 before saving
recall = evaluate_recall(index, test_queries, ground_truth, k=10)
print(f"Recall@10: {recall:.4f}") # → 0.9527
# Save index to disk
index.save_index("legal_index.bin")
# Bug: save_index() writes the HNSW graph — node vectors, neighbor lists,
# M, ef_construction, element count — to the binary file.
# It does NOT write index.ef (the query-time search parameter).
# index.ef is a runtime attribute of the Python/C++ object in memory.
# After load_index(), the C++ HierarchicalNSW constructor resets ef_ = 10
# (hardcoded default in hnswlib/hnswalg.h:
# explicit HierarchicalNSW(...) : ... ef_(10) { ... }
# )
#
# No warning is printed. index.save_index() returns None.
# The saved file is correct — it's a valid, intact HNSW graph.
# The ef is simply not part of what gets saved.
# index_config.json is NOT created — the team never saved ef separately
# index_deploy.py — production server (EC2 c6i.4xlarge)
# Bug: ef not restored after load_index()
import hnswlib
DIM = 1536
index = hnswlib.Index(space="cosine", dim=DIM)
index.load_index("legal_index.bin", max_elements=2_200_000)
# After load_index():
# index.M == 16 ✓ (loaded from file)
# index.ef_construction == 200 ✓ (loaded from file)
# index.element_count == 2,100,000 ✓
# index.ef == 10 ← RESET TO DEFAULT (not in file)
#
# No error. No warning. The index is fully valid.
# Queries run. Response shapes are correct.
# But ef=10 means the greedy beam search maintains only 10 candidates
# during traversal — far fewer than ef=200 (which maintains 200 candidates).
# HNSW traversal with ef=10 terminates much earlier:
# For recall@10, ef must be large enough to explore a region of the graph
# that reliably contains the true 10 nearest neighbors.
# ef=10: recall@10 = 62.1% (barely explores beyond the greedy path)
# ef=50: recall@10 = 83.4%
# ef=100: recall@10 = 90.1%
# ef=200: recall@10 = 95.3% ← build-time benchmark value
#
# The ef=10 configuration also runs FASTER (4ms p99 vs 18ms p99 at ef=200)
# which the team read as a sign the index was healthy.
def search(query_vector, k=10):
labels, distances = index.knn_query(query_vector, k=k)
return labels[0], distances[0]
# Results:
# Recall@10: 62.1% (SLA requires 90%)
# p99 latency: 4ms (looks great — it's wrong recall, not slow)
# Error rate: 0% (all queries return k=10 results with valid cosine scores)
During the retainer triage, one diagnostic revealed the problem immediately: printing index.ef in the deployed environment returned 10 — and printing it in the build environment (where the recall benchmark was run) returned 200. The hnswlib documentation for set_ef() notes that it sets the “query time accuracy/speed trade-off” but does not explicitly state that this value is not saved by save_index(). The fix is a one-line addition to the deployment code. Adding a startup assertion and a recall sanity check ensures the issue cannot silently recur on future index rebuilds.
Fix: call index.set_ef() after every load_index()
# Fixed index_build.py — Northfield HNSWLib Search Ltd.
import hnswlib, json
TARGET_EF = 200
index.set_ef(TARGET_EF)
recall = evaluate_recall(index, test_queries, ground_truth, k=10)
print(f"Recall@10 at ef={TARGET_EF}: {recall:.4f}") # → 0.9527
index.save_index("legal_index.bin")
# Fix: also save ef to companion config
config = {
"ef": TARGET_EF,
"M": 16,
"ef_construction": 200,
"dim": DIM,
"space": "cosine",
"max_elements": 2_200_000,
"num_elements": index.get_current_count(),
}
json.dump(config, open("index_config.json", "w"))
# Fixed index_deploy.py
import hnswlib, json
config = json.load(open("index_config.json"))
index = hnswlib.Index(space=config["space"], dim=config["dim"])
index.load_index("legal_index.bin", max_elements=config["max_elements"])
# Fix: restore ef immediately after load
index.set_ef(config["ef"])
assert index.ef == config["ef"], f"ef not set: got {index.ef}, expected {config['ef']}"
K = 10
assert index.ef >= K, (
f"ef={index.ef} must be >= k={K}. "
"hnswlib requires ef >= k for valid knn_query results."
)
# Startup recall sanity check (runs in ~2 minutes at ef=200 on 100 queries)
canary_recall = evaluate_recall(index, canary_queries, canary_ground_truth, k=K)
assert canary_recall >= 0.90, (
f"Production recall@{K} = {canary_recall:.3f} below 0.90 threshold. "
f"Check ef configuration (current ef={index.ef})."
)
print(f"Startup recall@{K}: {canary_recall:.4f} ✓")
# Results after fix — Northfield HNSWLib Search Ltd.:
# Recall@10: 95.3% (was 62.1%)
# p99 latency: 18ms (was 4ms — correct tradeoff for ef=200)
# Startup assertion: passes
# Future index rebuilds: ef always restored from index_config.json
#
# 4 engineers × 2 months × $7,500/month = $60,000
Related retainer posts
- FAISS developer on retainer — FAISS;
IndexIVFFlatloaded in separate process;make_direct_map()not called afterread_index();index.reconstruct()raises direct_map is not initialized; fetch-by-ID feature blocked 3 weeks; 1.5h - sentence-transformers developer on retainer — sentence-transformers; indexing pipeline encodes with
normalize_embeddings=False; inference service encodes query withnormalize_embeddings=True; dot product not cosine similarity; recall@10 drops 78% to 31%; 3 weeks; 1.5h - ChromaDB developer on retainer — ChromaDB; embedding model switch from Sentence Transformers to OpenAI silently breaks retrieval; cosine similarity returns meaningless scores; 78% recall drop; 3 weeks; 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →