Sub topic 2
work_mem: sorts, hashes, and temporary files
This chapter assumes you can run queries in psql, edit postgresql.conf, reload the server, and read a simple EXPLAIN plan.
How work_mem is used
work_mem sets how much memory one sort or hash operation can use before it writes temporary files to disk. The default is 4MB. The limit applies per operation, not per connection, so a query with three sorts can use three times the value.
Use EXPLAIN to check for spills:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY created_at;A line such as "Sort Method: external merge Disk: ..." means the sort spilled. "Sort Method: quicksort Memory: ..." means it fit.
To see how often each database spills, query pgstatdatabase:
SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp_size
FROM pg_stat_database
ORDER BY temp_bytes DESC;Raise work_mem for one role that runs heavy reports, not for every connection:
ALTER ROLE reporting SET work_mem = '256MB';Giving hash operations more memory with hash_mem_multiplier
Hash joins and hash aggregates may use workmem multiplied by hashmem_multiplier. The default multiplier is 2.0 in current releases.
| Setting | Default | Applies to |
|---|---|---|
| work_mem | 4MB | Sorts and hash tables |
| hash_mem_multiplier | 2.0 | Hash tables, as a multiple of work_mem |
| maintenance_work_mem | 64MB | VACUUM, CREATE INDEX, autovacuum |
maintenance_work_mem for VACUUM, CREATE INDEX, and autovacuum
maintenanceworkmem covers maintenance commands such as VACUUM and CREATE INDEX. Each autovacuum worker uses autovacuumworkmem, which falls back to maintenanceworkmem when unset. Three workers at 1GB each can use 3GB at the same time.
Budgeting memory across connections
Estimate the worst case with this formula:
maxconnections × workmem × memory-hungry nodes per query, plus maintenanceworkmem × concurrent maintenance jobs, plus shared_buffers.
For example, 100 connections, workmem of 64MB, and 2 sort or hash nodes per query give 100 × 64MB × 2 = 12.8GB, before sharedbuffers.
WAL and checkpoint tuning
A checkpoint writes dirty pages to disk. It runs every checkpointtimeout (default 5min) or when WAL reaches maxwal_size (default 1GB). Frequent checkpoints create bursts of writes. Set these values in postgresql.conf:
# postgresql.conf
max_wal_size = 4GB
checkpoint_timeout = 15min
checkpoint_completion_target = 0.9
log_checkpoints = oncheckpointcompletiontarget = 0.9 spreads checkpoint writes over 90% of the interval. log_checkpoints writes each checkpoint to the server log so you can check the effect. These settings take effect with a reload, not a restart.
> callout note
Exercise
A query plan shows "Sort Method: external merge Disk: 120kB". What is the likely cause, and what should you do first?
Show answer
The sort ran out of workmem and wrote temporary files. Raise workmem for that role or session, then rerun EXPLAIN (ANALYZE, BUFFERS) and confirm the plan shows "quicksort Memory".