Sub topic 8
Budgeting memory across connections
This chapter assumes you know the difference between shared_buffers and work_mem, can edit postgresql.conf and reload the server, and can read a simple EXPLAIN plan. Here you will combine the memory settings into one worst-case budget and use it to pick safe values for work_mem, maintenance_work_mem, and max_connections.
Why per-setting tuning fails
Every memory setting looks reasonable alone. work_mem = 64MB sounds small on a 64 GB server. The trouble is that PostgreSQL runs one operating system process per connection, and each process allocates its own private memory on top of the shared memory. The total depends on how many processes are busy and what they are doing.
The memory splits into two groups:
- Shared memory is allocated once at server start. It includes
shared_buffers, WAL buffers, and lock tables. Its size does not depend on load. - Private memory is allocated by each backend as it works. It includes sort and hash memory,
temp_buffers, catalog and plan caches, and maintenance operations. It grows with concurrency and query complexity.
Capacity planning mostly means bounding the private part.
The pieces of the budget
work_mem is per node, not per connection
work_mem is the memory limit for one sort or hash operation inside a query plan. A single query can contain several such nodes, and they can all be active at once. A plan with a hash join, a sort for ORDER BY, and a hash aggregate can use up to three times work_mem.
Hash-based nodes get a larger limit: work_mem * hash_mem_multiplier. The default multiplier is 2.0 in PostgreSQL 15 and later (1.0 in earlier versions). With work_mem = 32MB, one hash node may use 64MB.
Parallel queries multiply this again. Each parallel worker is a separate process with its own work_mem for each node, so a plan with a Gather node and 2 workers can use about three times the memory of the same plan run serially. With Parallel Hash, the shared hash table limit scales with the number of participating processes.
maintenance_work_mem and autovacuum
maintenance_work_mem applies to VACUUM, CREATE INDEX, and ALTER TABLE ADD FOREIGN KEY. Autovacuum workers use autovacuum_work_mem if you set it. Otherwise they use maintenance_work_mem. Several can run at once, up to autovacuum_max_workers (default 3), plus any manual VACUUM or index build a person starts. Parallel index builds and parallel vacuum add further workers, each using this much memory.
Values here can be much larger than work_mem, such as 512MB or 1GB, because few such operations run concurrently. Budget them as a count of concurrent jobs, not as a per-connection cost.
Fixed overhead per backend
Each backend also holds memory that you cannot set with one parameter:
- Catalog and relation caches, which grow as the session touches more tables, indexes, and functions.
- Cached plans for prepared statements.
temp_buffers(default 8MB), which is allocated only when the session first uses temporary tables, and then up to that limit.
A lightly used backend might take a few MB. A long-lived session that touches thousands of partitions can take far more. Treat 5 to 10 MB per connection as a rough starting assumption and replace it with a measurement.
The worst-case formula
A conservative upper bound looks like this:
total = shared_buffers
+ max_connections * (work_mem * nodes_per_query * parallel_factor + per_backend_overhead)
+ maintenance_work_mem * concurrent_maintenance_jobs
+ headroom for the OS and page cachenodes_per_query is how many memory-hungry nodes a typical heavy query has. Four is a reasonable planning number. parallel_factor is 1 if you do not use parallel query. Otherwise it is closer to the number of participants.
A worked example
Take a 64 GB dedicated server with these settings:
| Component | Value | Worst-case memory |
|---|---|---|
| shared_buffers | 16GB | 16 GB |
| max_connections | 200 | |
| work_mem | 32MB, 4 nodes per query | 200 x 32MB x 4 = 25 GB |
| Per-backend overhead | about 10MB | 200 x 10MB = 2 GB |
| maintenance_work_mem | 1GB, 3 autovacuum workers + 1 manual job | 4 GB |
| Total | about 47 GB |
That leaves about 17 GB for the operating system and its page cache. This is tight but workable, because the page cache is what effective_cache_size assumes is available. If you raised work_mem to 128MB, the middle line would become 100 GB, and the server could exceed physical RAM if enough connections ran heavy queries at once.
The worst case rarely happens. Most connections are idle at any moment, and few queries use four spilling nodes. The budget is a safety limit, not a prediction. If your workload makes the worst case plausible (for example, hundreds of connections all running reports at the same time), the budget is the thing that prevents an outage.
Computing the budget in SQL
This query reads your live settings and applies the formula. The nodes, overhead, and maint_jobs values are assumptions you change. Casting to bigint avoids integer overflow on large products.
WITH s AS (
SELECT pg_size_bytes(current_setting('shared_buffers'))::bigint AS shared_buffers,
pg_size_bytes(current_setting('work_mem'))::bigint AS work_mem,
pg_size_bytes(current_setting('maintenance_work_mem'))::bigint AS maintenance_work_mem,
current_setting('max_connections')::bigint AS max_connections,
current_setting('autovacuum_max_workers')::bigint + 1 AS maint_jobs,
4::bigint AS nodes,
pg_size_bytes('10MB')::bigint AS overhead
)
SELECT pg_size_pretty(shared_buffers) AS shared,
pg_size_pretty(max_connections * (work_mem * nodes + overhead)) AS per_connection_worst_case,
pg_size_pretty(maintenance_work_mem * maint_jobs) AS maintenance_worst_case,
pg_size_pretty(shared_buffers
+ max_connections * (work_mem * nodes + overhead)
+ maintenance_work_mem * maint_jobs) AS total_worst_case
FROM s;Compare total_worst_case with physical RAM, then subtract at least 20 to 25 percent for the OS and page cache. On a dedicated database server, a total worst case above about 75 to 80 percent of RAM is a warning sign.
Measuring real per-backend memory
The formula uses an assumed overhead, so check it. PostgreSQL 14 and later expose memory contexts for your own session:
SELECT name, pg_size_pretty(sum(total_bytes)) AS total
FROM pg_backend_memory_contexts
GROUP BY name
ORDER BY sum(total_bytes) DESC
LIMIT 5;To inspect another backend, call pg_log_backend_memory_contexts(pid). It writes that backend's memory contexts to the server log. You can also compare the resident memory of postgres processes in the OS, but shared buffer pages are counted in each process, so the numbers overcount. Prefer proportional set size (PSS) where your OS provides it.
Reducing the risk without starving queries
Keep the global work_mem modest and raise it only where needed. The two main tools are role-level and transaction-level settings:
ALTER ROLE reporting SET work_mem = '256MB';BEGIN;
SET LOCAL work_mem = '512MB';
-- run the one heavy report here
COMMIT;SET LOCAL lasts until the end of the transaction, so a pooled connection does not carry the large value into the next client's work.
For the remaining knobs:
- Lower
max_connectionsand use a pooler. A pooler such as PgBouncer in transaction mode lets thousands of clients share a few dozen server connections. The budget multiplies by active connections, so 40 server connections atwork_mem = 64MBis far safer than 400. - Cap role concurrency.
ALTER ROLE reporting CONNECTION LIMIT 5bounds how many heavy sessions the largework_memcan apply to. - Limit parallelism.
max_parallel_workers_per_gatherdirectly scales the per-query multiplier. - Keep maintenance jobs separate. Run big
CREATE INDEXjobs off-peak, or setmaintenance_work_memin the session that runs them instead of globally.
Verifying that the budget fits
Checking the budget does not stop at arithmetic. After you choose values, confirm them against real behavior:
- Set
log_temp_files = 0and watch whether queries still spill. If they do, find out which nodes spill before raisingwork_memglobally. - Check
pg_stat_database.temp_filesandtemp_bytesover a day of normal load. - Watch free memory and swap usage on the host during peak load. If page cache shrinks sharply when reports run, the budget is too aggressive.
- Re-run the budget query after any change to
max_connections,work_mem,hash_mem_multiplier, or parallel settings.
Exercise
A server has 32 GB of RAM, sharedbuffers = 8GB, maxconnections = 300, workmem = 64MB, hashmemmultiplier = 2.0, and maintenanceworkmem = 1GB with autovacuummax_workers = 3. Assume 3 memory-hungry nodes per heavy query, 10MB overhead per backend, and one manual maintenance job. Is this configuration safe, and what is the best first change?
Show answer
Per-connection worst case is 300 x (64MB x 3 + 10MB) = 300 x 202MB = about 59 GB, even before counting hash nodes at 128MB each. Maintenance adds 1GB x 4 jobs = 4 GB and sharedbuffers adds 8 GB, for a total of about 71 GB on a 32 GB machine. The worst case far exceeds RAM, so it is not safe if many connections run heavy queries at once. The best first change is to cut the number of active server connections with a pooler (for example 50 active connections instead of 300) and set workmem lower globally, such as 16MB. Then grant higher workmem to specific roles or transactions that need it. Check logtempfiles and pgstat_database to see whether the lower value causes meaningful spills.
Exercise
Why does adding up the RES column for every postgres process in top overstate memory use?
Show answer
Each backend's resident size includes the pages of shared memory (such as sharedbuffers) that it has touched. Those pages are counted once per process but exist only once in RAM. Use PSS, or compute budgets from settings and pgbackendmemorycontexts instead.