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
- PostgreSQL18.6-0ubuntu0.26.04.1
- Test data400,000 rows, 2 core / 4 GB host
- TimeAbout 16 min
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 |
This guide includes
Use this when a sort is slow and you suspect it is spilling to disk. This matters because work_mem is per operation rather than per connection - and the spill is measurable both in the plan and server-wide.
- sorting more than
work_memcan hold, and watching it spill - raising
work_memfor the session only, and measuring again - finding spills across the whole database with
pg_stat_database
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