Sub topic 1
Where PostgreSQL uses memory
PostgreSQL does not have one memory pool. It has one large block of shared memory that every process can read and write, plus private memory inside each server process, plus the operating system's file cache, which sits outside PostgreSQL but affects it heavily. Knowing which setting controls which area is the first step in tuning. Most tuning mistakes come from treating a per-operation setting as if it were a global limit.
Prerequisites
This chapter assumes you can:
- Run queries in psql and read a simple
EXPLAINplan. - Edit
postgresql.confand know the difference between reloading and restarting the server. - Explain at a basic level what RAM, disk, and the operating system file cache are.
Later chapters cover each setting in depth. This chapter gives you the map.
The process model
PostgreSQL uses one operating system process per client connection. The main process, the postmaster, starts at boot and listens for connections. For each new connection it forks a backend process. It also starts helper processes such as the checkpointer, the background writer, the WAL writer, and autovacuum workers.
This design leads to the main division of memory:
- Shared memory is allocated once at server start. All processes attach to it.
- Local (per-process) memory is allocated by each backend or helper as it needs it. Other processes cannot see it.
The diagram shows how the areas relate.
Shared memory areas
The settings in this group take effect at server start. Changing them requires a restart.
Shared buffers
shared_buffers is PostgreSQL's own cache of table and index pages. Each page is 8 kB by default. When a backend needs a page, it looks in shared buffers first. If the page is missing, the backend reads it from the operating system, which may serve it from its own cache or go to disk. Modified pages stay in shared buffers as "dirty" pages until a checkpoint or the background writer flushes them.
The default is 128 MB, which is small for a production server. Choosing a better value is covered in the chapter on sizing shared_buffers.
WAL buffers
The write-ahead log (WAL) records every change before the data pages are written. wal_buffers holds WAL records in memory until they are flushed to disk. The default of -1 sizes it automatically to about 1/32 of shared_buffers, capped at one WAL segment (16 MB by default). It rarely needs manual tuning.
Other shared structures
Shared memory also holds the lock tables, the list of active processes, and caches for transaction commit status. Their size follows settings such as max_connections and max_locks_per_transaction. Raising max_connections makes the shared memory request larger even when no extra sessions are connected.
Per-process memory areas
These areas are allocated only when a process needs them. Most can be changed per session, per role, or per database without a restart.
work_mem
work_mem is the memory a single query operation may use before it spills to temporary files. The default is 4 MB. Operations that use it include:
- Sorts (
ORDER BY, merge joins,DISTINCT) - Hash tables (hash joins, hash aggregates)
- Some other nodes, such as memoize
The limit applies per operation, not per query and not per connection. A query with three sorts and two hash joins can use up to five times work_mem. Parallel query makes this worse, because each parallel worker gets its own allowance. A hash operation may be allowed more than work_mem through hash_mem_multiplier, which is covered in a later chapter.
maintenance_work_mem
maintenance_work_mem is used by maintenance commands: VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY, and similar. The default is 64 MB. Autovacuum workers use it too, unless autovacuum_work_mem is set. Because up to autovacuum_max_workers (default 3) workers can run at once, the total can be several times this value.
temp_buffers
temp_buffers is a per-session buffer for temporary tables. The default is 8 MB. It is only allocated in sessions that touch temporary tables, and it cannot be changed after the session has used one.
Backend caches
Each backend keeps its own caches of catalog information (table definitions, types, functions) and prepared statement plans. These grow with the number of distinct objects a long-lived connection touches. They are usually small, but with thousands of tables or partitions and many long-lived connections they can add up. This memory has no dedicated setting.
The operating system page cache
PostgreSQL reads and writes data files through the operating system. The OS keeps recently used file blocks in free RAM, the page cache. This means a page may exist twice: once in shared_buffers and once in the OS cache. That is called double buffering, and it is normal.
Two consequences matter for tuning:
- A block counted as a "read" by PostgreSQL may still have been served from the OS cache, not the disk.
- Giving all RAM to
shared_buffersis a mistake. The OS cache is a large part of PostgreSQL's effective caching, and the planner is told about it througheffective_cache_size, which allocates nothing. It is only a hint for cost estimates.
Summary of settings by context
Each setting has a context that says how it can be changed. The common ones:
| Area | Setting | Default | Scope | Change requires |
|---|---|---|---|---|
| Shared | `shared_buffers` | 128 MB | Whole server | Restart |
| Shared | `wal_buffers` | -1 (auto) | Whole server | Restart |
| Shared | `max_connections` | 100 | Whole server | Restart |
| Per operation | `work_mem` | 4 MB | Session, role, database, server | Reload or `SET` |
| Per maintenance command | `maintenance_work_mem` | 64 MB | Session, role, database, server | Reload or `SET` |
| Per session | `temp_buffers` | 8 MB | Session | `SET` before first temp table use |
| Planner only | `effective_cache_size` | 4 GB | Session, server | Reload or `SET` |
Inspecting the current configuration
The pg_settings view shows each value and its context. The context column reads postmaster for settings that need a restart, sighup for settings that need a reload, and user for settings any session can change. The pending_restart column is true when a changed value is waiting for a restart.
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem',
'effective_cache_size', 'max_wal_size', 'checkpoint_timeout',
'random_page_cost', 'max_connections');Note the unit column. For shared_buffers, setting is a count of 8 kB blocks, not bytes. To read values in a friendlier form, use SHOW shared_buffers; or current_setting('shared_buffers').
Looking at actual allocations
On PostgreSQL 13 and later, a superuser or a member of pg_read_all_stats can see how the shared memory is divided:
SELECT name, pg_size_pretty(allocated_size) AS size
FROM pg_shmem_allocations
ORDER BY allocated_size DESC
LIMIT 10;The Buffer Blocks row is shared_buffers. On PostgreSQL 14 and later, a session can inspect its own private memory:
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;This shows how much the current backend holds in catalog caches, plan caches, and similar structures.
A worst-case estimate
Because work_mem is per operation, memory use cannot be read off one number. A rough upper bound is:
shared_buffers
+ max_connections × (work_mem × memory-hungry nodes per query)
+ maintenance_work_mem × concurrent maintenance jobs
+ OS and page cache headroomReal servers rarely reach the worst case, because not every connection runs a heavy query at once. But the formula explains why raising work_mem globally to 256 MB on a server with 500 connections can trigger the out-of-memory killer. A later chapter on budgeting memory across connections turns this into a procedure.
Common mistakes
- Treating
work_memas per connection. It is per sort or hash node, and parallel workers multiply it. - Setting
shared_buffersto most of RAM. This starves the OS cache and leaves no room for backends. - Expecting a reload to apply
shared_buffers. Thepending_restartcolumn tells you when a change is waiting. - Tuning from hit ratios alone. A high shared buffers hit ratio does not say whether blocks counted as reads came from disk or the OS cache.
Exercises
Exercise
A server has work_mem = 64MB and max_connections = 200. A developer says the most memory the queries can use is 200 × 64 MB = 12.8 GB. Why can this estimate be too low?
Show answer
work_mem applies to each sort or hash operation, not each connection. One query can contain several such operations, and parallel workers each get their own allowance. Actual worst-case usage can be a multiple of 12.8 GB. Maintenance jobs and autovacuum workers add their own maintenance_work_mem on top.
Exercise
You run ALTER SYSTEM SET shared_buffers = '4GB'; and SELECT pg_reload_conf();, but SHOW shared_buffers; still returns the old value. What do you check in pg_settings, and what do you do next?
Show answer
Check the context column, which is postmaster for shared_buffers, and the pending_restart column, which should be true. The setting only takes effect after a full server restart, so restart PostgreSQL and run SHOW shared_buffers; again.