Symptom
One of these, usually during a report run or a batch job:
- Free space on the data volume drops by tens of GB in minutes, then recovers when a query finishes or is cancelled.
- Queries fail with
ERROR: temporary file size exceeds temp_file_limit (10485760kB). base/pgsql_tmp(orpgsql_tmpunder a temp tablespace) contains largepgsql_tmpNNNN.Nfiles.- In the worst case the disk fills, WAL can't be written and PostgreSQL stops accepting writes.
Temporary files are written when a sort, hash join, hash aggregate, materialize step or index build needs more memory than work_mem (or maintenance_work_mem for index builds) allows. They are deleted when the operation ends. The disk space comes back on its own. The cause is still there, though: a query doing a large spill.
Warning
If the data disk is already above 95%, cancel the spilling query first (
pg_cancel_backend) and investigate afterwards. A full disk takes down WAL writes for every session, not just the one spilling.
Check 1: who is spilling right now
pg_ls_tmpdir() (PostgreSQL 12+) lists temp files in the default tablespace. It needs superuser or pg_monitor. On managed services, run it as the admin user.
-- Temp files on disk right now, largest first
SELECT name, pg_size_pretty(size) AS size, modification
FROM pg_ls_tmpdir()
ORDER BY size DESC
LIMIT 20;
The number in the file name (pgsql_tmp12345.3) is the PID of the backend writing it. Parallel workers write their own files, so check the leader PID as well.
-- Map the PID to the query and its runtime
SELECT pid, leader_pid, usename, application_name, state,
now() - query_start AS runtime,
left(query, 200) AS query
FROM pg_stat_activity
WHERE pid IN (12345) -- PIDs from the file names
OR leader_pid IN (12345);
Cancel it if you need to:
SELECT pg_cancel_backend(12345); -- cancel the query
-- SELECT pg_terminate_backend(12345); -- end the session if cancel does not work
Check 2: who has been spilling over time
Cumulative counters per database:
SELECT datname, temp_files,
pg_size_pretty(temp_bytes) AS temp_written,
stats_reset
FROM pg_stat_database
WHERE datname IS NOT NULL
ORDER BY temp_bytes DESC;
If pg_stat_statements is installed, you can see per statement which queries write temp blocks (8 kB each by default):
SELECT queryid,
calls,
pg_size_pretty(temp_blks_written * current_setting('block_size')::bigint) AS temp_written,
pg_size_pretty((temp_blks_written * current_setting('block_size')::bigint) / NULLIF(calls,0)) AS per_call,
round(mean_exec_time::numeric, 1) AS mean_ms,
left(query, 120) AS query
FROM pg_stat_statements
ORDER BY temp_blks_written DESC
LIMIT 15;
Column names differ in older releases: before PostgreSQL 13 it is mean_time, not mean_exec_time.
Check 3: log every spill above a threshold
log_temp_files logs each temp file when it is deleted, along with the statement that created it. The value is in kB. 0 logs every file and -1 (the default) turns logging off.
ALTER SYSTEM SET log_temp_files = '100MB';
SELECT pg_reload_conf();
Log lines look like this:
LOG: temporary file: path "base/pgsql_tmp/pgsql_tmp48211.0", size 2147483648
STATEMENT: SELECT customer_id, sum(amount) FROM orders GROUP BY customer_id ORDER BY 2 DESC
On RDS/Aurora, set it in the DB parameter group. On Azure Flexible Server, set it under server parameters:
aws rds modify-db-parameter-group --db-parameter-group-name pg16-prod \
--parameters "ParameterName=log_temp_files,ParameterValue=102400,ApplyMethod=immediate"
az postgres flexible-server parameter set -g rg-db -s pg-prod \
--name log_temp_files --value 102400
Find the step that spills
Run the statement with EXPLAIN (ANALYZE, BUFFERS) on a replica or in a quiet window. It executes the query.
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, sum(amount)
FROM orders
GROUP BY customer_id
ORDER BY 2 DESC;
Look for these lines:
| Plan output | What it means | Usual fix |
|---|---|---|
Sort Method: external merge Disk: 812345kB | Sort larger than work_mem | Raise work_mem for this query, add an index that supplies the order, or sort fewer rows |
Hash ... Batches: 64 (originally 1) | Hash join split into batches on disk | Better row estimates (ANALYZE, extended stats), more work_mem/hash_mem_multiplier, smaller build side |
HashAggregate ... Batches: 33 Disk Usage: ... | Hash aggregate spilled (PostgreSQL 13+) | Same as hash join; check if GROUP BY cardinality was underestimated |
temp read=... written=... under Buffers: | Total temp I/O for that node | Start with the node that has the largest value |
CREATE INDEX writing temp files | Index sort exceeded maintenance_work_mem | Raise maintenance_work_mem for the session doing the build |
A badly underestimated row count is the most common root cause. The planner picks a hash for 1,000 rows, gets 50 million, and spills. Compare rows= estimated against actual rows= on the spilling node before you touch memory.
Fix
Give the query enough memory, but only that query
Don't raise work_mem globally. Every sort or hash node in every session can use up to that amount, and hash nodes can use work_mem × hash_mem_multiplier. Scope the change instead:
-- One transaction only
BEGIN;
SET LOCAL work_mem = '512MB';
SELECT ...;
COMMIT;
-- A reporting role
ALTER ROLE reporting_user SET work_mem = '256MB';
-- An index build session
SET maintenance_work_mem = '2GB';
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);
To check whether the spill went away, re-run EXPLAIN (ANALYZE, BUFFERS). You want Sort Method: quicksort Memory: or Batches: 1.
Caution
work_memis per operation, not per session. A query with six hash joins running in 4 parallel workers can use 24 times the value or more. Before you raise it for a role, multiply the value by the role's realistic concurrency and check that against free RAM.
Fix the query or the statistics
- Run
ANALYZEon the tables involved. If the columns are correlated, add extended statistics (CREATE STATISTICS ... (dependencies, ndistinct)). - Add an index that returns rows already ordered, so the sort disappears.
- Filter or pre-aggregate before the join, not after it.
- If someone runs
SELECT DISTINCTorORDER BYover a whole table and only needs the first page, replace it with keyset pagination.
Put a ceiling on temp usage
temp_file_limit caps the temp space a single process can use. The value is in kB and the default -1 means no limit. A query that exceeds the cap fails with the error above, and the disk stays safe.
ALTER SYSTEM SET temp_file_limit = '20GB'; -- superuser; reload is enough
SELECT pg_reload_conf();
-- Or tighter for ad-hoc users
ALTER ROLE analyst SET temp_file_limit = '5GB';
Only a superuser (or a role granted SET on the parameter in PostgreSQL 15+) can set temp_file_limit per role. On managed services, set it in the parameter group or server parameters.
Move temp files off the data volume
On self-managed servers you can place temp files in a separate tablespace on fast local disk. That way a spill can't fill the volume that holds the data and WAL:
CREATE TABLESPACE temp_fast LOCATION '/pgtemp';
ALTER SYSTEM SET temp_tablespaces = 'temp_fast';
SELECT pg_reload_conf();
On Aurora PostgreSQL and on RDS instance classes with local NVMe, temp files can land on local storage. Some Azure Flexible Server tiers can do the same. Behaviour varies by service and instance class, so check your service's documentation for where temp files are stored and how large that space is.
Tip
Temp files left behind after a crash are removed at the next restart (
remove_temp_files_after_crash, on by default from PostgreSQL 14). If you find oldpgsql_tmpfiles with no matching PID, restarting removes them. Don't delete files by hand while the server is running unless you have confirmed no backend owns them.
Prevent it next time
- Keep
log_temp_filesset (100 MB is a reasonable start) and alert on the log line or on growth inpg_stat_database.temp_bytes. - Set a server-wide
temp_file_limitbelow the free space on the volume, and tighter per-role limits for ad-hoc and BI users. - Alert on data-volume free space at 80% and 90%, not only at 95%.
- Review the top
temp_blks_writtenstatements frompg_stat_statementsevery week. Fix the query or the statistics before raising memory. - Size
work_memper role from evidence, and leave the global default modest.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get