Sub topic 17
Index build time, memory, and maintenance
This chapter assumes you can already create HNSW and IVFFlat indexes and tune hnsw.ef_search and ivfflat.probes. It covers the operational side: what an index build costs, which settings control it, and how to keep an index healthy as data changes.
Why build cost matters
A vector index is far more expensive to build than a B-tree. HNSW computes distances between each new vector and many candidate neighbors. IVFFlat runs k-means clustering over a sample of the data and then assigns every row to a list. Both cost more as the table grows and as the dimension count rises.
| Aspect | HNSW | IVFFlat |
|---|---|---|
| Build time | Slower | Faster |
| Index size | Larger | Smaller |
| Needs data before build | No | Yes, because lists are computed from existing rows |
| Memory pressure during build | The graph should fit in `maintenance_work_mem` | The sample and centroids must fit |
| Behavior after many changes | Stays usable, but deletes leave dead entries | Recall can drift as the data changes |
Memory settings that control the build
maintenance_work_mem is the main knob. Its default is 64MB, which is too small for most vector indexes. For HNSW, the build is fastest while the in-progress graph fits in this memory. When it no longer fits, pgvector emits a notice like hnsw graph no longer fits into maintenance_work_mem after N tuples. The build still finishes, but it slows down sharply.
Parallel workers shorten the build. max_parallel_maintenance_workers sets how many workers one CREATE INDEX can use. The workers come out of the pool limited by max_parallel_workers, which max_worker_processes also caps.
SET maintenance_work_mem = '2GB';
SET max_parallel_maintenance_workers = 7;
CREATE INDEX items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);Both settings apply to the current session, so you can raise them for one build without changing the server. Keep maintenance_work_mem below the free RAM on the machine. Each parallel worker may use memory too, so check total usage if you use many workers.
Build-time parameters and their cost
Higher m and ef_construction give a better graph and better recall, but they lengthen the build and enlarge the index. Doubling ef_construction roughly increases build work, so raise it only if measured recall at your ef_search is too low. You can't change either value on an existing index. Changing them means building a new index.
For IVFFlat, lists sets the number of clusters. A common starting point is rows / 1000 for tables up to about one million rows, and sqrt(rows) above that. More lists mean faster queries at a given probe count but a longer build and more required probes for good recall.
Build IVFFlat only after the table holds representative data. If you create the index on an empty or tiny table, the centroids are poor and recall suffers. The usual remedy is to load the data first and create the index afterward.
Watching a build in progress
PostgreSQL reports index build progress in pg_stat_progress_create_index. Run this from a second session while the build runs.
SELECT
pid,
phase,
round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS pct_blocks,
tuples_done,
tuples_total
FROM pg_stat_progress_create_index;The phase column shows which stage is running, such as scanning the table or building the index. Percentages can stay at zero for a while in some phases, so judge progress by phase and tuples_done as well.
Checking index size
Index size tells you how much memory you need to keep the index cached. Compare it with the table and with the RAM available for caching.
SELECT
pg_size_pretty(pg_relation_size('items')) AS table_size,
pg_size_pretty(pg_relation_size('items_embedding_hnsw')) AS hnsw_size;Query speed is best when the index pages stay in shared_buffers or the operating system cache. If the index is much larger than available memory, every query reads from disk and latency rises. You can load an index into the cache after a restart with the pg_prewarm extension.
CREATE EXTENSION IF NOT EXISTS pg_prewarm;
SELECT pg_prewarm('items_embedding_hnsw');Building without blocking writes
A plain CREATE INDEX takes a lock that blocks inserts, updates, and deletes on the table until the build ends. On a large table that can last hours. Use CONCURRENTLY on a live system.
CREATE INDEX CONCURRENTLY items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);Concurrent builds take longer because they scan the table more than once, and they can't run inside a transaction block. If one fails, it can leave an invalid index behind. Find it with \d items in psql or by checking pg_index.indisvalid, then drop it and retry.
Maintaining an index over time
The two index types age differently.
HNSW
New rows are inserted into the graph as they arrive, so the index stays usable without rebuilds. Inserts are slower than into a B-tree, because each one searches the graph. Deleted and updated rows leave dead entries that VACUUM has to clean up. Vacuuming an HNSW index can be slow. A workaround that pgvector's documentation suggests is to reindex first, so the dead entries are gone, and then vacuum.
REINDEX INDEX CONCURRENTLY items_embedding_hnsw;
VACUUM items;IVFFlat
New rows are assigned to the nearest existing centroid, but the centroids never move. If the data you add differs from the data you built on, for example after switching embedding models or after a large shift in content, some lists become oversized and recall drops. Rebuild the index when the data distribution changes noticeably.
REINDEX INDEX CONCURRENTLY items_embedding_ivfflat;A maintenance routine
A reasonable routine looks like this:
- After a bulk load, create the index (IVFFlat only after the load) with raised
maintenance_work_memand parallel workers. - Record the index size and the recall measured against exact search, as described in the recall chapter.
- After large changes to the data, measure recall again. If it has fallen, reindex.
- Reindex with
CONCURRENTLYon live tables, and check for invalid leftover indexes.
Common mistakes
- Leaving
maintenance_work_memat the default and then wondering why an HNSW build takes hours. - Creating an IVFFlat index on an empty table during setup and never rebuilding it.
- Running a plain
CREATE INDEXon a production table and blocking writes. - Changing
morlistsand expecting the existing index to change. These are fixed at build time. - Ignoring the notice about the graph no longer fitting in memory.
Exercise
You loaded 5 million rows into a table and built an HNSW index with the default settings. The build took far longer than expected and the server log shows "hnsw graph no longer fits into maintenanceworkmem". What do you change, and how do you build the index again without blocking writes on a live table?
Show answer
Raise maintenance_work_mem (and max_parallel_maintenance_workers if CPU is free) for the session so the graph fits in memory, then rebuild with CREATE INDEX CONCURRENTLY or REINDEX INDEX CONCURRENTLY. For example: SET maintenance_work_mem = '4GB'; SET max_parallel_maintenance_workers = 7; followed by REINDEX INDEX CONCURRENTLY items_embedding_hnsw;. Choose a value that leaves enough free RAM to avoid swapping.
Exercise
Six months after building an IVFFlat index, recall measured against exact search has dropped, and the team has added a large batch of documents on a new topic. Why did recall drop, and what is the fix?
Show answer
IVFFlat centroids are computed once at build time and never move. The new documents are assigned to existing centroids that don't represent them well, so some lists become oversized and the right neighbors are missed when only a few lists are probed. Rebuild the index with REINDEX INDEX CONCURRENTLY so the centroids are recomputed from the current data. Raising ivfflat.probes can recover recall temporarily at the cost of speed.