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

ItemValue
Execution modelProcess model. One backend process per connection (fork)
Top-level processpostmaster: accepts connections, creates and monitors child processes
Maximum connectionsmax_connections, default 100. Of these, superuser_reserved_connections (default 3) is reserved for superusers. Changing it requires a restart
Shared memoryAllocated once at start. On Linux, anonymous mmap (shared_memory_type = mmap)
Buffer poolshared_buffers, default 128MB. Requires a restart
WAL bufferswal_buffers, default -1 = 1/32 of shared_buffers (minimum 64KB, maximum one WAL segment, 16MB)
Work memorywork_mem, default 4MB. This much per sort or hash operation. Hashes get up to hash_mem_multiplier (default 2) times that
Maintenance memorymaintenance_work_mem, default 64MB. VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY
Temporary table bufferstemp_buffers, default 8MB. Per session
Parallel querymax_parallel_workers_per_gather default 2, total max_parallel_workers default 8, background worker slots max_worker_processes default 8
Shared memory for parallel queryDynamic shared memory (dynamic_shared_memory_type, default posix on Linux). Created per query and released when it ends
Execution plan cacheNot 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.

  1. When the Client requests a connection (①), the postmaster receives it. The postmaster does not execute SQL; for each connection it creates one Backend process with fork (②) and hands over the connection. After that, the client and the backend process exchange SQL and results directly (③).
  2. The four processes in the Background processes box are created by the postmaster when the server starts. If a child process terminates abnormally, the postmaster ends all the other processes, rebuilds shared memory, and restarts from recovery, because one process may have corrupted shared memory.
  3. A backend process reads and modifies pages in shared_buffers in the Shared memory box, and appends a WAL record to the WAL buffers on every modification. At commit, the backend process itself writes the WAL buffers to the WAL files and calls fsync.
  4. The checkpointer and the background writer write dirty pages in shared_buffers to the Data files. The walwriter periodically writes WAL buffers not yet written to the file.
  5. The autovacuum launcher does not run VACUUM itself. As the dotted arrow shows, it asks the postmaster to start a worker process, and the worker processes one table at a time and then exits.

Process List

ProcessWhen it runsWhat it doesRelated settings (default)
postmasterAlwaysAccepts connections on the port (default 5432) and forks backends. Monitors and restarts child processesmax_connections (100)
Backend (client backend)Per connectionParse, plan, execute. Writes WAL at commitwork_mem (4MB)
startupAt start, continuously on a standby serverReplays WAL for recovery. Exits when done
checkpointerAlwaysWrites all dirty pages and calls fsync at a checkpoint. Also handles fsync requests handed over by backendscheckpoint_timeout (5 min), max_wal_size (1GB)
background writerAlwaysWrites ahead dirty pages that will soon be evicted between checkpoints. Reduces writes backends do themselvesbgwriter_delay (200ms)
walwriterAlwaysPeriodically writes WAL buffers to the file and calls fsync. Responsible for writing asynchronous commits (synchronous_commit = off)wal_writer_delay (200ms)
autovacuum launcherautovacuum = onWalks through databases and requests worker launchesautovacuum_naptime (1 min)
autovacuum workerWhen neededRuns VACUUM and ANALYZE on a tableautovacuum_max_workers (3)
logical replication launcherAlways (default setting)Starts apply workers if a subscription existsmax_logical_replication_workers (4)
Parallel workerPer parallel queryRuns a plan fragment handed over by the leader backend and exitsmax_parallel_workers_per_gather (2)
walsender / walreceiverWhen replicatingSends WAL to a standby server / receives WAL from the primarymax_wal_senders (10)
archiverarchive_mode = onCopies completed WAL segments to the archive locationarchive_command
WAL summarizersummarize_wal = on (since 17)Writes WAL summary files for incremental backup
loggerlogging_collector = onWrites 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_buffers takes most of it. WAL buffers hold WAL records not yet written to the file, SLRU buffers hold whether transactions committed (pg_xact) plus subtransaction and multixact information, and the Lock table and process array hold locks and the list of running transactions.
  • The four cells in the Local memory row are memory that one backend process uses alone. work_mem is 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 cache in the Operating system row is not memory PostgreSQL allocated. PostgreSQL reads and writes data files with buffered I/O, so pages not in shared_buffers are often found here (Operating System Cache).

Shared Memory Composition

RegionContentsSetting that sizes it
Buffer blocksThe 8KB pages themselvesshared_buffers
Buffer descriptors, mapping hashFor each buffer, which block of which file it holds, pin count, usage_count, dirty flagProportional to shared_buffers
WAL buffersWAL records not yet written to the filewal_buffers
SLRU bufferspg_xact (commit status), subtransactions, commit timestamps, multixacts, the NOTIFY queuetransaction_buffers, subtransaction_buffers, etc. (configurable since 17)
Lock tableHeavyweight 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 arrayThe running transaction ID of each process. Read when building a snapshotProportional to max_connections and others
Cumulative statisticsStatistics read by the pg_stat_* views (in shared memory since 15)Grows in dynamic shared memory with usage

Local Memory Composition

RegionContentsLimit
Work memorySorts, hash joins, hash aggregates, materialization (Materialize)work_mem per operation. Hashes use work_mem × hash_mem_multiplier
Maintenance memoryThe dead-row list of VACUUM, the sort of CREATE INDEXmaintenance_work_mem. autovacuum uses autovacuum_work_mem (default -1 = same value)
Temporary table buffersPages of the session's temporary tablestemp_buffers
Catalog cacheTable, column, and function definitions (relcache, catcache). Grows as used and stays until the connection endsNo limit
Plan cachePlans of prepared statements (PREPARE, extended protocol)No limit
Ring for large scansAn area inside shared_buffers that large sequential scans and VACUUM reuse in a circlevacuum_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.

  1. The Backend process that receives the UPDATE looks for the page in shared_buffers in Shared memory. If it is absent, it picks an empty buffer and reads the page in from the data file.
  2. 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.
  3. On COMMIT, the backend process writes the WAL buffer up to the commit record to the WAL file, calls fsync, and then responds to the client. If other backends commit at the same moment, they share the same fsync. With synchronous_commit = off, the backend responds without waiting and the walwriter writes later.
  4. The lower part marked with Note is separated from the commit in time. The checkpointer writes dirty pages to the Data file at 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).

ItemValue
Running processespostmaster, checkpointer, background writer, walwriter, autovacuum launcher, logical replication launcher, and a client backend per connection
Total shared memory279MB (shared_memory_size)
Of which buffer blocks256MB
WAL buffers (XLOG Ctl)About 8MB = 256MB ÷ 32
Buffer descriptors2MB
pg_xact buffers (transaction)About 1MB
CacheMemoryContext of a freshly connected backend1MB

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) and external merge Disk: … (temporary file) in EXPLAIN (ANALYZE). With log_temp_files = 0, statements that used temporary files are logged.
  • At the operating system level, ps -ef | grep postgres shows 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 (default try) to put shared memory on large pages and reduce the page table overhead.

Comparison with Other DBMSs

PostgreSQLMySQLOracleSQL ServerKDBS
One connectionProcessThreadProcess (dedicated server)Session. A worker per requestConnection inside a per-core reactor
Shared areaShared memoryProcess address spaceSGAProcess address spaceProcess address space
Work memorywork_mem (per operation)sort_buffer_size, etc. (session)PGAMemory grantsort_max_rows (row-count limit)
Execution plan sharingNone (per backend)NoneShared 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