A team ships a retrieval feature on a laptop. Fifty thousand document chunks, a default index, a nearest-neighbour query that returns in a few milliseconds, and every demo goes well. Six months later the corpus holds twenty million chunks across a few hundred customers, each query must be restricted to one customer, and the same code answers in a second or two, or returns the wrong neighbours, or gets the node killed by the out-of-memory reaper. Nothing in the application changed. The data crossed a threshold where the choices made at demo time (index type, vector precision, where the filter runs) stopped being free.
Comparing Qdrant, Milvus and pgvector is usually framed as a leaderboard question: which one is fastest. That framing hides the useful part. All three can serve approximate nearest-neighbour search well, and published numbers depend heavily on dimensionality, recall target, filter selectivity and hardware. What differs is the shape of each system: where memory goes, how filters interact with the index, what happens during writes, and how many moving parts you have to operate. This article walks through those mechanics so you can predict where each one will hurt, and then shows how to measure it on your own data instead of trusting anyone's chart, including ours.
1. The memory arithmetic that decides most of the design
Before comparing products, do the arithmetic that all of them share. A float32 vector costs 4 bytes per dimension. Ten million vectors of 768 dimensions is 10,000,000 × 768 × 4 bytes, roughly 30.7 GB of raw vector data. At 1,536 dimensions it is about 61 GB. This is before any index, replication or headroom, and it is the number that determines whether you are shopping for a laptop, a single large node or a cluster.
The graph index itself is comparatively small. An HNSW index with M = 16 stores up to 2 × M neighbour links per node on the bottom layer, so roughly 32 links × 4 bytes = 128 bytes per vector, around 1.3 GB for ten million vectors, plus a small contribution from the upper layers. The vectors dominate, the graph is a rounding error next to them, and that is why quantization is the lever that matters most.
Quantization changes the bill, not just the speed
- Scalar quantization (int8): one byte per dimension instead of four. The same ten million 768-dimension vectors drop to about 7.7 GB, a 4x reduction, usually with a modest recall cost that rescoring recovers.
- Product quantization: splits each vector into sub-vectors and replaces each with a codebook index. A 768-dimension vector can shrink to tens of bytes. The compression is large and the recall loss is larger, so it is normally paired with a rescoring pass.
- Binary quantization: one bit per dimension, a 32x reduction (96 bytes for 768 dimensions). It works best with high-dimensional embeddings that were trained to tolerate it, and almost always needs rescoring with the original vectors.
- Lower-precision storage types: storing float16 halves the footprint with little visible effect on most embedding models.
Rescoring is the part that makes aggressive compression usable. The engine searches the compressed vectors to get a generous candidate list, then re-ranks only those candidates using full-precision vectors, which may live on disk because only a few hundred are touched per query. You pay a few random reads in exchange for keeping the bulk of the data off RAM.
2. Index families: HNSW, IVF and disk-based graphs
Exact search compares the query against every vector. It is perfectly accurate and scales linearly, which is acceptable for tens of thousands of vectors and painful beyond that. Approximate indexes trade a small, tunable amount of recall for large reductions in work. Three families cover most of what you will meet.
HNSW: layered proximity graphs
Hierarchical Navigable Small World graphs connect each vector to nearby vectors and add sparser upper layers that act like express lanes. A query enters at the top, greedily walks toward the query, drops a layer, and repeats, finishing with a best-first search on the bottom layer that keeps a candidate list of size ef. Three parameters matter: M (links per node), ef_construction (candidate list while building) and ef_search (candidate list while querying). Larger values raise recall and cost memory, build time or latency. HNSW gives excellent recall-versus-latency behaviour in RAM, supports incremental inserts, and is weaker on deletes, because removing a node leaves holes that engines handle with tombstones and periodic rebuilds.
IVF: partition first, scan a few partitions
Inverted-file indexes cluster the vectors (often with k-means) into nlist cells, then at query time scan only the nprobe cells whose centroids are nearest to the query. Build time and memory are lower than HNSW, and the structure combines naturally with quantization (IVF-PQ, IVF-SQ). The cost is that quality depends on clustering done at build time. If the data distribution drifts, the centroids go stale and recall quietly falls until you retrain.
Disk-oriented graphs
DiskANN-style indexes keep a graph and compressed vectors in memory while the full-precision vectors and neighbour lists live on SSD, which makes billion-scale search feasible on modest RAM at the cost of higher and more variable latency. They fit when the corpus is far larger than memory and SSD latency is acceptable. They are overkill below a few tens of millions of vectors for most teams.
3. pgvector: the database you already operate
pgvector adds vector column types, distance operators and approximate indexes to PostgreSQL. It supports HNSW and IVFFlat indexes, several distance functions (L2, inner product, cosine), and types beyond the plain float32 vector, including half-precision, binary and sparse variants in recent releases. Check the current documentation for exact dimension limits per type, since they have changed between versions.
Its strongest argument is not speed but surface area. Embeddings live next to the rows they describe, so a similarity search, a relational filter, a join and a permission check are one SQL statement inside one transaction. When a document is deleted or a customer's access is revoked, the vector goes with it, with no second system to keep consistent. For many products the corpus is a few million vectors and the simplest architecture is the right one.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
tenant_id integer NOT NULL,
doc_id bigint NOT NULL,
body text NOT NULL,
embedding vector(768) NOT NULL
);
-- ANN index for similarity, plain b-tree for the relational filter
CREATE INDEX chunks_embedding_hnsw
ON chunks USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 200);
CREATE INDEX chunks_tenant_idx ON chunks (tenant_id);
-- Per-session recall/latency knob
SET hnsw.ef_search = 100;
-- Top 10 neighbours for one tenant ($1 is the query embedding)
SELECT id, doc_id, body
FROM chunks
WHERE tenant_id = 42
ORDER BY embedding <=> $1
LIMIT 10;
The limits are the limits of Postgres. The HNSW graph competes with everything else for shared_buffers and the OS page cache, large index builds are memory- and time-hungry, autovacuum and bloat behaviour apply to the vector table like any other, and a single primary caps write throughput. Horizontal scale means partitioning, read replicas or an extension layer, which brings you back toward operating a distributed system anyway. The planner may also pick a b-tree on tenant_id instead of the vector index, which is correct for tiny tenants and surprising for large ones; read the EXPLAIN output rather than assuming.
4. Qdrant: filtering and quantization as first-class features
Qdrant is a purpose-built vector engine. Data lives in collections divided into segments, each vector can have an associated JSON payload, and the HNSW graph is aware of payload indexes, which is the design choice that shapes its filtering behaviour (more in section 6). Quantization (scalar, product, binary) is configured per collection, vectors and the graph can be placed on disk independently of one another, and a cluster distributes shards and replicas across nodes. It also supports sparse vectors and multiple named vectors per point, which helps with hybrid retrieval.
from qdrant_client import QdrantClient, models
client = QdrantClient(url="http://localhost:6333")
client.create_collection(
collection_name="chunks",
vectors_config=models.VectorParams(
size=768,
distance=models.Distance.COSINE,
on_disk=True, # full-precision vectors off RAM
),
hnsw_config=models.HnswConfigDiff(m=16, ef_construct=200),
quantization_config=models.ScalarQuantization(
scalar=models.ScalarQuantizationConfig(
type=models.ScalarType.INT8,
always_ram=True, # compressed copy stays in memory
)
),
)
# Index the field you filter on, or the filter degrades to a scan
client.create_payload_index(
collection_name="chunks",
field_name="tenant_id",
field_schema=models.PayloadSchemaType.KEYWORD,
)
hits = client.query_points(
collection_name="chunks",
query=query_embedding, # list[float], length 768
query_filter=models.Filter(
must=[models.FieldCondition(
key="tenant_id", match=models.MatchValue(value="acme"))]
),
search_params=models.SearchParams(
hnsw_ef=128,
quantization=models.QuantizationSearchParams(rescore=True),
),
limit=10,
).points
The trade-off is one more system to run. You now own a second datastore, a sync path from your primary database, and the question of what happens when the two disagree. That cost is real, and it is the reason to prefer pgvector until a concrete limit forces the move.
5. Milvus: a distributed system with separate roles
Milvus is designed as a cloud-native, disaggregated system. In its distributed deployment, responsibilities are split across roles: proxies accept requests, coordinators track metadata and schedule work, data nodes handle ingestion, index nodes build indexes, and query nodes serve searches. Durable state lives in object storage, with a metadata store and a message or log stream coordinating writes. Exact component choices have changed across releases, so read the architecture page for the version you deploy.
Data arrives in growing segments that are searched by brute force or a lightweight index, then sealed and indexed in the background. That separation gives you independent scaling (add query nodes for read load, index nodes for build throughput) and a wide menu of index types, including flat, IVF variants, HNSW, DiskANN and GPU-accelerated indexes. Smaller deployment modes exist, from an embedded library for prototypes to a single-node server, which let you start small with the same client API.
The cost is operational weight. A full cluster has several stateful dependencies, upgrade procedures and failure domains to understand. It earns its keep when you have hundreds of millions of vectors, heavy concurrent load, or need to scale ingestion and querying independently. For a few million vectors it is more machinery than the problem needs.
6. Filtered search and multi-tenancy: where benchmarks stop being honest
Most published vector benchmarks run unfiltered queries. Production queries almost never are: restrict to this tenant, this language, documents the caller may read, items newer than a date. Filtering interacts with approximate indexes in three ways, and the failure mode depends on which one your engine uses.
- Post-filtering: search the index for the top K, then drop results that fail the filter. It is cheap and fast, and it silently returns fewer than K results (sometimes none) when the filter is selective. A tenant holding 0.1% of the data will often get an empty answer.
- Pre-filtering with a scan: compute the matching set first, then brute-force it. Results are exact and complete, and the cost scales with the matching set, so it is excellent for small tenants and slow for large filters.
- In-graph filtering: evaluate the filter while traversing the graph, skipping non-matching nodes. This keeps results full and fast, but a very selective filter can disconnect the traversable subgraph, which is why engines add extra links built around indexed payload fields or switch strategies by estimated selectivity.
Each system handles this differently. Postgres lets the planner choose between the vector index and a b-tree, and recent pgvector releases add iterative index scans that keep walking the graph until enough rows survive the filter. Qdrant plans queries using payload index cardinality estimates and builds filter-aware links. Milvus supports filter expressions on scalar fields with its own strategy choices per index type. The practical consequence is the same everywhere: test with your actual filter distribution, including the smallest and largest tenant.
Multi-tenancy patterns
There are three common layouts. One shared collection with a tenant field is simplest and efficient when tenants are many and small, provided the tenant field is indexed. One collection per tenant gives hard isolation and trivial deletion, but cost grows with tenant count since each has its own indexes and overhead. Partitioning or sharding by tenant sits in between and is useful when a handful of very large tenants coexist with a long tail. Pick based on your largest tenant and your tenant count, not on the average.
7. Side-by-side comparison and a decision checklist
The table below compares design properties, not speed. It is deliberately qualitative because performance depends on the workload; treat the entries as a map of where to look, and confirm details against current documentation for the versions you intend to run.
| Property | pgvector | Qdrant | Milvus |
|---|---|---|---|
| Shape | Extension inside PostgreSQL | Dedicated vector engine, single binary or cluster | Distributed system with separate roles; lighter modes available |
| Main indexes | HNSW, IVFFlat | HNSW with payload-aware links | Flat, IVF family, HNSW, DiskANN, GPU indexes |
| Quantization | Half-precision and binary types, plus expression-index tricks | Scalar, product, binary, with rescoring | Several, tied to the chosen index type |
| Filtering | SQL planner; iterative scans in recent releases | Payload indexes with filter-aware traversal | Scalar field expressions with per-index strategies |
| Transactions with other data | Full ACID with your tables | Per-point operations, no cross-system transaction | Per-collection operations, no cross-system transaction |
| Scale-out | Replicas, partitioning, external tooling | Built-in sharding and replication | Built-in, roles scale independently |
| Operational weight | Lowest if you already run Postgres | Moderate | Highest in full cluster mode |
| Natural fit | Up to low tens of millions of vectors beside relational data | Filter-heavy retrieval, tight RAM budgets | Very large or write-heavy corpora needing independent scaling |
Decision checklist
- Compute raw vector bytes and decide the RAM budget. If it fits on one machine with quantization, a single node is likely enough.
- Do you need transactional consistency with relational data (deletes, permissions, joins)? Lean toward pgvector.
- Are queries filtered, and is any filter highly selective? Test that case first; it breaks more deployments than raw speed does.
- Do you need independent scaling of ingestion and search, or more data than one machine holds on SSD? Look at Milvus or a Qdrant cluster.
- How much operational complexity can your team carry? A system you cannot debug at 3 a.m. is slower than any benchmark suggests.
- How often does the embedding model change? Re-embedding millions of vectors is a migration; plan for dual indexes and a cutover.
8. Measuring recall and latency on your own data
A latency number without a recall number is meaningless, because you can make any index fast by making it sloppy. The honest procedure is to build ground truth with exact search, then sweep the speed knobs and record both recall and tail latency.
import time
import numpy as np
def recall_at_k(approx_ids, exact_ids, k=10):
"""Fraction of the true top-k neighbours that the ANN query returned."""
return len(set(approx_ids[:k]) & set(exact_ids[:k])) / k
def exact_top_k(corpus, query, k=10):
# corpus: (n, d) float32 normalised; cosine == dot product
scores = corpus @ query
top = np.argpartition(-scores, k)[:k] # k best, unordered
return top[np.argsort(-scores[top])] # ordered best-first
def evaluate(search_fn, corpus, queries, k=10):
recalls, latencies = [], []
for q in queries:
truth = exact_top_k(corpus, q, k)
t0 = time.perf_counter()
got = search_fn(q, k) # your client call returning ids
latencies.append((time.perf_counter() - t0) * 1000)
recalls.append(recall_at_k(got, truth, k))
return {
"recall@k": float(np.mean(recalls)),
"p50_ms": float(np.percentile(latencies, 50)),
"p99_ms": float(np.percentile(latencies, 99)),
}
# Sweep the knob (ef_search / hnsw_ef / nprobe) and keep the cheapest
# setting that still meets your recall target, e.g. recall@10 >= 0.95.
Common mistakes
- Benchmarking with random vectors. Real embeddings cluster; random data has different geometry and flatters or punishes indexes unrealistically.
- Testing on a warm cache with one client. Production has concurrent clients, cold segments after restarts and background indexing competing for CPU.
- Ignoring the write path. Measure ingestion while querying, and measure what happens after bulk deletes.
- Comparing at different recall. A system at 0.90 recall will look faster than one at 0.99. Fix the recall target first.
- Forgetting the embedding step. Embedding the query often costs more wall-clock time than the vector search itself.
9. What to do Monday, and a short FAQ
- Write down corpus size, dimensions, growth rate, tenant count, largest tenant and the filters your queries really use.
- Build a few hundred real queries with exact ground truth from your actual embeddings.
- Stand up the simplest candidate (usually pgvector if you run Postgres) and measure recall, p99 latency and memory.
- Test the nastiest filter: the smallest tenant and the largest tenant, concurrently with ingestion.
- Move to a dedicated engine only when a measured limit, not a hunch, says so.
Do I need a vector database at all? Below roughly a hundred thousand vectors, exact search in memory is often fast enough and removes every tuning question. Is higher recall always better? No, retrieval feeds a downstream model or ranker, and beyond a point extra recall buys nothing visible; pick the target from end-to-end answer quality. Should I use hybrid search? If users search for exact identifiers, names or codes, combining keyword and vector scores usually beats either alone, and all three systems can participate in such a setup. Can I switch later? Yes, if you keep the source text and embedding model version alongside the vectors, because rebuilding an index is then a batch job instead of an archaeology project.