7 min read

Why a pgvector HNSW Index Build Is Slow, and the Fix

A slow pgvector HNSW build usually means the graph no longer fits in maintenance_work_mem. How to read the notice, size the memory and add parallel workers.

By Cogniq Labs ResearchEvidence policy

RetrievalAgents in Production
Isometric illustration of a growing network of connected nodes filling a container, with the outer nodes spilling past its edge onto a slower surface.

A pgvector HNSW index on a few thousand rows builds in seconds. On millions of rows it can take hours, and sometimes it fails outright. The most common cause of a slow build is that the HNSW graph no longer fits in maintenance_work_mem. Raise it so the graph fits, add parallel workers, and build after loading the data. If the build fails instead of crawling, the cause is usually the other end of the same setting: too much memory, or a container without enough shared memory.

This note explains how to tell which one you have and what to change.

The notice that tells you

When a build outgrows its memory, Postgres says so. pgvector's documentation shows the message:

NOTICE:  hnsw graph no longer fits into maintenance_work_mem after 100000 tuples
DETAIL:  Building will take significantly more time.
HINT:  Increase maintenance_work_mem to speed up builds.

If you see it, you have found your problem. The README states the rule behind it plainly: indexes build significantly faster when the graph fits into maintenance_work_mem. Once the graph spills out of memory, the build is no longer working on one structure in RAM, and it slows down sharply.

If you built the index from a client that hides notices, run it in psql, or check the server log.

Fix 1: give the build enough memory

Set it for the session that runs the build:

SET maintenance_work_mem = '8GB';
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);

The README uses 8GB as its example. The right number depends on your data. As an estimate, the vectors alone take rows times dimensions times 4 bytes at 32-bit precision, and the graph adds links on top of that. The following is illustrative arithmetic and ignores overheads:

Rows Dimensions Vector data alone
100,000 768 about 0.3 GB
1,000,000 768 about 3 GB
1,000,000 1,536 about 6 GB
5,000,000 1,536 about 31 GB

So a million 768-dimension vectors need a few gigabytes before the graph is counted, and the default maintenance_work_mem of a typical Postgres install is far below that. That gap is why a build that was fine on a test table crawls on the real one.

Two cautions from the README. First: "Do not set maintenance_work_mem so high that it exhausts the memory on the server." A value larger than the free RAM makes the operating system swap or kill the process, and that turns a slow build into a failed one. Second, set it for the building session only, not globally, because other maintenance operations will use the same setting.

Fix 2: use parallel workers

The README says you can also speed up index creation by increasing the number of parallel workers, which is 2 by default:

SET max_parallel_maintenance_workers = 7; -- plus leader

For a large number of workers, it adds, you may need to increase max_parallel_workers, which is 8 by default. Choose a number that matches your CPU cores, leaving some for the rest of the database, since a build that takes every core will slow down anything else running.

Fix 3: build after loading

The README states that, like other index types, it is faster to create an index after loading your initial data. Loading a table that already has an HNSW index means maintaining the graph for every insert, one row at a time. Loading first and building once is much quicker for an initial import. For a table that is already live, you cannot avoid maintaining the index, but you can build a new one concurrently:

CREATE INDEX CONCURRENTLY ON items USING hnsw (embedding vector_cosine_ops);

A concurrent build takes longer and does more work, but it does not block writes to the table.

Fix 4: check your index options

The README says the index options have a significant impact on build time, and recommends the defaults unless you see low recall. The two options for HNSW are:

Option Meaning Default
m The maximum number of connections per layer 16
ef_construction The size of the dynamic candidate list used when building the graph 64

A higher ef_construction gives better recall at the cost of build time and insert speed. If someone raised it to 200 or 400 for a better recall, that is a likely reason a build is slow. Measure whether it was necessary. The method is in why pgvector returns fewer rows when you add a filter, and the larger question of whether you need an approximate index at all is in you may not need a vector database.

For very large collections, the README also suggests binary quantization for faster build times at scale, which stores a compact form of each vector and trades some precision for speed.

When it fails instead of getting slow

The server runs out of memory

The opposite problem. If maintenance_work_mem is higher than the memory actually free, the build can be killed. Lower the value, or run the build on a machine with more RAM.

"Could not resize shared memory segment" (Docker)

