Abdul MoizFractional CTO · Senior EngineerBook a free call

AI systems

IVFFlat vs HNSW in pgvector: The Difference That Finally Made It Click for Me

IVFFlat partitions the vector space; HNSW navigates a layered graph. Getting the two mental models confused is how a production query ended up at ef_search = 600 and a 4,900 ms latency cliff.

Updated · 6 min read

Fractional CTO · Senior Engineer

Key takeaways

  • Start with HNSW for most pgvector workloads. It gives better recall at low latency and copes well with changing data, as long as the index fits in memory.
  • Choose IVFFlat when memory or index build time is the limit and the data changes rarely.
  • Whichever you pick, measure recall against an exact scan before trusting it.

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 vs HNSW at a glance
IVFFlatHNSW
How it worksGroups vectors into lists (clusters)Links vectors in a layered graph
Query settingivfflat.probes (default 1)hnsw.ef_search (default 40)
Build settingslistsm = 16, ef_construction = 64 by default
Build on an empty table?Not usefully, it needs data to find clustersYes, there is no training step
Memory and build timeLowerHigher
Best forStable data, tight memoryHigh recall and low latency

What a pgvector index solves

Suppose you have a million product embeddings. Without an index, PostgreSQL does an exact search:

sql
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).

sql
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_search value should always be greater than or equal to the LIMIT in 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

sql
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:

sql
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:

sql
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 lists to rows / 1000 up to a million rows, and to the square root of the row count above that.
  • Set probes to about the square root of lists, then tune.

HNSW

  • Keep m = 16 and ef_construction = 64 until a measurement says otherwise.
  • Raise maintenance_work_mem before building. Builds slow down sharply once the graph no longer fits.
  • Start at the default ef_search of 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:

sql
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.

Common questions

Is HNSW always faster than IVFFlat?

No. HNSW usually gives a better balance of speed and recall, but it uses more memory. If the part of the graph a query touches does not fit in memory, PostgreSQL reads it from disk and latency can jump from milliseconds to seconds.

What should I set hnsw.ef_search to?

The default is 40. Raise it in steps, such as 80, 100 and 150, and measure recall and P95 latency at each one. Stop when extra recall is no longer worth the extra time. Without iterative scans, keep it at least as high as your LIMIT.

Why does my pgvector query return fewer rows than LIMIT?

Approximate indexes apply filters after the index scan, and HNSW only tracks ef_search candidates. Raise ef_search, or on pgvector 0.8.0 and later turn on iterative index scans so it keeps searching until enough rows match.

How many lists should an IVFFlat index have?

The pgvector documentation suggests starting with rows / 1000 for up to one million rows and the square root of the row count above that, then setting probes to about the square root of lists.

Sources and further reading

Abdul MoizFractional CTOSenior Engineer

About the author

I build production-grade AI applications, AI agents and data systems, fix AI-built apps, and help teams as a fractional CTO. I've spent seven years building software people rely on, including a media platform that grew to 2M+ users.

ShareXLinkedIn

Keep reading

Working on something like this?

Tell me about it on a free 30-minute call.