PostgreSQL Memory and Process Architecture
A PostgreSQL server (instance) consists of several operating system processes and one block of shared memory they use together. It does not use threads. One client connection is one backend process, while work such as writing dirty pages, writing WAL, and VACUUM is done by background processes that run separately. Memory is divided into shared memory, whose size is fixed when the server starts, and local memory, which each process allocates when needed and returns.
Key Specs
| Item | Value |
|---|---|
| Execution model | Process model. One backend process per connection (fork) |
| Top-level process | postmaster: accepts connections, creates and monitors child processes |
| Maximum connections | max_connections, default 100. Of these, superuser_reserved_connections (default 3) is reserved for superusers. Changing it requires a restart |
| Shared memory | Allocated once at start. On Linux, anonymous mmap (shared_memory_type = mmap) |
| Buffer pool | shared_buffers, default 128MB. Requires a restart |
| WAL buffers | wal_buffers, default -1 = 1/32 of shared_buffers (minimum 64KB, maximum one WAL segment, 16MB) |
| Work memory | work_mem, default 4MB. This much per sort or hash operation. Hashes get up to hash_mem_multiplier (default 2) times that |
| Maintenance memory | maintenance_work_mem, default 64MB. VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY |
| Temporary table buffers | temp_buffers, default 8MB. Per session |
| Parallel query | max_parallel_workers_per_gather default 2, total max_parallel_workers default 8, background worker slots max_worker_processes default 8 |
| Shared memory for parallel query | Dynamic shared memory (dynamic_shared_memory_type, default posix on Linux). Created per query and released when it ends |
| Execution plan cache | Not shared. The plan of a prepared statement exists only inside that backend |
Process Architecture
Figure. postmaster and child processes
flowchart TB
CL["Client"] -->|"① Connection request"| PM["postmaster<br/>accepts connections, monitors child processes"]
PM -->|"② fork"| BE["Backend process<br/>one per connection"]
CL -->|"③ SQL and results"| BE
PM -->|"fork at server start"| BG
subgraph BG ["Background processes"]
CK["checkpointer"]
BW["background writer"]
WW["walwriter"]
AL["autovacuum launcher"]
end
subgraph SHM ["Shared memory"]
SB["shared_buffers"]
WB["WAL buffers"]
end
subgraph DISK ["Disk"]
DF["Data files"]
WF["WAL files"]
end
BE -->|"Read and modify pages"| SB
BE -->|"Append WAL records"| WB
BE -->|"Write WAL at commit"| WF
CK -->|"Write dirty pages"| DF
BW -->|"Write dirty pages"| DF
WW -->|"Write WAL buffers"| WF
AL -.->|"Request to run a worker"| PM
Diagram notes: From top to bottom the order is processes, shared memory, disk.
- When the
Clientrequests a connection (①), thepostmasterreceives it. Thepostmasterdoes not execute SQL; for each connection it creates oneBackend processwithfork(②) and hands over the connection. After that, the client and the backend process exchange SQL and results directly (③). - The four processes in the
Background processesbox are created by thepostmasterwhen the server starts. If a child process terminates abnormally, thepostmasterends all the other processes, rebuilds shared memory, and restarts from recovery, because one process may have corrupted shared memory. - A backend process reads and modifies pages in
shared_buffersin theShared memorybox, and appends a WAL record to theWAL bufferson every modification. At commit, the backend process itself writes the WAL buffers to theWAL filesand callsfsync. - The
checkpointerand thebackground writerwrite dirty pages inshared_buffersto theData files. Thewalwriterperiodically writes WAL buffers not yet written to the file. - The
autovacuum launcherdoes not runVACUUMitself. As the dotted arrow shows, it asks thepostmasterto start a worker process, and the worker processes one table at a time and then exits.
Process List
| Process | When it runs | What it does | Related settings (default) |
|---|---|---|---|
postmaster | Always | Accepts connections on the port (default 5432) and forks backends. Monitors and restarts child processes | max_connections (100) |
| Backend (client backend) | Per connection | Parse, plan, execute. Writes WAL at commit | work_mem (4MB) |
| startup | At start, continuously on a standby server | Replays WAL for recovery. Exits when done | |
| checkpointer | Always | Writes all dirty pages and calls fsync at a checkpoint. Also handles fsync requests handed over by backends | checkpoint_timeout (5 min), max_wal_size (1GB) |
| background writer | Always | Writes ahead dirty pages that will soon be evicted between checkpoints. Reduces writes backends do themselves | bgwriter_delay (200ms) |
| walwriter | Always | Periodically writes WAL buffers to the file and calls fsync. Responsible for writing asynchronous commits (synchronous_commit = off) | wal_writer_delay (200ms) |
| autovacuum launcher | autovacuum = on | Walks through databases and requests worker launches | autovacuum_naptime (1 min) |
| autovacuum worker | When needed | Runs VACUUM and ANALYZE on a table | autovacuum_max_workers (3) |
| logical replication launcher | Always (default setting) | Starts apply workers if a subscription exists | max_logical_replication_workers (4) |
| Parallel worker | Per parallel query | Runs a plan fragment handed over by the leader backend and exits | max_parallel_workers_per_gather (2) |
| walsender / walreceiver | When replicating | Sends WAL to a standby server / receives WAL from the primary | max_wal_senders (10) |
| archiver | archive_mode = on | Copies completed WAL segments to the archive location | archive_command |
| WAL summarizer | summarize_wal = on (since 17) | Writes WAL summary files for incremental backup | |
| logger | logging_collector = on | Writes log output from other processes to a file |
Connection cost. Each connection creates a process, and that process fills its catalog cache from scratch. Even an idle connection holds one process and its cache memory. So a service that opens and closes connections often or keeps thousands of them puts a connection pooler such as PgBouncer in front and keeps max_connections small.
Parallel query. The leader backend asks the postmaster for workers and exchanges the plan and tuples through dynamic shared memory segments. Each worker also uses its own work_mem.
Memory Architecture
Figure. Shared memory and local memory
block-beta
columns 6
t1["Shared memory: used by all processes together, size fixed at server start"]:6
sb["shared_buffers<br/>data and index pages"]:3 wb["WAL buffers<br/>wal_buffers"] sl["SLRU buffers<br/>commit status"] lk["Lock table<br/>process array"]
t2["Local memory: separate per process, allocated when needed"]:6
wm["work_mem<br/>per sort or hash operation"]:2 mw["maintenance_work_mem<br/>VACUUM, CREATE INDEX"]:2 tb["temp_buffers<br/>temporary tables"] cc["Catalog cache<br/>plan cache"]
t3["Operating system"]:6
oc["Page cache: data files and WAL files are read and written with buffered I/O"]:6
class t1,t2,t3 plain
class sb data
class wb hot
class sl,lk meta
class wm,mw,tb,cc slot
class oc muted
Diagram notes: Read it as three layers.
- The four cells in the Shared memory row are allocated once at server start, and their size does not change while running.
shared_bufferstakes most of it.WAL buffershold WAL records not yet written to the file,SLRU buffershold whether transactions committed (pg_xact) plus subtransaction and multixact information, and theLock tableandprocess arrayhold locks and the list of running transactions. - The four cells in the Local memory row are memory that one backend process uses alone.
work_memis not a limit per process but a limit per sort or hash operation, so a query with two sorts and one hash join can use three times that or more. An operation that exceeds the limit spills to temporary files. - The
Page cachein the Operating system row is not memory PostgreSQL allocated. PostgreSQL reads and writes data files with buffered I/O, so pages not inshared_buffersare often found here (Operating System Cache).
Shared Memory Composition
| Region | Contents | Setting that sizes it |
|---|---|---|
| Buffer blocks | The 8KB pages themselves | shared_buffers |
| Buffer descriptors, mapping hash | For each buffer, which block of which file it holds, pin count, usage_count, dirty flag | Proportional to shared_buffers |
| WAL buffers | WAL records not yet written to the file | wal_buffers |
| SLRU buffers | pg_xact (commit status), subtransactions, commit timestamps, multixacts, the NOTIFY queue | transaction_buffers, subtransaction_buffers, etc. (configurable since 17) |
| Lock table | Heavyweight locks, including table locks. Row locks are recorded in the row header, not here (Locks) | max_locks_per_transaction (64) × (max_connections + max_prepared_transactions) |
| Process array | The running transaction ID of each process. Read when building a snapshot | Proportional to max_connections and others |
| Cumulative statistics | Statistics read by the pg_stat_* views (in shared memory since 15) | Grows in dynamic shared memory with usage |
Local Memory Composition
| Region | Contents | Limit |
|---|---|---|
| Work memory | Sorts, hash joins, hash aggregates, materialization (Materialize) | work_mem per operation. Hashes use work_mem × hash_mem_multiplier |
| Maintenance memory | The dead-row list of VACUUM, the sort of CREATE INDEX | maintenance_work_mem. autovacuum uses autovacuum_work_mem (default -1 = same value) |
| Temporary table buffers | Pages of the session's temporary tables | temp_buffers |
| Catalog cache | Table, column, and function definitions (relcache, catcache). Grows as used and stays until the connection ends | No limit |
| Plan cache | Plans of prepared statements (PREPARE, extended protocol) | No limit |
| Ring for large scans | An area inside shared_buffers that large sequential scans and VACUUM reuse in a circle | vacuum_buffer_usage_limit (2MB), etc. |
PostgreSQL manages memory in units of memory contexts. When a query ends, its context is released as a whole, so memory does not leak between queries. CacheMemoryContext (the catalog cache), on the other hand, stays until the connection ends, so a connection attached for a long time to a database with tens of thousands of tables can grow to several hundred MB.
Estimating Memory Size
The upper bound of the memory the server can use is roughly the following sum.
shared memory (shared_buffers + WAL buffers + a few % for the rest)
+ number of connections × (process baseline of a few MB + catalog cache)
+ number of concurrently running sort and hash operations × work_mem
+ autovacuum_max_workers × maintenance_work_mem
work_mem has no limit that bounds the total. With work_mem = 64MB, if 200 connections run queries with two sorts each at the same time, the worst case needs 25GB. So keep work_mem small globally and raise it with SET work_mem only in the sessions or transactions that need a large value.
The Path of One Statement
Figure. Processes an UPDATE and COMMIT pass through
sequenceDiagram
participant C as Client
participant B as Backend process
participant M as Shared memory
participant W as WAL file
participant K as checkpointer
participant D as Data file
C->>B: UPDATE
B->>M: Find the page in shared_buffers, read it from the data file if absent
B->>M: Append a record to the WAL buffer
B->>M: Modify the page, mark it dirty
C->>B: COMMIT
B->>W: Write the WAL buffer and fsync
B-->>C: Commit complete
Note over K,D: From here on, later and independent of the commit
K->>M: Collect dirty pages
K->>D: Write pages and fsync
Diagram notes: Time flows from top to bottom.
- The
Backend processthat receives theUPDATElooks for the page inshared_buffersinShared memory. If it is absent, it picks an empty buffer and reads the page in from the data file. - It builds the change as a WAL record and appends it to the WAL buffer, then modifies the page and marks it dirty. At this point nothing has been written to disk.
- On
COMMIT, the backend process writes the WAL buffer up to the commit record to theWAL file, callsfsync, and then responds to the client. If other backends commit at the same moment, they share the samefsync. Withsynchronous_commit = off, the backend responds without waiting and thewalwriterwrites later. - The lower part marked with
Noteis separated from the commit in time. Thecheckpointerwrites dirty pages to theData fileat a checkpoint. Even if the server dies before that, the record is in the WAL file, so the startup process applies it again (WAL).
In the Sandbox
Values seen in this site's PostgreSQL sandbox (17.12, started with shared_buffers = 256MB).
| Item | Value |
|---|---|
| Running processes | postmaster, checkpointer, background writer, walwriter, autovacuum launcher, logical replication launcher, and a client backend per connection |
| Total shared memory | 279MB (shared_memory_size) |
| Of which buffer blocks | 256MB |
WAL buffers (XLOG Ctl) | About 8MB = 256MB ÷ 32 |
| Buffer descriptors | 2MB |
pg_xact buffers (transaction) | About 1MB |
CacheMemoryContext of a freshly connected backend | 1MB |
Shared memory outside shared_buffers is 23MB, about 8% of the total.
Configuration and Checks
-- Running processes and their types
SELECT pid, backend_type, state, wait_event_type, wait_event
FROM pg_stat_activity ORDER BY backend_start;
-- Who uses how much shared memory (since 13, superuser or pg_read_all_stats)
SELECT name, pg_size_pretty(allocated_size) AS size
FROM pg_shmem_allocations ORDER BY allocated_size DESC LIMIT 10;
SHOW shared_memory_size; -- since 15
-- Local memory of this backend (since 14)
SELECT name, pg_size_pretty(total_bytes) AS total
FROM pg_backend_memory_contexts ORDER BY total_bytes DESC LIMIT 10;
-- Memory settings and what is needed to change them (context: postmaster = restart)
SELECT name, setting, unit, context FROM pg_settings
WHERE name IN ('shared_buffers', 'wal_buffers', 'work_mem', 'maintenance_work_mem',
'temp_buffers', 'max_connections', 'autovacuum_max_workers', 'max_worker_processes');
- Whether a sort finished in memory is shown by
Sort Method: quicksort Memory: …(memory) andexternal merge Disk: …(temporary file) inEXPLAIN (ANALYZE). Withlog_temp_files = 0, statements that used temporary files are logged. - At the operating system level,
ps -ef | grep postgresshows the process names as they are (postgres: checkpointer, etc.). A process's RSS includes the shared memory that process touched, so summing all RSS values gives a figure much larger than the real usage. - With large memory, use
huge_pages(defaulttry) to put shared memory on large pages and reduce the page table overhead.
Comparison with Other DBMSs
| PostgreSQL | MySQL | Oracle | SQL Server | KDBS | |
|---|---|---|---|---|---|
| One connection | Process | Thread | Process (dedicated server) | Session. A worker per request | Connection inside a per-core reactor |
| Shared area | Shared memory | Process address space | SGA | Process address space | Process address space |
| Work memory | work_mem (per operation) | sort_buffer_size, etc. (session) | PGA | Memory grant | sort_max_rows (row-count limit) |
| Execution plan sharing | None (per backend) | None | Shared pool (all sessions) | Plan cache (all sessions) | None (compiled per statement) |
The full comparison is in DBMS Architecture at a Glance.
In the Articles
NOTE Defaults are for PostgreSQL 17 and can vary with the version. From 18, I/O worker processes for asynchronous I/O (
io_method,io_workers) also start.
Related pages
- DBMS Architecture at a Glance
- PostgreSQL
- PostgreSQL connections, cursors, and SQL cache
- shared_buffers
- PostgreSQL WAL
- VACUUM
- synchronous_commit
- Operating system cache and direct I/O
- MySQL memory and thread structure
- Oracle memory and process structure
- SQL Server Memory and Thread Structure
- KDBS Memory and Thread Architecture