Sub topic 7
maintenance_work_mem for VACUUM, CREATE INDEX, and autovacuum
This chapter covers the memory setting that maintenance commands use, and how it differs from work_mem. It assumes you can run queries in psql, edit postgresql.conf, and tell a reload from a restart. It also assumes you know that work_mem limits a single sort or hash node in a query. Everything below applies to PostgreSQL 14 and later unless a version is named.
What the setting controls
maintenance_work_mem is the memory limit for maintenance operations. These are the commands that build or clean up data structures, not the ones that answer ordinary queries. The main users are:
VACUUM, which stores the list of dead row versions it still has to remove from indexes.CREATE INDEX, which sorts the key values before writing the index.REINDEX, which does the same work asCREATE INDEXfor an existing index.ALTER TABLE ... ADD FOREIGN KEY, which uses the memory to validate existing rows.CLUSTERandVACUUM FULL, which sort or rewrite whole tables. In some versions they take their sort memory frommaintenance_work_mem.
The default is 64MB. Regular queries use work_mem (default 4MB). Maintenance commands run far less often than queries, so a much larger limit is safe for them.
The value is a ceiling for each operation, not a reservation. Memory is allocated as the command needs it. A VACUUM on a small table uses little memory even when the setting is 2GB.
VACUUM and the dead-tuple list
VACUUM first scans the table heap and collects the identifiers (tuple IDs) of dead rows. It then scans every index and removes the entries that point to those rows. Finally it goes back to the heap and frees the space.
The list of tuple IDs must fit in memory. Before PostgreSQL 17, the list was a flat array that could hold at most 1GB, whatever maintenance_work_mem said. Each entry took 6 bytes, so the array held roughly 179 million dead tuples. If the list filled up, VACUUM had to stop collecting, run a full pass over all indexes, clear the list, and resume the heap scan. A table with many indexes and many dead rows could therefore have its indexes scanned several times in one run.
PostgreSQL 17 replaced the array with a more compact radix-tree structure, and it no longer has the 1GB cap. It uses memory more efficiently, but the principle holds: a larger limit means fewer index passes on big tables with heavy churn.
You can see the number of index passes in VACUUM VERBOSE output and in the pg_stat_progress_vacuum view.
SELECT pid,
relid::regclass AS table_name,
phase,
heap_blks_total,
heap_blks_scanned,
index_vacuum_count
FROM pg_stat_progress_vacuum;The column index_vacuum_count shows how many complete index-vacuum cycles have finished. A value above 1 on a long run means the dead-tuple list filled up at least once. In PostgreSQL 17 and later, the view also reports max_dead_tuple_bytes and dead_tuple_bytes, which show how full the list is.
CREATE INDEX and REINDEX
An index build sorts all key values. With enough memory the sort happens in RAM. With too little, PostgreSQL spills to temporary files and merges them, which is much slower on large tables.
The effect is easy to measure. Set a session-level value, time the build, and compare.
CREATE TABLE index_demo AS
SELECT g AS id, md5(g::text) AS payload
FROM generate_series(1, 2000000) AS g;
SET maintenance_work_mem = '16MB';
\timing on
CREATE INDEX index_demo_payload_small ON index_demo (payload);
SET maintenance_work_mem = '512MB';
CREATE INDEX index_demo_payload_large ON index_demo (payload);
DROP TABLE index_demo;On most hardware the second build is clearly faster. The exact gain depends on the table size, the key width, and the storage. If you see no gain, the sort already fit in 16MB or the build is limited by disk writes.
Building the index also benefits from parallel workers. max_parallel_maintenance_workers (default 2) sets how many extra workers a single CREATE INDEX may use for B-tree builds.
Parallel builds multiply the memory
For a parallel index build, the memory limit is shared among the leader and its workers. Each participant gets a portion, so the total stays near maintenance_work_mem. That makes the parallel case easier to budget than parallel queries, where each worker can use its own work_mem per node. Check your version's documentation if you depend on this, since details vary between index types.
autovacuum_work_mem
Autovacuum workers are background processes that run VACUUM and ANALYZE for you. By default each one uses maintenance_work_mem. The default for autovacuum_work_mem is -1, which means "use maintenance_work_mem".
The number of workers is set by autovacuum_max_workers (default 3). All of them can run at the same moment. This creates a problem if you raise maintenance_work_mem globally:
- Worst case from autovacuum alone is
autovacuum_max_workers × maintenance_work_mem. - A manual
VACUUMorCREATE INDEXruns on top of that.
For example, a global value of 2GB with 3 workers allows 6GB for autovacuum, plus 2GB for a manual index build running at the same time.
The usual fix is to set the two limits separately. Keep the global maintenance_work_mem large enough for your administrators' manual work, and cap the autovacuum workers with their own value.
ALTER SYSTEM SET maintenance_work_mem = '1GB';
ALTER SYSTEM SET autovacuum_work_mem = '256MB';
SELECT pg_reload_conf();
SELECT name, setting, unit, context
FROM pg_settings
WHERE name IN ('maintenance_work_mem', 'autovacuum_work_mem',
'autovacuum_max_workers');Both memory settings have the context user or sighup, so a reload is enough. Changing autovacuum_max_workers needs a restart, because the worker slots are set up at server start. The context column in pg_settings tells you which case applies.
How much is enough?
More memory helps only until the work fits. Past that point extra memory does nothing, and for VACUUM it can even hold back the OS page cache that the server relies on.
Use these rules as starting points.
| Situation | Starting value |
|---|---|
| Small server, under 8GB RAM | 128MB to 256MB |
| General-purpose server, 16 to 64GB RAM | 512MB to 1GB |
| Large tables with many dead rows or big index builds | 1GB to 2GB, set per session |
| Autovacuum workers | 128MB to 512MB with `autovacuum_work_mem` |
For a one-time heavy job such as restoring a dump, set a high value for that session only and leave the server default alone.
BEGIN;
SET LOCAL maintenance_work_mem = '2GB';
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_created_at_idx
ON orders (created_at);
COMMIT;This example would fail, and the failure shows a real rule. CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Use a plain SET instead, which lasts for the session.
SET maintenance_work_mem = '2GB';
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_created_at_idx
ON orders (created_at);
RESET maintenance_work_mem;You can also attach the value to a role used for maintenance jobs, in the same way you would raise work_mem for a reporting role.
ALTER ROLE dba_maintenance SET maintenance_work_mem = '1GB';Where the memory sits in the budget
The chapter on connection budgeting adds all the pieces together. For now, note the maintenance part of that sum:
SELECT 3 * (256 * 1024 * 1024) AS autovacuum_worst_case_bytes,
1 * (2048::bigint * 1024 * 1024) AS manual_job_bytes;Autovacuum workers, a manual VACUUM, and index builds can all run at once. Add them to the shared memory and the per-query memory, and leave headroom for the OS page cache.
Common mistakes
- Using
work_memto speed up an index build. It has no effect onCREATE INDEX. Usemaintenance_work_mem. - Setting a huge global value and forgetting autovacuum. Each worker can claim the full amount.
- Expecting more memory to make
VACUUMfaster on every table. If the dead-tuple list already fits, extra memory changes nothing. The cost is then the scan itself. - Checking only the server default. A role or database may override the value. Query
pg_db_role_settingor useSHOWinside the affected session. - Running
CREATE INDEX CONCURRENTLYinside a transaction. It is rejected. Set the value at session level instead.
Summary of the decision
- Leave the default for small databases.
- If index builds are slow or
VACUUMreports several index scans, raisemaintenance_work_memfor one session and measure. - Once a higher value is proven useful, set it globally, and cap autovacuum with
autovacuum_work_mem. - Include both values in your worst-case memory budget.
Exercise
Your server has 32GB of RAM, autovacuum_max_workers = 3, and maintenance_work_mem = 4GB. autovacuum_work_mem is -1. What is the largest amount of memory autovacuum alone can use for its dead-tuple lists, and what single change reduces that without slowing down your manual index builds?
Show answer
Autovacuum alone can use up to 3 × 4GB = 12GB. Set autovacuum_work_mem to a smaller value such as 512MB, which limits autovacuum workers to 3 × 512MB = 1.5GB. The global maintenance_work_mem stays at 4GB, so manual CREATE INDEX and VACUUM commands still get the larger limit. A reload is enough to apply it.
Exercise
A VACUUM VERBOSE on a large table with many indexes reports "index scans: 4". What does this tell you, and what would you test?
Show answer
The dead-tuple list filled up and was emptied four times during the run, so every index was scanned four times. Test a higher maintenance_work_mem (or autovacuum_work_mem if autovacuum ran it) for one session, and run VACUUM VERBOSE again. If the index scan count drops and the run time falls, keep the higher value. On PostgreSQL 16 and earlier, remember the list is capped at 1GB, so raising the setting past 1GB gives no more benefit.