In PostgreSQL, work_mem sets the base memory budget for individual query operations, such as sorts and hash joins, before they spill to temporary files. Set it too low, and spills can slow queries significantly. Set it too high, and concurrent queries can exhaust available memory. This post explains how work_mem affects query execution, how to monitor memory pressure and disk spills, and how to choose a setting for your workload.

How work_mem Changes Query Execution

We’ll run three experiments to see how work_mem affects sorting, hash joins, and hash aggregation.

Each experiment runs the same query twice with parallel query disabled: first at PostgreSQL’s built-in work_memdefault of 4MB, then at 512MB. EXPLAIN (SETTINGS) does not list work_mem when it matches the built-in default.

Create the sample data used by all three tests:

CREATE TABLE yuan_mem AS
SELECT id, md5(random()::text) AS id_text
FROM (
SELECT 1 + floor(random() * 6000000)::integer AS id
FROM generate_series(1, 6000000)
) AS sampled;
ANALYZE yuan_mem;

Sort

Sort six million rows by id and compare disk spills at 4MB and 512MB.

BEGIN;
SET LOCAL max_parallel_workers_per_gather = 0;
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT id, id_text FROM yuan_mem ORDER BY id;
SET LOCAL work_mem = '512MB';
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT id, id_text FROM yuan_mem ORDER BY id;
ROLLBACK;

Execution plans at 4MB and 512MB:


BEGIN
SET
                                                QUERY PLAN

-----------------------------------------------------------------------------------------------------------
 Sort  (cost=1113775.97..1128777.36 rows=6000555 width=37) (actual rows=6000000.00 loops=1)
   Sort Key: id
   Sort Method: external merge  Disk: 276016kB  👈
   Buffers: shared hit=188 read=49860, temp read=68996 written=69115  👈
   ->  Seq Scan on yuan_mem  (cost=0.00..110053.55 rows=6000555 width=37) (actual rows=6000000.00 loops=1)
         Buffers: shared hit=188 read=49860
 Settings: max_parallel_workers_per_gather = '0'
 Planning Time: 0.045 ms
 Execution Time: 16662.344 ms  👈
(9 rows)

SET
                                                QUERY PLAN

-----------------------------------------------------------------------------------------------------------
 Sort  (cost=785615.97..800617.36 rows=6000555 width=37) (actual rows=6000000.00 loops=1)
   Sort Key: id
   Sort Method: quicksort  Memory: 485412kB  👈
   Buffers: shared hit=282 read=49766  👈
   ->  Seq Scan on yuan_mem  (cost=0.00..110053.55 rows=6000555 width=37) (actual rows=6000000.00 loops=1)
         Buffers: shared hit=282 read=49766
 Settings: max_parallel_workers_per_gather = '0', work_mem = '512MB'  👈
 Planning Time: 0.044 ms
 Execution Time: 3003.005 ms  👈
(9 rows)

ROLLBACK


At 4MB, the sort used external merge, reported Disk: 276016kB, and wrote 69,115 temporary blocks. At 512MB, it used quicksort with about 474 MiB of memory and no temporary I/O. Execution time fell from 16.662 s to 3.003 s, an 82.0% reduction in this run.

Hash Join

Join yuan_mem to itself on id and compare hash batches and temporary I/O at 4MB and 512MB.

BEGIN;
SET LOCAL max_parallel_workers_per_gather = 0;
SET LOCAL enable_hashjoin = on;
SET LOCAL enable_mergejoin = off;
SET LOCAL enable_nestloop = off;
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT count(*)
FROM yuan_mem AS left_rows
JOIN yuan_mem AS right_rows ON left_rows.id = right_rows.id;
SET LOCAL work_mem = '512MB';
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT count(*)
FROM yuan_mem AS left_rows
JOIN yuan_mem AS right_rows ON left_rows.id = right_rows.id;
ROLLBACK;

Hash join plans at 4MB and 512MB:

