When you add vector search to PostgreSQL with pgvector, one of the first decisions is which approximate nearest-neighbor index to use: IVFFlat or HNSW. Both avoid comparing a query embedding against every row, and they work in completely different ways.
IVFFlat clicked for me quickly because it maps onto K-Means clustering. HNSW took much longer because it is a graph structure, and I kept trying to understand it with the clustering model I had already built for IVFFlat.
That confusion turned expensive when a production search issue produced this:
- ef_search 150
- About 7 ms per query
- ef_search 300
- About 21 ms per query
- ef_search 600
- About 4,900 ms per query
Doubling ef_search from 300 to 600 did not double latency. It created a cliff.
| IVFFlat | HNSW | |
|---|---|---|
| How it works | Groups vectors into lists (clusters) | Links vectors in a layered graph |
| Query setting | ivfflat.probes (default 1) | hnsw.ef_search (default 40) |
| Build settings | lists | m = 16, ef_construction = 64 by default |
| Build on an empty table? | Not usefully, it needs data to find clusters | Yes, there is no training step |
| Memory and build time | Lower | Higher |
| Best for | Stable data, tight memory | High recall and low latency |
What a pgvector index solves
Suppose you have a million product embeddings. Without an index, PostgreSQL does an exact search:
SELECT id, title
FROM products
ORDER BY embedding <=> $1
LIMIT 10;Accurate, but it computes the distance to every vector before sorting. Approximate indexes search only a slice instead, trading slight recall accuracy for speed.
IVFFlat: partition the space
IVFFlat divides the vector space into groups called lists (clusters).
CREATE INDEX products_embedding_ivfflat_idx
ON products
USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 1000);A million vectors across 1,000 lists is roughly 1,000 vectors per list. When a query arrives, PostgreSQL finds the closest lists, and ivfflat.probes decides how many to actually search. probes = 1 searches only the closest list (fast, low recall). probes = 100 searches much more (slower, higher recall).
Mental model: divide vectors into neighborhoods, then choose how many neighborhoods to open.
HNSW: navigate a graph
HNSW does not cluster. It builds a hierarchical graph where each node is a stored vector, and edges are permanent physical wires connecting it to neighbors.
- Top layer
- A, M, Z: a few points, long jumps across the data
- Middle layer
- A, F, M, R, Z: more points, shorter jumps
- Bottom layer
- A, B, C, D, E … every point, short local steps
It works like navigating a city — motorways, then major roads, then local streets. You enter at an upper layer, skip across the graph rapidly, descend into the dense bottom layer, and return the closest results.
What ef_search actually means
This parameter causes the most confusion. hnsw.ef_search = 600 does not mean "visit exactly 600 nodes."
Think of ef_search as the algorithm carrying a clipboard with exactly 600 blank lines.
As a query navigates the graph, it writes down the closest vectors it encounters. Once the 600 lines are full, it uses a strict "one-in, one-out" rolling replacement. If it finds a new node closer to the query than the worst node on the clipboard, it erases the worst one and writes the new one down.
It stops when it hits a dead end. A larger ef_search gives the algorithm massive memory to explore competing candidates, yielding higher recall but substantially more work.
The golden rule of pgvector
Because HNSW only tracks candidates on this clipboard, your SQL LIMIT and ef_search are inextricably linked.
When HNSW hits its dead end, it hands the clipboard to PostgreSQL. If your query asks for LIMIT 100 but your ef_search clipboard only has 40 slots, PostgreSQL can only return 40 results.
The golden rule: without iterative scans, your
ef_searchvalue should always be greater than or equal to theLIMITin your SQL query.
The latency cliff: memory vs. disk I/O
Why did our ef_search jump from 21 ms to 4,900 ms? The answer is disk thrashing.
Traversing an HNSW graph requires random memory access. If your active graph footprint fits in RAM (shared_buffers or the OS page cache), these hops take nanoseconds.
Increasing ef_search forces the algorithm to explore a larger footprint. If that expanded radius exceeds cached memory, PostgreSQL suffers a cache miss and must fetch the index page from disk. Random disk reads — even on NVMe — take milliseconds, roughly 1,000 to 10,000 times slower than RAM.
Going from 300 to 600 pushed the working set out of memory, turning a fast CPU traversal into an I/O-bound nightmare. HNSW latency is ultimately bounded by your cache hit rate.
The two build parameters
CREATE INDEX products_embedding_hnsw_idx
ON products
USING hnsw (embedding vector_cosine_ops)
WITH (
m = 16,
ef_construction = 64
);m is the permanent physical wires on disk (max edges per node).
ef_construction is the clipboard used only when building. When inserting a node, it uses a clipboard of 64 slots to explore. Once it finds the absolute best 64 candidates, it picks the top 16, wires itself permanently (m = 16), and throws the clipboard away. Higher means slower builds but better graph routing.
IVFFlat vs HNSW: which should you use?
You'll see heuristics like "IVFFlat below 30,000 vectors, HNSW above 50,000." These refer to the point where brute-force exact search becomes too slow, making an index necessary.
The real question is: at what row count does my setup stop meeting targets on my infrastructure?
IVFFlat suits constrained memory and stable datasets. HNSW suits substantial growth and tight latency with high recall, provided you have the RAM to keep the index cached.
Benchmark recall, don't guess it
Compare configurations against a forced exact scan:
SET LOCAL enable_indexscan = off;
SELECT id
FROM products
ORDER BY embedding <=> $1
LIMIT 10;Run the same query with SET LOCAL hnsw.ef_search = 100; and count the overlap. Then compare:
- ef_search 40
- P95 latency 8 ms · recall@10 86%
- ef_search 80
- P95 latency 12 ms · recall@10 92%
- ef_search 150
- P95 latency 18 ms · recall@10 96%
- ef_search 300
- P95 latency 30 ms · recall@10 98%
- ef_search 600
- P95 latency 4,900 ms · recall@10 99%
If pushing from 300 to 600 buys 1% recall for a 5-second penalty, it isn't worth it.
Filters, missing rows and iterative scans
Add a WHERE clause and a new problem appears. With an approximate index, the filter runs after the index scan. If a condition matches 10% of rows and ef_search is 40, only about 4 rows survive.
Since pgvector 0.8.0 you can ask it to keep scanning until it has enough:
SET hnsw.iterative_scan = strict_order;This matters most where filters are not optional, such as permission checks inside a RAG system. A query that silently returns fewer rows looks like a model that "did not know".
Sensible starting settings
IVFFlat
- Load the data first. The index learns its clusters from the rows that exist.
- Set
liststo rows / 1000 up to a million rows, and to the square root of the row count above that. - Set
probesto about the square root oflists, then tune.
HNSW
- Keep
m = 16andef_construction = 64until a measurement says otherwise. - Raise
maintenance_work_membefore building. Builds slow down sharply once the graph no longer fits. - Start at the default
ef_searchof 40 and raise it in steps.
How to check that your HNSW index fits in memory
Compare the size of the index with the memory available to cache it:
SELECT pg_size_pretty(pg_relation_size('products_embedding_hnsw_idx'));
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM products
ORDER BY embedding <=> $1
LIMIT 10;In the BUFFERS line, hit means the page was already in PostgreSQL's cache and read means it was not. If read climbs as you raise ef_search, you are walking toward the same cliff.