Sub topic 5
`work_mem`: sorts, hashes, and temporary files
This chapter assumes you can run SQL in psql, read a simple EXPLAIN plan, and distinguish server-wide settings from session settings.
work_mem is the maximum memory PostgreSQL normally gives to one sort or hash operation before that operation uses temporary files. It is not a memory limit for a connection. One query can contain several memory-hungry operations, and parallel workers can perform their own operations.
See where memory is going
Start by checking the active value and its configuration context:
SELECT name, setting, unit, context, source, pending_restart
FROM pg_settings
WHERE name IN ('work_mem', 'hash_mem_multiplier',
'maintenance_work_mem');The context column tells you how a setting can change. A setting with user or query context can change for a session or query. A setting with sighup context needs a configuration reload. pending_restart identifies changes that still need a server restart.
A small work_mem value is safer for a busy server, but large sorts may spill to disk. A spill increases I/O and can make a query much slower.
Find sort and hash spills
Use EXPLAIN (ANALYZE, BUFFERS) on a representative query:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
ORDER BY created_at;In the plan, a line such as this indicates a spill:
Sort Method: external merge Disk: 184320kBexternal merge means PostgreSQL wrote intermediate sort data to temporary files. A line such as this means the sort stayed in memory:
Sort Method: quicksort Memory: 24576kBHash operations can also spill. Look for hash nodes that report batches greater than one, such as Batches: 8. Multiple batches usually mean the hash operation could not keep all its data in memory at once.
The BUFFERS option helps show regular table and index I/O, but temporary-file activity is easier to confirm with logging and statistics.
Measure temporary-file activity
This view reports temporary files created by each database since its statistics were last reset:
SELECT datname,
temp_files,
pg_size_pretty(temp_bytes) AS temp_size
FROM pg_stat_database
ORDER BY temp_bytes DESC;These counters do not identify the exact query. Enable temporary-file logging when you need that detail:
# postgresql.conf
log_temp_files = 0A value of 0 logs every temporary file. A positive value logs files at or above that many kilobytes. After changing the setting, reload the configuration and inspect the server log for the responsible statement and file size.
Choose a safe scope
Increase the setting only for a role or transaction that needs it:
BEGIN;
SET LOCAL work_mem = '256MB';
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, count(*)
FROM orders
GROUP BY customer_id
ORDER BY count(*) DESC;
ROLLBACK;SET LOCAL ends with the transaction. This limits the risk to the tested workload. You can also use ALTER ROLE ... SET work_mem for a dedicated reporting role.
hash_mem_multiplier allows hash operations to use more memory than work_mem. Treat that multiplier as part of the same memory budget.
Exercise
A query reports Sort Method: external merge Disk: 80MB. What should you do first?
Show answer
Confirm that the spill is important with execution timing and temporary-file statistics, then test a higher work_mem with SET LOCAL for that query before changing the global value.