A parallel build uses shared memory, and containers often give Postgres very little by default. Docker's default /dev/shm is 64 MB, and the error commonly reported for parallel HNSW builds in containers looks like could not resize shared memory segment ... No space left on device. Two fixes are widely used. Give the container more shared memory, with --shm-size on docker run or shm_size in Docker Compose, or set max_parallel_maintenance_workers = 0 to avoid the shared segment, at the cost of a single-threaded and much slower build. These come from community reports, not from the pgvector documentation, so check which applies to your setup.

Managed databases

On a hosted service you often cannot change shared memory, so the practical options are a lower maintenance_work_mem or fewer parallel workers. Some managed services also cap the setting. Check your provider's limits before assuming a number from a blog post will work.

The statement times out

A long build can hit a statement timeout set on the role or the database. Check SHOW statement_timeout; and, for the build session only, set it to 0 to disable it. Remember to do this in the same session as the CREATE INDEX.

If HNSW is too slow, consider IVFFlat

HNSW is not the only approximate index. The README says an IVFFlat index has faster build times and uses less memory than HNSW, but has lower query performance in terms of the speed and recall trade-off. For a very large table where build time or memory is the real constraint, it can be the practical choice. The README gives three keys to good recall with it: create the index after the table has some data, choose a sensible number of lists, and set an appropriate number of probes at query time.

The trade is the one we describe in you may not need a vector database: faster to build and smaller, but you tune it more, and queries are less accurate for the same speed. Test both on your own queries before switching, since the right answer depends on your data and your latency budget.

Plan for rebuilds

An index build is not a one-off. You will rebuild when you change the embedding model, because vectors from different models are not comparable and the whole table has to be re-embedded and re-indexed. Treat the build time you measure now as a recurring cost. Write down the settings that worked, the memory you needed and how long it took, and keep the build as a script. A change of model, a new dimension count or a change of distance function all mean a new index, and doing it under pressure with settings you have forgotten is how a one-hour job becomes an afternoon.

Watch the build

pgvector's README points to PostgreSQL's progress reporting, and gives a query to run from another session:

SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%"
FROM pg_stat_progress_create_index;

The phases for HNSW are initializing and loading tuples. Watching the percentage over a few minutes tells you whether the build is progressing, how fast, and roughly how long is left. If it stalls at the same figure, look at the memory notice and the server log.

A checklist

  1. Run the build in psql and look for the "no longer fits" notice.
  2. Work out the size of your vectors, and set maintenance_work_mem above it, below your free RAM.
  3. Raise max_parallel_maintenance_workers, and max_parallel_workers if needed.
  4. Load the data first, then build.
  5. Use the default m and ef_construction unless measurement shows low recall.
  6. In Docker, check --shm-size.
  7. Watch pg_stat_progress_create_index.
  8. Disable the statement timeout for the building session only.

Once the index exists, a slow index is not the only way retrieval can go wrong. Filtered queries can quietly return too few rows, which we cover in the linked note above, and recall should be measured, not assumed, as we discuss in how to evaluate an LLM application.

What we do not know

We have not benchmarked these settings, and the memory table is an estimate. Real graph size depends on m, on the vector type and on overheads. Defaults and behaviour change between pgvector releases, so check the README for your version. The Docker and managed-service fixes come from community reports and differ between platforms, so test them on a copy of your data before you rely on them.

Sources

  1. pgvector: open-source vector similarity search for Postgres — GitHub
  2. CREATE INDEX progress reporting — PostgreSQL

Frequently asked questions

Why is my pgvector HNSW index build so slow?

Most often because the graph no longer fits in maintenance_work_mem. Postgres then prints a notice that the hnsw graph no longer fits after 100000 tuples and that building will take significantly more time. Raising maintenance_work_mem so the graph fits is the main fix.

How much maintenance_work_mem does pgvector need?

Enough to hold the whole graph. The vectors themselves take rows times dimensions times 4 bytes at 32-bit precision, and the graph adds links on top, so a rough floor is a little above the size of the vectors. The README warns not to set it so high that it exhausts the server's memory.

How do I speed up a pgvector index build with parallel workers?

Raise max_parallel_maintenance_workers, which defaults to 2 according to the pgvector docs, and if you ask for many workers also raise max_parallel_workers, which defaults to 8. Set them in the session before CREATE INDEX.

Should I create the index before or after loading data?

After. The pgvector README says that, like other index types, it is faster to create an index after loading your initial data than to maintain it row by row while loading.

How can I see how far an index build has got?

Query pg_stat_progress_create_index from another session. The README gives a query that reports the phase and the percentage of blocks done. For HNSW the phases are initializing and loading tuples.

Related reading