Sub topic 10
Queries that spill to temporary files
This chapter assumes you can read the pg_stat_statements view and rank queries by total and mean time, as covered in earlier chapters. It also assumes you know what work_mem is. Here you will learn how to find the statements that write temporary files, and what to do about them.
Why spills matter
Sorts, hash joins, hash aggregates, and a few other plan nodes build their data structures in memory. Each node may use about work_mem (4MB by default). Hash-based nodes may use work_mem * hash_mem_multiplier (PostgreSQL 13 and later; the multiplier defaults to 1.0 until PostgreSQL 17 and 2.0 from 18). When the data does not fit, PostgreSQL writes the overflow to temporary files on disk and reads it back later. This is called a spill.
A spill is not an error. The query still returns correct results, but it does extra disk writes and reads, so it runs slower. Because temporary files are created per execution, a frequently called query that spills can generate a lot of I/O.
pg_stat_statements records this per normalized query in these columns:
| Column | Meaning |
|---|---|
| `temp_blks_read` | Blocks read back from temporary files |
| `temp_blks_written` | Blocks written to temporary files |
| `temp_blk_read_time` | Milliseconds spent reading temporary blocks (PostgreSQL 15 and later, only if `track_io_timing` is on) |
| `temp_blk_write_time` | Milliseconds spent writing temporary blocks (same conditions) |
| `local_blks_*` | Blocks for temporary tables. These are not spills. |
Do not confuse temp_blks_* with local_blks_*. The local columns count access to session-local tables created with CREATE TEMP TABLE. The temp columns count the working files that the executor creates on its own.
Finding spilling statements
The simplest query lists every statement that has written temporary blocks, worst first:
SELECT queryid,
calls,
temp_blks_written,
left(query, 80) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 10;Block counts are hard to judge by eye. A block is 8kB in a default build, but the value is configurable at compile time, so read it from the server instead of assuming. This version converts to bytes and adds a per-call figure:
SELECT queryid,
calls,
pg_size_pretty(temp_blks_written
* current_setting('block_size')::bigint) AS temp_written,
round(temp_blks_written::numeric / calls, 1) AS blks_per_call,
round(mean_exec_time::numeric, 2) AS mean_ms,
left(query, 80) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC
LIMIT 10;The per-call figure separates two different problems:
- High total, low per call. A cheap query that runs millions of times and spills a little each time. Fixing it may need a small
work_memincrease or a better query shape. - High per call, few calls. A report or batch job that sorts or hashes a very large set. A larger
work_memfor that job only, or an index that avoids the sort, usually fits better.
Remember that normalization merges all parameter values into one row. A statement such as WHERE customer_id = $1 may spill only for one customer with a huge number of rows. The average will hide this, so look at max_exec_time and stddev_exec_time for the same queryid as well.
flowchart TDThe diagram below shows the decision the executor makes for each memory-hungry node, and where the counters you query come from.
Reproducing a spill
You can see the whole cycle on a small test table. Run this in a scratch database where the extension is already enabled:
CREATE TABLE spill_demo AS
SELECT g AS id, md5(g::text) AS payload
FROM generate_series(1, 500000) AS g;
SELECT pg_stat_statements_reset();
SET work_mem = '1MB';
SELECT count(*) FROM (
SELECT * FROM spill_demo ORDER BY payload
) AS s;Sorting 500,000 rows with 1MB of memory cannot be done in memory. Query the statistics:
SELECT calls,
temp_blks_written,
temp_blks_read,
pg_size_pretty(temp_blks_written
* current_setting('block_size')::bigint) AS written,
left(query, 60) AS query
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC;You should see one row for the sort query with thousands of blocks written. The exact numbers vary by version and platform.
Confirming with EXPLAIN
The statistics tell you that a statement spills. They do not tell you which plan node does it. Run the statement under EXPLAIN:
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM spill_demo ORDER BY payload;Look for these signs in the output:
Sort Method: external merge Disk: ...kBon a Sort node. An in-memory sort saysquicksort Memory: ...kBinstead.Buffers: temp read=... written=...on the node that spills. These are the same counters, for one execution.Batches: 8(or any value above 1) on a Hash or HashAggregate node. More than one batch means the hash table was split across temporary files.
The Buffers line on the top node sums the whole plan, so check the individual nodes to find the source of the spill.
Now give the session enough memory and run it again:
SET work_mem = '256MB';
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM spill_demo ORDER BY payload;The Sort node should now report quicksort and the temp counters should disappear. If it still spills, the data needs more memory than you granted. Raise the value and try again.
Choosing a fix
Raising work_mem is the obvious fix, and also the one most likely to cause harm if done globally. The limit applies per plan node, not per query, and a complex query may have several sorts and hashes. Every concurrent connection can use that much again. A value that looks safe for one session can exhaust RAM under load.
Options, from least to most risky:
- Change the query or the schema. An index that matches the
ORDER BYremoves the sort. Selecting fewer columns shrinks each row. Filtering earlier reduces the data that reaches the sort or hash. - Raise
work_memfor one transaction. UseSET LOCAL work_mem = '128MB'inside the transaction that runs the heavy statement. - Raise it for one role or database.
ALTER ROLE reporting SET work_mem = '128MB'applies to a reporting user without touching OLTP traffic. - Raise the global default. Do this last, and only after estimating
work_memtimes the number of nodes times the number of connections against available memory.
BEGIN;
SET LOCAL work_mem = '128MB';
-- run the heavy report here
COMMIT;Index builds and VACUUM use maintenance_work_mem, not work_mem. A spill during CREATE INDEX is controlled by that setting.
Cross-checking with other sources
pg_stat_statements shows which statements spill. Two other tools help you judge how big the problem is overall:
pg_stat_databasehastemp_filesandtemp_bytesper database. They are cumulative, like the statement counters, and cover all statements, including ones that were evicted frompg_stat_statements.- Setting
log_temp_files = 0(or a size threshold such as'10MB') writes a log line for each temporary file when it is deleted. The line includes the file size and, for most statements, the statement text. This gives you a per-execution record, whichpg_stat_statementsdoes not keep.
SELECT datname,
temp_files,
pg_size_pretty(temp_bytes) AS temp_size
FROM pg_stat_database
WHERE datname = current_database();Common mistakes
- Treating every spill as a bug. A nightly report that writes 200MB once a day may not be worth a configuration change.
- Reading
local_blks_writtenas spills. Those blocks belong to temporary tables. - Ignoring parameter skew. The average per call can look harmless while one parameter value spills heavily.
- Raising
work_memglobally to fix one query. Scope the change to the role, session, or transaction that needs it. - Judging a fix by a single run. Compare
temp_blks_writtenper call before and after, over the same kind of workload.
Exercise
After running a workload, one statement shows calls = 20, tempblkswritten = 2,400,000, and meanexectime = 9,500 ms. Another shows calls = 4,000,000, tempblkswritten = 8,000,000, and meanexectime = 0.4 ms. With an 8kB block size, how much does each statement write per call, and which kind of fix suits each one?
Show answer
The first writes 2,400,000 / 20 = 120,000 blocks per call, about 940MB. This is a heavy batch or report query, so use a per-transaction or per-role workmem increase, or an index or query rewrite that avoids the large sort or hash. The second writes 8,000,000 / 4,000,000 = 2 blocks per call, about 16kB. It is cheap per call but frequent, so check whether a small workmem increase for that role, or a tighter query shape, stops the repeated small spills.
Exercise
You run EXPLAIN (ANALYZE, BUFFERS) on a statement that pgstatstatements flagged for temporary writes, and the top node shows "Buffers: temp read=5000 written=5000". How do you find which node is responsible, and what text on that node confirms a spill?
Show answer
Read the Buffers lines on each child node, since the top node adds up the whole plan. A Sort node with "Sort Method: external merge Disk: ...kB" confirms a sort spill. A Hash or HashAggregate node with "Batches" greater than 1 confirms a hash spill. The node with its own temp read and written counters is the source.