Sub topic 5
work_mem: sorts, hashes, and temporary files
This chapter assumes you can run queries in psql, edit and reload postgresql.conf, and read a simple EXPLAIN plan. It covers what work_mem controls, how to spot spills to disk, and how to raise it without risking an out-of-memory failure.
What work_mem controls
work_mem is the amount of memory a single query operation may use before it falls back to temporary files on disk. The default is 4MB. The operations it covers include:
- Sorts for
ORDER BY,DISTINCT, merge joins, and window functions. - Hash tables for hash joins, hash aggregation, and hashed subplans.
- Memoize nodes and some other plan nodes that buffer rows.
The limit applies per operation, not per connection and not per query. A query with three sorts and two hash joins can use up to five times work_mem. Parallel workers each get their own allowance too. A parallel query with four workers and a leader can use the limit in each process.
Unlike shared_buffers, work_mem needs no restart. It can be changed with a reload, per session with SET, per role, per database, or per transaction with SET LOCAL.
Check the current value
The query below reads the settings from earlier chapters. The context column shows whether a change needs a reload or a restart, and pending_restart shows whether a changed value is still waiting for a restart.
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem',
'effective_cache_size', 'max_wal_size', 'checkpoint_timeout',
'random_page_cost', 'max_connections');For work_mem, context is user. Any session can change it for itself. For shared_buffers and max_connections, it is postmaster, which means a restart.
Finding spills with EXPLAIN
Run the suspect query under EXPLAIN (ANALYZE, BUFFERS). Note that ANALYZE executes the query, so wrap data-modifying statements in a transaction you roll back.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY created_at;Look at the sort node:
Sort Method: quicksort Memory: 20480kBmeans the sort fit inwork_mem.Sort Method: external merge Disk: 184320kBmeans it spilled. The disk figure is how much temporary file space the sort used.Buffers: temp read=... written=...on a node confirms temporary file I/O.
For hash nodes, look for Batches. Batches: 1 means the hash table fit in memory. A larger number means the table was split into batches and written to temporary files. Memory Usage tells you how much memory the table used.
A spill is not always a problem. A nightly report that sorts a large table once does not need to run in memory. A query that runs thousands of times per minute and spills each time does.
Finding spills across the whole server
EXPLAIN tells you about one query. To see how often spills happen overall, use the cumulative counters in pg_stat_database.
SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp_size
FROM pg_stat_database
ORDER BY temp_bytes DESC;These counters accumulate since the last statistics reset. Take two readings a few minutes apart and compare them to get a rate. A large total from months ago says little about today.
To find which queries cause spills, log them. Setting log_temp_files = 0 writes a log line for every temporary file, with its size and the statement that created it. On a busy server, a value such as 10MB logs only larger files.
# postgresql.conf
log_checkpoints = on
log_temp_files = 0
max_wal_size = 4GB
checkpoint_timeout = 15min
checkpoint_completion_target = 0.9The checkpoint lines in this block belong to a later chapter on WAL. They are shown here so one configuration covers both logging needs. If you also load pg_stat_statements, its temp_blks_written column ranks statements by temporary file output.
Changing work_mem
ALTER SYSTEM writes the value to postgresql.auto.conf. pg_reload_conf() makes the postmaster re-read its configuration, and new sessions pick up the value.
ALTER SYSTEM SET work_mem = '32MB';
SELECT pg_reload_conf();
SHOW work_mem;Be careful with SHOW here. An existing session that has already read the old value, or that set its own value with SET, keeps it. Open a new connection to confirm the change.
A global increase affects every connection, so it is usually the wrong first move. Narrower scopes limit the risk:
ALTER ROLE reporting SET work_mem = '256MB';The same idea works per database (ALTER DATABASE ... SET) and per transaction:
BEGIN;
SET LOCAL work_mem = '512MB';
-- run the one heavy report query here
COMMIT;SET LOCAL reverts at the end of the transaction. This suits a batch job that needs a large allowance once. Role and database settings apply only to new sessions, so connection poolers that reuse sessions may keep old values until the connection is recycled.
Why more is not always better
Raising work_mem carries three costs.
- Memory risk. Worst-case use multiplies with the number of concurrent operations, as the next section shows.
- Planner behavior. The planner uses
work_memto estimate whether a hash or sort will fit. A larger value makes hash joins and hash aggregation look cheaper, so plans can change. That is often good, but it should be tested. - Diminishing returns. Once a sort fits in memory, extra memory does nothing. Going from 64MB to 1GB gains nothing for a query that needs 40MB.
Also note that the on-disk size of a spill is not the memory needed to avoid it. In-memory representation of rows is usually larger than the compact form written to temp files, so you may need a work_mem several times the Disk: figure. Find the right value by trying it under EXPLAIN (ANALYZE) in a session with SET work_mem, not by calculation.
Estimating worst-case memory
The rough budget has this shape:
SELECT 8 * 1024 * 1024 * 1024 AS shared_buffers_bytes,
100 * (64 * 1024 * 1024) AS example_work_mem_worst_case_bytes;
-- Rough budget: shared_buffers + max_connections * (work_mem * memory-hungry nodes per query)
-- + maintenance_work_mem * concurrent maintenance jobs + OS and page cache headroomHere 100 connections each running one 64MB operation need 6.4GB, on top of 8GB of shared_buffers. If each query has three memory-hungry nodes, the figure triples to about 19GB. Parallel workers raise it again.
Most servers never reach the worst case, because not every connection runs a heavy query at once. But a burst of reporting queries can. When the operating system runs out of memory, the Linux OOM killer may terminate a PostgreSQL backend, and the postmaster then restarts all backends. That is far worse than a slow query.
A practical approach:
- Keep the global default modest, often 4MB to 64MB depending on RAM and connection count.
- Give heavy roles or transactions a larger value through
ALTER ROLEorSET LOCAL. - Reduce the number of concurrent heavy queries with a connection pooler instead of letting hundreds of sessions run in parallel.
hash_mem_multiplier
Hash-based operations are more sensitive to memory than sorts, because a hash table that does not fit is split into batches with costly rewrites. PostgreSQL provides hash_mem_multiplier, which scales the limit for hash nodes to work_mem * hash_mem_multiplier. Since PostgreSQL 15 the default is 2.0. It lets you favor hash joins and aggregates without enlarging every sort. A later chapter covers it in detail.
Common mistakes
- Treating work_mem as per connection. It is per operation, and parallel workers multiply it.
- Setting a high global value to fix one query. Use a role, database, or
SET LOCALinstead. - Testing in a session that already set its own value.
SHOW work_memin that session does not reflect the global change. - Reading
Disk:as the memory needed. Test candidates directly. - Ignoring plan changes. A higher value can switch a nested loop or merge join to a hash join. Compare plans before and after.
Summary workflow for a spill problem
- Confirm that spills are frequent using
pg_stat_databaseandlog_temp_files. - Identify the statements involved from the log or
pg_stat_statements. - Test a higher value in one session with
EXPLAIN (ANALYZE, BUFFERS). - Apply it at the narrowest scope that covers the workload.
- Recompute the worst-case budget.
- Re-measure temporary file counts after a representative period.
Exercise
A server has 16GB of RAM, shared_buffers = 4GB, max_connections = 200, and work_mem = 64MB. A typical reporting query has two sorts and one hash join. Is the global setting safe if 50 reporting queries can run at once? Show the arithmetic and suggest a change.
Show answer
Each reporting query can use up to 3 nodes x 64MB = 192MB (hash nodes may use more with hashmemmultiplier, so treat this as a floor). Fifty such queries need about 50 x 192MB = 9.6GB. Add 4GB of sharedbuffers and the total is 13.6GB, which leaves about 2.4GB for the OS, page cache, maintenance work, and other connections, and parallel workers can push it over. It is not safe. Lower the global workmem to something like 16MB, give the reporting role a larger value with ALTER ROLE reporting SET work_mem, and limit concurrent reporting queries with a pooler or a connection limit on that role.
Exercise
An EXPLAIN (ANALYZE, BUFFERS) output shows "Sort Method: external merge Disk: 90000kB" for a query that runs once a day. Should you raise work_mem globally? What would you check first?
Show answer
No. A once-a-day query does not justify a global increase. First check how much time the spill costs relative to the total runtime and whether the query matters. If it does, use SET LOCAL work_mem inside the job's transaction, or ALTER ROLE for the job's role, and test values under EXPLAIN (ANALYZE) until the method changes to quicksort. Remember that the in-memory size is larger than the 90000kB on disk.