Video in progress
What is `work_mem`, how does it affect sorts and hashes, and what do you do when `external merge Disk` shows up in EXPLAIN?
work_mem is the memory a single sort or hash operation may use before spilling to disk. If it isn't enough, PostgreSQL writes to temporary files and the query slows down. Raising it globally is risky, because one query can have several such operations and many connections each take that much.
📖 Answer
How it looks in EXPLAIN ANALYZE:
Sort (actual time=1830.2..2100.5 rows=2000000)
Sort Key: created_at
Sort Method: external merge Disk: 145000kB
The default work_mem is 4MB. A 145 MB sort spilled to disk.
Why not just set it to 1GB? Because this limit isn't per connection, it's per sort/hash node. A single complex query can have 5 such nodes, parallel workers take their own, and hash operations get hash_mem_multiplier times more (default 2 in PG15+). 200 connections × 5 × 1GB, and the server falls to the OOM killer.
The practical approach:
-- only for a heavy report
BEGIN;
SET LOCAL work_mem = '256MB';
SELECT ... ;
COMMIT;
-- or per role
ALTER ROLE reporting SET work_mem = '128MB';
I set the global value around 16-64MB, depending on memory and the connection count. I find queries that spill to disk through log_temp_files = 0 or temp_blks_written in pg_stat_statements.
Sometimes the problem isn't memory, it's the query: if there's a suitable index for the ORDER BY, no sort is needed at all.
Sign up to mark studied questions and save your progress.