BEGIN
SET
SET
SET
SET
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=588876.86..588876.87 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=849 read=99247, temp read=34664 written=34664 👈
-> Hash Join (cost=208500.49..560877.41 rows=11199782 width=0) (actual rows=11996928.00 loops=1)
Hash Cond: (left_rows.id = right_rows.id)
Buffers: shared hit=849 read=99247, temp read=34664 written=34664 👈
-> Seq Scan on yuan_mem left_rows (cost=0.00..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buffers: shared hit=470 read=49578
-> Hash (cost=110053.55..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buckets: 262144 Batches: 64 Memory Usage: 5343kB 👈
Buffers: shared hit=379 read=49669, temp written=17269 👈
-> Seq Scan on yuan_mem right_rows (cost=0.00..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buffers: shared hit=379 read=49669
Settings: max_parallel_workers_per_gather = '0', enable_mergejoin = 'off', enable_nestloop = 'off'
Planning:
Buffers: shared hit=24 read=5
Planning Time: 5.158 ms
Execution Time: 20483.426 ms 👈
(17 rows)
SET
QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=495116.86..495116.87 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=1225 read=98871 👈
-> Hash Join (cost=185060.49..467117.41 rows=11199782 width=0) (actual rows=11996928.00 loops=1)
Hash Cond: (left_rows.id = right_rows.id)
Buffers: shared hit=1225 read=98871 👈
-> Seq Scan on yuan_mem left_rows (cost=0.00..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buffers: shared hit=658 read=49390
-> Hash (cost=110053.55..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buckets: 8388608 Batches: 1 Memory Usage: 276474kB 👈
Buffers: shared hit=567 read=49481
-> Seq Scan on yuan_mem right_rows (cost=0.00..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buffers: shared hit=567 read=49481
Settings: max_parallel_workers_per_gather = '0', enable_mergejoin = 'off', enable_nestloop = 'off', work_mem = '512MB' 👈
Planning Time: 0.080 ms
Execution Time: 7222.371 ms 👈
(15 rows)
ROLLBACK

At 4MB, the hash join split the input into 64 batches and read and wrote 34,664 temporary blocks each (about 271 MiB each with 8 KiB blocks). At 512MB, the hash table fit in one batch at about 270 MiB, with no temporary I/O. Execution time fell from 20.483 s to 7.222 s, a 64.7% reduction in this run.

Hash Aggregate

Group yuan_mem by id and compare hash batches and temporary I/O at 4MB and 512MB.

BEGIN;
SET LOCAL max_parallel_workers_per_gather = 0;
SET LOCAL enable_hashagg = on;
SET LOCAL enable_sort = off;
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT id, count(*) FROM yuan_mem GROUP BY id;
SET LOCAL work_mem = '512MB';
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT id, count(*) FROM yuan_mem GROUP BY id;
ROLLBACK;

Hash aggregate plans at 4MB and 512MB:

BEGIN
SET
SET
SET
QUERY PLAN
----------------------------------------------------------------------------------------------------------
HashAggregate (cost=447584.77..526613.53 rows=3214943 width=12) (actual rows=3793822.00 loops=1)
Group Key: id
Planned Partitions: 64 Batches: 65 Memory Usage: 8729kB Disk Usage: 191616kB 👈
Buffers: shared hit=752 read=49296, temp read=17070 written=40608 👈
-> Seq Scan on yuan_mem (cost=0.00..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buffers: shared hit=752 read=49296
Settings: max_parallel_workers_per_gather = '0', enable_sort = 'off'
Planning Time: 0.058 ms
Execution Time: 16871.382 ms 👈
(9 rows)
SET
QUERY PLAN
----------------------------------------------------------------------------------------------------------
HashAggregate (cost=140056.33..172205.76 rows=3214943 width=12) (actual rows=3793822.00 loops=1)
Group Key: id
Batches: 1 Memory Usage: 286745kB 👈
Buffers: shared hit=846 read=49202 👈
-> Seq Scan on yuan_mem (cost=0.00..110053.55 rows=6000555 width=4) (actual rows=6000000.00 loops=1)
Buffers: shared hit=846 read=49202
Settings: max_parallel_workers_per_gather = '0', enable_sort = 'off', work_mem = '512MB' 👈
Planning Time: 0.058 ms
Execution Time: 3725.998 ms 👈
(9 rows)
ROLLBACK

At 4MB, the hash aggregate spilled to disk: it ran in 65 batches, reported about 187 MiB of disk usage, and wrote 40,608 temporary blocks. At 512MB, the same HashAggregate used about 280 MiB and completed in one batch with no temporary I/O. Execution time fell from 16.871 s to 3.726 s, a 77.9% reduction in this run.

Raising work_mem from 4MB to 512MB eliminated disk spills in all three experiments and cut execution time by 82.0% for the sort, 64.7% for the hash join, and 77.9% for the hash aggregate.

One query can use multiple work_mem budgets

work_mem is a per-operation budget, not a memory cap for the query. The tests above disable parallel workers to make the individual operations easier to compare. A real execution plan can use more memory in three ways:

  • Multiple nodes in one plan: Each sort or hash operation has its own memory budget based on work_mem. If several operations hold memory at the same time, a single query can use several times the configured work_memvalue.
  • Hash operations: The memory budget for a hash join or HashAggregate is work_mem × hash_mem_multiplier. The default multiplier is 2.0, so with work_mem = '4MB', each hash operation has an 8 MiB budget.
  • Parallel workers: Each worker can use its own work_mem budget for operations it runs independently. A parallel query can therefore use several times that budget, especially if the leader also participates.

Monitoring Memory Pressure and Disk Spills

The work_mem setting affects both memory pressure and disk spills. Monitoring both helps you judge whether the setting is right for your workload. Use PostgreSQL logs and database views to track spills, and OS process metrics to monitor backend memory under load.

1. PostgreSQL Logs

The log_temp_files setting controls which temporary files PostgreSQL logs. Set it to 0 to log each file’s name and size when it’s deleted. The following example enables logging for a single transaction and compares the logged file size with the Disk: value in the sort plan.


postgres=# BEGIN;
SET LOCAL log_temp_files = 0;
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT id, id_text FROM yuan_mem ORDER BY id;
ROLLBACK;
BEGIN
SET
                                                QUERY PLAN
-----------------------------------------------------------------------------------------------------------
 Sort  (cost=1113775.97..1128777.36 rows=6000555 width=37) (actual rows=6000000.00 loops=1)
   Sort Key: id
   Sort Method: external merge  Disk: 276016kB  👈
   Buffers: shared hit=1128 read=48920, temp read=68996 written=69115  👈
   ->  Seq Scan on yuan_mem  (cost=0.00..110053.55 rows=6000555 width=37) (actual rows=6000000.00 loops=1)
         Buffers: shared hit=1128 read=48920
 Planning Time: 0.048 ms
 Execution Time: 4154.907 ms
(8 rows)

ROLLBACK


The sort spilled to disk, and the execution plan reported Disk: 276016kB. The corresponding PostgreSQL log entry showed the temporary file’s path and size in bytes:

2026-12-01 07:47:40.315 GMT [2270770] LOG: temporary file: path "base/pgsql_tmp/pgsql_tmp2270770.2", size 282640384
2026-12-01 07:47:40.315 GMT [2270770] STATEMENT: EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF)
SELECT id, id_text FROM yuan_mem ORDER BY id;

The file size matches the plan’s Disk: figure: 276016 × 1024 = 282640384 bytes.

2. Database Views

With pg_stat_statements enabled, you can see how many temporary blocks each statement has read and written across all recorded calls. The query below lists the five statements with the most temporary blocks written, using temporary blocks read to break ties:

SELECT left(query, 20) AS query_prefix,
calls,
temp_blks_written,
temp_blks_read,
round(temp_blks_written::numeric / NULLIF(calls, 0), 1) AS avg_written_per_call
FROM pg_stat_statements
WHERE temp_blks_written > 0
ORDER BY temp_blks_written DESC, temp_blks_read DESC
LIMIT 5;

Sample output:

     query_prefix     | calls | temp_blks_written | temp_blks_read | avg_written_per_call
----------------------+-------+-------------------+----------------+----------------------
 EXPLAIN (ANALYZE, BU |     8 |            414690 |         413976 |              51836.3
 select c_name, c_cus |     2 |            157776 |         101052 |              78888.0
 SELECT left(regexp_r |     3 |             71583 |          71583 |              23861.0
 EXPLAIN (ANALYZE, BU |     3 |             70284 |          69740 |              23428.0
 SELECT id, id_text F |     1 |             69115 |          68996 |              69115.0
(5 rows)

3. OS Processes

On Linux, use pidstat to sample each PostgreSQL process’s memory usage once per second:

$ pidstat -r -C postgres 1

Sample output:

09:54:47 AM UID PID minflt/s majflt/s VSZ RSS %MEM Command
09:54:48 AM 26 2210137 13.00 0.00 440404 50164 0.32 postgres
09:54:48 AM 26 2210139 4.00 0.00 440536 144760 0.91 postgres
09:54:48 AM 26 2210140 43.00 0.00 440404 136980 0.86 postgres
09:54:48 AM 26 2210141 58.00 0.00 440404 133376 0.84 postgres

To assess memory pressure, start by tracking two pidstat metrics over time: RSS, which shows how much memory each process has resident, and majflt/s, which shows how often a process must fetch a memory page from storage. Neither proves memory pressure on its own; check system-wide available memory and swap activity for context.

Setting work_mem for Your Workload

The goal of tuning work_mem is to meet your latency and throughput targets at realistic concurrency, not to eliminate every disk spill. More memory isn’t always better: use the lowest setting that meets your performance goals without creating memory pressure.

Tuning work_mem is an iterative process:

  1. Start with a conservative baseline. PostgreSQL’s built-in 4MB default is a reasonable starting point. It can be enough for operations that sort or hash small amounts of data. Queries that sort or hash large amounts of data may benefit from a higher setting.
  2. Raise work_mem when costly spills slow queries. During a short diagnostic run, set log_temp_files = 0 to log every temporary file. If a slow query generates substantial temporary I/O, increase work_mem in small steps and retest to see whether the query gets faster.
  3. Choose the lowest effective setting. Stop when you meet your latency and throughput targets at realistic concurrency without creating memory pressure. You don’t need to eliminate every spill.
  4. Tune exceptions separately. Use SET LOCAL inside a transaction for occasional queries that need more memory. For workloads with different needs in the same cluster, use database- or role-specific defaults instead of raising the setting for everyone.

Leave a Reply

I’m Yuan

Welcome to the blog of a database performance maven. Feel free to contact me to share and discuss database knowledge.

My Oracle Book

My 26 Oracle Certifications

A screenshot from certview.oracle.com

My MySQL Book

MySQL 8.0 Operations and Optimization

Let’s connect