writing

Your 4 GiB database was caching 128 MB

Until today a Gagarin postgres ran the same stock settings at every size. Now its size sets its memory and connections. We tuned it by the textbook first, and a stress test OOM-killed two of the three sizes. Our second attempt passed that test, and a code review still found two costs it missed. This post covers what we measured, the trade-off we made, and why shipping it restarted none of your databases.

A postgres on Gagarin comes in three sizes. S gets half a CPU and a 1 GiB ceiling on a shared node. M gets a dedicated CPU and 2 GiB, and L gets two CPUs and 4 GiB. Until today all three ran the settings postgres ships with:

settingstock value
shared_buffers128 MB
max_connections100
work_mem4 MB
effective_cache_size4 GB

So an L paid for 4 GiB and gave postgres 128 MB of it as buffer cache. An S told its query planner it had 4 GB of cache inside a 1 GiB pod. And a team running six app instances with a pool of 20 each would hit "too many clients" on whatever size they bought, while the CPU sat idle.

The textbook answer

Postgres tuning guides start in the same place. Give shared buffers a quarter of memory, tell the planner the rest is cache, and size work_mem so that connections times work_mem plus shared buffers fits in RAM. Our first plan did that and came out at 100, 200 and 300 connections with 2, 2 and 4 MB of work_mem. The arithmetic said each size would peak below 90% of its limit.

We wrote the test before we believed the arithmetic. It starts the real image inside the size's real memory limit, opens every connection, and makes all of them work at the same moment. The first version gave each connection a query with a hash join and a sort, and it OOM-killed S and M.

What a sort costs

Postgres bounds memory per plan node, so a query with four nodes can hold four times work_mem. We knew that, and we expected a single sort to hold one work_mem and a little change. Then we gave every connection one sort of 12 MB of text and read the container's own cgroup while it ran:

work_memresident per connection
idle1.6 MiB
1 MB4.2 MiB
2 MB7.4 MiB
4 MB12.1 MiB

A sort that spills to disk holds about three times its work_mem. The setting limits the tuples the sort keeps. The allocator's overhead around them and the merge's read buffers sit outside it. The guides' formula undercounts by a factor of three. On a 1 GiB pod with a hundred connections, that factor is the margin between a slow query and an OOM kill.

For comparison, stock S under the same load peaked at 976 MiB of its 1024. It survived, with 48 MiB to spare and no room for an autovacuum worker.

The parallel query surprise

The hash join run also failed in a second way. Queries came back with could not resize shared memory segment: No space left on device. Each parallel plan asks for a shared memory segment in the container's /dev/shm, and containers get 64 MiB of it by default. Ninety-seven parallel hash joins used it up before RAM ran short. Production databases on stock settings had the same exposure.

S and M have one CPU or less, so a parallel worker there competes with the query that started it for the same core. We turned parallel query off at every size, including L, which gives up two-way parallelism on big single queries. Parallel index builds take the same segments, so those went too.

What a connection holds after an hour

Our second table gave S, M and L 75, 140 and 150 connections. It passed the stress test, and then a review of the pull request asked two questions the test couldn't answer.

The first was about page tables. Each postgres connection is its own process, and shared buffers are memory every process maps. The kernel keeps 8 bytes of page table for each 4 KiB page a process touches, so a connection that has read all of a 1 GiB buffer cache holds 2 MiB of page tables for it. The container's memory limit counts that, and the kernel can't reclaim it while the connection stays open. Our sampler read anonymous and shared memory, so it never saw them. A pool that keeps connections open for hours reaches that state on its own.

The second was temp_buffers, the per-session cache for temporary tables, which ships at 8 MB. We hadn't counted it at all.

We ran the test again. This time every connection first read the whole buffer cache and filled a temp table:

page tablespeaklimit
S, 72 connections30 MiB849 MiB1024 MiB
M, 137 connections165 MiB1987 MiB2048 MiB
L, 147 connections326 MiBOOM-killed4096 MiB

So we added both costs to the model, cut temp_buffers to 2 MB, and kept the sizes' work_mem. That left fewer connections again.

The trade-off

Once a sort costs three times work_mem and a connection carries page tables and temp buffers on top, a size's memory buys connections or sort memory, and you have to pick. We kept work_mem at 2, 2 and 4 MB and gave up connections:

SML
max_connections60105119
shared_buffers128 MB512 MB1 GB
effective_cache_size512 MB1536 MB3 GB
work_mem2 MB2 MB4 MB
maintenance_work_mem64 MB64 MB256 MB
autovacuum_work_mem16 MB16 MB64 MB
temp_buffers2 MB2 MB2 MB
worst case by the model919 of 1024 MiB1843 of 20483678 of 4096
measured, the full load730 MiB1675 MiB3058 MiB

S keeps 128 MB of shared buffers because it reserves only 256 MiB on a shared node, and Kubernetes evicts pods by how far they run past their reservation. S drops from 100 connections to 60. M and L gain connections and a real cache.

The model that produced the worst-case row charges each connection three times work_mem, 2 MiB of overhead, its temp buffers and its page tables. On top of that it counts full shared buffers, three autovacuum workers and one index build. A unit test holds it under 90% of each limit. The stress test runs the full load at every size and fails if the measured peak beats the model. A third test raises work_mem to 64 MB and fails unless the harness catches the OOM kill that follows, so we know the detector works.

If one query needs more sort memory, it can ask for it:

sql
SET work_mem = '64MB';

That lasts for your session. If your app needs more connections, put a pooler in front of postgres or move up a size.

Shipping it restarted nothing

The settings ride on postgres's command line. That makes them outrank ALTER SYSTEM, so a stray ALTER SYSTEM SET shared_buffers = '8GB' can't crash-loop an S. A test runs that statement, restarts the server and checks the platform's value survived.

The command line also lives in the pod template, and our reconciler compares every template every minute. Changing it for every database at once would have restarted the whole platform's postgres fleet on deploy. So each database carries a tuning revision. Revision 0 means stock, and every database that existed this morning has it. Another test pins the command for revision 0 to the digest it had before this change, byte for byte, and checks that tuning changes nothing else in the pod.

A database moves to revision 1 when it restarts for a reason of its own:

  • you create it, or restore a backup into a new one
  • you resize it, and it picks up the new size's settings in the restart a resize already costs
  • we roll out a new postgres image, which restarts every database once anyway

Backups carry data and no settings, so a backup from an L restores into a new S and runs as an S.

What you do

New databases get their size's settings now. To move an existing one, resize it:

sh
gg resource add shop/db postgres --size m

An S you created before today keeps 100 connections. A new S gets 60, and so does an M or L you shrink to S. If you hold more than 60 connections, pool them or move to M.