Troubleshooting·PostgreSQL
PostgreSQL work_mem and Sort Spill
A sort spills to disk at the default `work_mem`. Raising it to 128 MB keeps the sort in memory - and makes the query **slower**. The measurement is the lesson.
Performance Guide 37 of 47 Advanced
- OSUbuntu 26.04 LTS (resolute)
- PostgreSQL18.6-0ubuntu0.26.04.1
- Test data400,000 rows, 2 core / 4 GB host
- TimeAbout 16 min
- Reviewed27 August 2026
Written against the versions above. `work_mem` is per sort or hash **per node per worker**, not per query. A parallel query with several sorts can use many multiples of it, which is why raising it globally is riskier than it looks.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| db-a01 | 192.168.0.81 | Ubuntu 26.04 LTS | Primary / Source / Replica Set Member 1 | 2 Core | 4 GB | 50 GB |
Before you start
- The
eventstable with 400,000 rows.
-
Sort more than work_mem can hold
-
Raise work_mem and measure again
-
Find spills across the whole database