Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Work_mem lab1 of 5
fits in work_mem 400 mssorted in memory does not fit temp files 2.3 sto disk and back 1,000,000 rows, 4 MB of work_mem

the story

Why not give the sort all the memory?

One query sorts 1,000,000 rows. Postgres gives each sort a slice of memory called work_mem. If the rows fit, the sort takes 400 ms. If not, the rest goes to disk and back: 2.3 s at the default 4 MB.

So give it more. But every session gets that same slice at the same time. Why does nobody set it to a gigabyte?

work_mem 16 MB 95 MBwritten to disk work_mem 64 MB ? MByour guess 4 times same 1,000,000 rows, one session

guess first

Four times the memory. How much less goes to disk?

800 MBmost it may be asked, of 12 GB free

sort takes 2.3 s spill 190 MB

run it

Turn work_mem up. Watch what the box could be asked for.

4 MB of work_mem

100 sessions run the sort at once. The box has 12 GB free. Red is what spills to disk.

every session gets its own work_mem #12 sorts each#22 sorts each#32 sorts each ... 100 sessions, all sorting at once the box has 12 GB free

why it grows

Every session gets its own work_mem. Twice.

Each session can run 2 memory-hungry steps at once, and each takes a full work_mem. Memory use is the setting times 2 times 100 sessions.

the working

100 × 2 × 64 MB = 12,800 MB12,800 ÷ 1,024 = 12.5 GBFree is 12 GB, so 12.5 GB is too much100 × 2 × 256 MB = 51,200 MB51,200 ÷ 1,024 = 50 GB
100 sessions at once 12 GB free 16 MBasks 3.1 GB64 MBasks 12.5 GB256 MBasks 50 GB which one keeps the box up?

your call

100 sessions, 12 GB free. Which work_mem?

Database InternalsQuery execution: sort and spill

The work_mem dial

Your sort spills to disk. Give it more memory and it stops. Why does nobody set work_mem to a gigabyte?

One query sorts a million rows, and Postgres gives that sort its own slice of memory, work_mem. Rows that fit are sorted in memory. The rest go to disk as sorted runs and are merged back. Every session gets the same slice at once. Turn the dial and watch spill and the worst case trade places.

try this Click The default, then A big desk and The whole room, drag Sessions running it at once, and watch The whole box.

100 sessions at once

These are teaching values. The query sorts 1,000,000 rows: 100 bytes each in a temporary file and 150 bytes each in memory. The server has 16 GB, 4 GB of it given to shared_buffers, and each copy of the query holds 2 memory-hungry steps at once. The merge rule is Postgres's own, from its sort code.

One query

190 MB

written to temporary files

Sort Method: external merge Disk: 97,656kB

36 sorted runs of 4 MB each went to temporary files, then 2 merge passes read them back, 15 at a time.

About 2.3 s for the sort.

The whole box

800 MB

the most these sessions could ask for, of 12 GB free

If every session sorted at once, they could ask for 800 MB of the 12 GB left after shared_buffers. It fits.

Largest safe setting at this many sessions: work_mem = 16MB.

The working

Where the spill, the time and the box's total come from, redone every time you move a control.

  1. Sorted runs, then mergessorted runs36after pass 13after pass 21The rows need 143 MB in memory and each sort may use 4 MB, so it sorts 36 batches, the last one part full, and writes each out as a sorted run. A merge reads 15 runs at once, so 36 runs become 3, then 1.= 2 passes
  2. Written to temporary filesthe runs95 MBpass 195 MBpass 2streams outWriting the runs puts every row on disk once, 95 MB. Each merge pass but the last writes them all again, and the last streams its rows straight to the query. 95 × 2= 190 MB
  3. The sort timesorted02.3 sSorting in memory takes 0.4 s. The 190 MB is written and read back, 380 MB at 200 MB/s, which adds 1.9 s. 0.4 + 1.9= 2.3 s
  4. The whole boxcould ask800 MBfree12 GBEach session holds 2 memory-hungry steps of 4 MB, 8 MB a session. 100 sessions could ask for 800 MB at once. The box has 12 GB free. 100 × 8= 800 MB

The dial, swept

Every setting at the current number of sessions. Read the temporary-file column against the last one. Spill falls in steps, not smoothly, and the row that spills nothing is the row the box cannot afford.

work_memSorted runsMerge passesTemp writtenSort timeBox could need
1MB1443285 MB3.25 s200 MB
4MB362190 MB2.3 s800 MB
16MB9195 MB1.35 s3.1 GB
64MB3195 MB1.35 s12.5 GB (over)
256MBin memory00 MB400 ms50 GB (over)

Sorted runs, then a merge

A sort that fits in work_mem reads its rows into memory, quicksorts them and hands them on. One that does not fit fills its memory, sorts that batch, writes it to a temporary file as a sorted run, and starts the next. When the input ends it merges the runs, reading the front of each and always taking the smallest. A merge can read only so many runs at once, because each needs a buffer in the same work_mem. Too many runs, and it merges them in groups and writes the groups back out, which is a second pass over every row.

That is why spill falls in steps. At 1 MB the sort makes 144 runs and needs 3 passes, writing 285 MB. At 16 MB it makes 9 runs, merges them all at once, and writes95 MB, every row exactly once. At 64 MB it still writes 95 MB: fewer, bigger runs, same one pass. Only at 256 MB, when the whole sort fits, does the disk drop out, and the sort takes400 ms instead of 1.35 s.

The setting is per sort, not per server

work_mem is not a budget the server shares out. Every sort and every hash in every running query may take that much, at the same moment. 100 sessions each running this query at 256 MB could ask for50 GB, on a box with 12 GB to give. Most of the time they will not all sort at once, which is why a large setting can look fine for months. The day they do, Linux's out-of-memory killer picks a process to end, and when that is a Postgres process every connection is dropped while the server recovers. The usual answer is a modest default for everyone and a larger value set for one session, or one role, that runs the big report.

Limits of this model

Teaching values. 1,000,000 rows of 100 bytes on disk and 150 in memory, 400 ms to sort them in memory, and 200 MB/s to the temporary file make the steps easy to read. They are not any machine's speed. The merge-order rule is Postgres's own (work_mem divided by 272 KB, kept between 6 and 500), but a real run count also depends on row width and allocator overhead.

A worst case, not a forecast. The box panel assumes every session uses its full allowance in2 steps at the same moment. Real plans have more or fewer memory-hungry steps, hash steps may use work_mem times hash_mem_multiplier (2 by default), and parallel workers each get their own allowance.

Sorts only. A hash aggregate or hash join that outgrows its memory also spills, in batches rather than runs. The operating system's page cache may hold the temporary files in memory, so a spill can be cheaper than the time column says.

Sources

On a narrow screen the three panels stack below the tabs and session slider. The table scrolls sideways.

the lesson The sentence that says what
The whole idea this lab came from, told start to finish.

on the path Module 1 of 1 in Database Internals: One Database, to the Bolt
The lessons, boards and videos around this lab, in reading order.

Board: The Query Planner

next lab The slate next to the stove
Most orders are for three favourites. How big does the slate need to be before a bigger one stops helping?