Search Tutorials
--Ads--Optimizing Vector Database Performance
Tune index parameters, filters, quantization, sharding and hardware for fast, accurate vector search.
A vector database that was fast with 100,000 chunks can become slow, expensive or inaccurate at 50 million, especially with filters, many tenants and constant updates. Optimisation is a balance between recall (finding the true nearest neighbours), latency, throughput and cost (mostly memory). This lesson gives a measurement-first method, a benchmark harness you can point at any database, and the main tuning levers: index parameters, quantization, filtering, sharding and operations.
What you will learn
- How to benchmark recall and latency for any vector store against an exact baseline
- How to estimate memory and choose quantization with rescoring
- How to tune HNSW parameters, filtered search and sharding
- Operational practices that keep performance stable as data changes
Prerequisites
Step 1: Measure first
Never tune blindly. Define targets (for example "recall@10 at least 0.95, p95 latency under 50 ms at 200 queries per second") and measure against an exact search on a sample of real queries. This harness works with any search function:
import time
from collections.abc import Callable
import numpy as np
def exact_top_k(corpus: np.ndarray, queries: np.ndarray, k: int) -> np.ndarray:
"""Ground truth by brute force (vectors are L2-normalised, so dot product = cosine)."""
scores = queries @ corpus.T
return np.argsort(-scores, axis=1)[:, :k]
def benchmark(search: Callable[[np.ndarray, int], list[int]], queries: np.ndarray,
truth: np.ndarray, k: int = 10) -> dict:
latencies, recalls = [], []
for q, true_ids in zip(queries, truth):
start = time.perf_counter()
found = search(q, k)
latencies.append((time.perf_counter() - start) * 1000)
recalls.append(len(set(found) & set(true_ids.tolist())) / k)
lat = np.array(latencies)
return {"recall@k": round(float(np.mean(recalls)), 3), "p50_ms": round(float(np.percentile(lat, 50)), 2),
"p95_ms": round(float(np.percentile(lat, 95)), 2), "qps_single_thread": round(1000 / float(lat.mean()), 1)}
rng = np.random.default_rng(0)
corpus = rng.normal(size=(50_000, 384)).astype(np.float32)
corpus /= np.linalg.norm(corpus, axis=1, keepdims=True)
queries = corpus[rng.choice(len(corpus), 200, replace=False)] + rng.normal(scale=0.05, size=(200, 384)).astype(np.float32)
queries /= np.linalg.norm(queries, axis=1, keepdims=True)
truth = exact_top_k(corpus, queries, 10)
def flat_search(q: np.ndarray, k: int) -> list[int]:
return np.argpartition(-(corpus @ q), k)[:k].tolist()
print("flat:", benchmark(flat_search, queries, truth))
flat: {'recall@k': 1.0, 'p50_ms': 6.6, 'p95_ms': 7.54, 'qps_single_thread': 149.3}
To benchmark Qdrant, pgvector, Weaviate or any other store, wrap its query call in a function with the same signature. These numbers come from one run on a laptop CPU; your timings depend on hardware. Use your own embeddings and real queries in practice: random vectors behave differently from text embeddings.
Step 2: Estimate memory and use quantization
Memory is usually the biggest cost. Raw size is vectors × dimensions × bytes, plus index overhead (HNSW graphs add roughly M × 2 × 4 bytes per vector for links at the base layer, a rough rule of thumb):
def memory_gb(vectors: int, dims: int, bytes_per_value: float, hnsw_m: int = 16) -> float:
raw = vectors * dims * bytes_per_value
graph = vectors * hnsw_m * 2 * 4
return round((raw + graph) / 1024**3, 1)
for name, b in [("float32", 4), ("float16", 2), ("int8", 1), ("binary", 1 / 8)]:
print(f"{name:<8} 50M x 1024 dims: {memory_gb(50_000_000, 1024, b):>7} GB")
float32 50M x 1024 dims: 196.7 GB
float16 50M x 1024 dims: 101.3 GB
int8 50M x 1024 dims: 53.6 GB
binary 50M x 1024 dims: 11.9 GB
Quantization shrinks vectors at some loss of accuracy. The standard remedy is rescoring: search the compressed vectors for more candidates than you need, then re-rank those candidates with the full-precision vectors (kept on disk or in cheaper storage). Many databases support this natively (for example oversampling and rescore options in Qdrant, quantized index types in Elasticsearch and OpenSearch). The idea in a few lines:
scale = 127 / np.abs(corpus).max()
corpus_int8 = np.round(corpus * scale).astype(np.int8) # 4x smaller
def int8_search(q: np.ndarray, k: int, oversample: int = 1) -> list[int]:
approx = corpus_int8.astype(np.int32) @ np.round(q * scale).astype(np.int32)
candidates = np.argpartition(-approx, k * oversample)[:k * oversample]
if oversample == 1:
return candidates.tolist()
exact = corpus[candidates] @ q # rescore with float32
return candidates[np.argsort(-exact)[:k]].tolist()
print("int8 :", benchmark(lambda q, k: int8_search(q, k), queries, truth))
print("int8 + x4 :", benchmark(lambda q, k: int8_search(q, k, oversample=4), queries, truth))
int8 : {'recall@k': 0.968, 'p50_ms': 33.39, 'p95_ms': 40.26, 'qps_single_thread': 29.1}
int8 + x4 : {'recall@k': 1.0, 'p50_ms': 34.09, 'p95_ms': 38.57, 'qps_single_thread': 28.9}
In this run, int8 alone found 96.8% of the true top 10, and four-times oversampling with float32 rescoring brought recall back to 100%. (The int8 version is slower here only because NumPy converts to 32-bit integers on every query; vector databases use optimised integer and SIMD kernels, where quantized search is faster than float32.) On real text embeddings the numbers differ, so measure with your own data. Binary quantization saves far more memory but needs larger oversampling and works best with models trained for it.
Step 3: Tune the index
| Parameter (HNSW) | Effect of increasing it | Typical starting point |
|---|---|---|
M (links per node) | Better recall, more memory, slower build | 16–32 |
ef_construction | Better graph quality, slower indexing | 100–200 |
ef_search / ef | Better recall, slower queries (tunable per query) | Start at 64–128; at least k |
Tune ef_search first: it changes nothing at build time, so you can sweep values and plot recall against latency. Change M and ef_construction only if ef_search alone cannot reach the target, since they require re-indexing.
Step 4: Make filtered search fast
- Index every filtered field (payload indexes, keyword fields, B-tree indexes in PostgreSQL).
- Use the database's integrated filtering (filter inside the vector query), not post-filtering, so you still get k results.
- Partition by very selective, always-present filters: a tenant with 0.1% of the data searches faster in its own partition, collection or shard.
- Benchmark with filters: run the harness with realistic tenant and permission filters; filtered recall and latency often differ a lot from unfiltered numbers.
- In pgvector, use iterative index scans for selective filters (RBAC, ABAC and Row-Level Security).
Step 5: Scale out
- Vertical first: more memory and faster disks are often the cheapest fix.
- Replicas add query throughput and availability.
- Shards split data across nodes when it no longer fits; every query fans out to all shards unless you route by tenant.
- Tiered storage: keep hot data in memory and cold or archived data on disk with memory-mapped files or a separate collection.
- Smaller vectors: Matryoshka embeddings can be truncated to fewer dimensions with modest recall loss; measure it.
Step 6: Operate for stable performance
- Batch writes and avoid single-vector upserts in hot loops.
- Watch deletes: many indexes mark deletions and clean up later; heavy update rates can degrade graphs until optimisation or vacuum runs.
- Separate ingestion from serving: large re-indexes can slow queries; schedule them, throttle them, or build a new collection and switch an alias.
- Monitor p95 latency, recall on a fixed probe set, memory use and index size; alert on regressions after every change.
Key takeaways
- Optimise against measurements: recall@k against exact search, plus latency percentiles and throughput.
- Memory dominates cost; use quantization with oversampling and rescoring.
- Tune
ef_searchfirst, thenMandef_constructionif needed. - Index filtered fields, filter inside the vector query, and partition by tenant when filters are very selective.
Frequently asked questions
Is 100% recall necessary?
No. A recall@10 of 0.95 against exact search is usually invisible in answer quality, especially with a reranker. Measure end-to-end answer quality to decide.
When should I switch databases?
When measured targets cannot be met with tuning, hardware and partitioning, or the operating cost is too high. Benchmark the candidate with the same harness and your real data first.
Practice exercises
- Wrap your production vector store's query in the harness and measure recall@10 and p95 latency with and without permission filters.
- Sweep
ef_searchover 16, 32, 64, 128 and 256 and plot recall against latency.
Related tutorials
- Choosing a Vector Database for Production
- Load Testing and Throughput Benchmarking for RAG
- Qdrant Tutorial for RAG