PostgreSQL Architecture Fundamentals
Table of Contents
1. Introduction β Instance, Port and Process-per-Connection
To work effectively with PostgreSQL, it is important to understand how it is built and how its different parts work together.
- PostgreSQL follows a process-per-user client/server model. Every time a client connects, PostgreSQL creates a separate backend process for that connection. It stays active until the client disconnects.
- A group of memory structures and background processes working together is called an instance.
- One server can run multiple instances. Each instance is independent: memory and processes are never shared between instances.
- Client applications connect to an instance to read or write data.
- The default port is 5432. It can be changed during installation or with the
port parameter in postgresql.conf. A change of port needs a restart.
Remember: PostgreSQL memory is divided into two groups. Shared memory is one area for the whole instance (shared buffers, WAL buffers, CLOG buffers, lock memory). Local memory is private to each process (work_mem, maintenance_work_mem, temp_buffers). Roughly, shared memory is like Oracle's SGA and local memory is like Oracle's PGA.
2. Architecture at a Glance
PostgreSQL Data Flow
PostgreSQL Architecture
PostgreSQL Startup Sequence
3. Process Architecture β Postmaster and Backend
3.1 Postmaster Process
The
Postmaster is the
first process that starts and the
parent of every other PostgreSQL process. Key responsibilities:
- Supervisor β monitors the child processes and restarts the background processes if one fails. If a process crashes, the postmaster resets shared memory and runs crash recovery.
- Listens for new client connections on port 5432.
- For each new connection, it forks a dedicated backend process.
- Starts the background processes at server startup.
Important: The postmaster does not run queries and does not itself check passwords. After the fork, the new backend process performs authentication using pg_hba.conf and checks that the user may connect to the requested database. This keeps the postmaster small and stable.
To check the postmaster and the other PostgreSQL processes:
[postgres@pgdb02 ~]$ ps -ef | grep postgres
root 4366 3019 0 20:50 pts/0 00:00:00 su - postgres
postgres 4367 4366 0 20:50 pts/0 00:00:00 -bash
postgres 4559 1 0 21:32 ? 00:00:00 /usr/pgsql-17/bin/postgres -D /pgData/pgsql17/data
postgres 4560 4559 0 21:32 ? 00:00:00 postgres: logger
postgres 4561 4559 0 21:32 ? 00:00:00 postgres: checkpointer
postgres 4562 4559 0 21:32 ? 00:00:00 postgres: background writer
postgres 4564 4559 0 21:32 ? 00:00:00 postgres: walwriter
postgres 4565 4559 0 21:32 ? 00:00:00 postgres: autovacuum launcher
postgres 4566 4559 0 21:32 ? 00:00:00 postgres: logical replication launcher
postgres 4568 4367 0 21:33 pts/0 00:00:00 ps -ef
postgres 4569 4367 0 21:33 pts/0 00:00:00 grep --color=auto postgres
[postgres@pgdb02 ~]$
[postgres@pgdb02 ~]$ pstree -p 4559
postgres(4559)ββ¬βpostgres(4560) ----- postgres: logger
ββpostgres(4561) ----- postgres: checkpointer
ββpostgres(4562) ----- postgres: background writer
ββpostgres(4564) ----- postgres: walwriter
ββpostgres(4565) ----- postgres: autovacuum launcher
ββpostgres(4566) ----- postgres: logical replication launcher
[postgres@pgdb02 ~]$
The same list is available from SQL. The
backend_type column shows the role of each process:
postgres=# SELECT pid, backend_type FROM pg_stat_activity ORDER BY backend_type;
3.2 Dedicated Backend Process
When a client connects, the postmaster creates a
dedicated backend process for that connection (shown as
client backend). Key points:
- There is one backend process per client connection. The number is limited by
max_connections (default 100).
- It handles the full lifecycle of the session: parses the SQL, creates the execution plan, executes it and returns the results.
- It reads and changes data pages in shared memory and uses its own private (local) memory for sorts, hashes and temporary tables.
- It ends automatically when the client disconnects.
Note: Because each connection is a full OS process, thousands of direct connections are expensive. Use a connection pooler such as PgBouncer when you need many clients.
4. Background Processes
PostgreSQL runs several background processes to manage data, memory, logging and maintenance. Each one has one job.
4.1 Background Writer (bgwriter)
| Point |
In simple words |
| What it does |
Saves some dirty pages to the data files ahead of time. A dirty page is a page that was changed in memory but not yet written to disk. |
| When it runs |
Wakes up every bgwriter_delay (default 200 ms). |
| How much it writes |
At most bgwriter_lru_maxpages pages per round (default 100), mostly pages that will be reused soon. |
| What it does NOT do |
It does not write every dirty page. Writing all of them is the job of the Checkpointer. |
| Why it is needed |
Keeps clean buffers ready so queries do not wait for free space, and spreads disk writes over time to avoid sudden I/O spikes. |
4.2 WAL Writer
| Point |
In simple words |
| What it does |
Copies WAL (Write-Ahead Log) records from the WAL buffers (memory) to the WAL files in pg_wal (disk). WAL is the record of every change. |
| When it runs (timer) |
Wakes up every wal_writer_delay (default 200 ms) and flushes the WAL buffers. |
| When it runs (size) |
Also flushes when more than wal_writer_flush_after (default 1 MB) of WAL was written since the last flush. |
| At COMMIT |
With synchronous_commit = on, the backend itself flushes the WAL up to its commit record and waits until it is on disk. A backend also writes WAL itself when the WAL buffers are full. |
| Are uncommitted changes written to WAL? |
Yes. WAL records are created as soon as you change data, before COMMIT, and they can reach disk before you commit. COMMIT only forces the flush and adds a commit record. After a crash, changes without a commit record are not kept. See the post Are Uncommitted Transactions Also Written to WAL? |
| Why it is needed |
Durability: WAL must be on disk before a commit is confirmed. Rule: "Write WAL first, then write the data files." |
Try it: Inside an open transaction, WAL that is still in the buffers is flushed by the WAL Writer even before you commit. Watch the gap between the insert position and the flush position close by itself:
postgres=# BEGIN;
postgres=*# INSERT INTO wal_demo (fname) VALUES ('walwriter test');
postgres=*# SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), pg_current_wal_flush_lsn()) AS bytes_not_flushed;
postgres=*# SELECT pg_sleep(1);
postgres=*# SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(), pg_current_wal_flush_lsn()) AS bytes_not_flushed;
postgres=*# ROLLBACK;
After one second the number is close to zero, without any COMMIT. For a full hands-on proof that even uncommitted changes are written to the WAL, see the companion post
Are Uncommitted Transactions Also Written to WAL?
4.3 Checkpointer
| Point |
In simple words |
| What it does |
Creates a safe recovery point. |
| Step 1 |
Writes all dirty pages to disk. Every changed page in shared buffers goes to the data files, spread over time (checkpoint_completion_target, default 0.9). |
| Step 2 |
Writes a checkpoint record into the WAL. |
| Step 3 |
Updates the control file (global/pg_control) with the location (LSN β Log Sequence Number) of that checkpoint record. |
| After a crash |
PostgreSQL reads the control file, finds the last checkpoint and replays the WAL from that point to recover all committed data. |
| Why it is needed |
Makes crash recovery short, gives a known and consistent starting point, and lets old WAL files be recycled. |
When it is triggered:
| Checkpoint Trigger |
Description |
| Time-based |
Automatically every checkpoint_timeout (default 5 minutes). |
| WAL size limit |
When the WAL generated since the last checkpoint approaches max_wal_size (default 1 GB). |
| Manual checkpoint |
A DBA runs CHECKPOINT; |
| Smart / Fast shutdown |
A shutdown checkpoint writes all dirty buffers, so the next startup needs no recovery. |
| Immediate shutdown |
No checkpoint. The next startup needs crash recovery. |
| pg_basebackup |
Requests a checkpoint before copying the files. --checkpoint=fast completes it as quickly as possible. --checkpoint=spread (default) spreads the writes. |
| Crash recovery |
After replaying the WAL, PostgreSQL writes a checkpoint before it accepts client connections. |
| Point-in-Time Recovery |
After the recovery target is reached, a checkpoint is written before the database opens for normal use. |
| Standby promotion |
When a standby becomes the new primary, a checkpoint creates a new recovery starting point. |
| Database operations |
CREATE DATABASE and DROP DATABASE force a checkpoint. |
postgres=# SELECT num_timed, num_requested, buffers_written FROM pg_stat_checkpointer; -- PostgreSQL 17
postgres=# CHECKPOINT;
CHECKPOINT
Note: In PostgreSQL 17 the checkpoint counters moved from pg_stat_bgwriter to the new view pg_stat_checkpointer.
4.4 Autovacuum (launcher and workers)
| Point |
In simple words |
| Two separate jobs |
Autovacuum is a launcher and workers. Neither belongs to a client session. |
| Launcher (the manager) |
Wakes up every autovacuum_naptime (default 1 min) and starts workers for databases that need work. It does not vacuum anything itself. |
| Workers (do the real work) |
Up to autovacuum_max_workers (default 3) run at once. Each worker has its own memory limit, autovacuum_work_mem. |
| What workers do |
Remove dead rows left by UPDATE and DELETE, prevent table bloat, update statistics (ANALYZE) for the planner, and freeze old transaction IDs to prevent wraparound. |
| When a table is vacuumed |
When dead rows pass the formula below (defaults: about 20% of the table). ANALYZE runs when enough rows changed. |
| Forced run |
Forced when a table gets close to transaction ID wraparound (autovacuum_freeze_max_age, default 200 million). |
| Why it is needed |
PostgreSQL uses MVCC: UPDATE and DELETE leave the old row version behind, so old versions must be cleaned up. If transaction IDs wrap around, PostgreSQL refuses new writes to protect itself, so keep autovacuum healthy. |
Formula used to decide when a table is vacuumed:
autovacuum_vacuum_threshold + (autovacuum_vacuum_scale_factor Γ number_of_rows_in_table)
(defaults: 50 + 0.2 Γ rows, so about 20% of the table)
4.5 Logger
| Point |
In simple words |
| What it does |
Collects server messages from all processes and writes them to the log files. |
| When it exists |
Only when logging_collector = on. |
| What is logged |
Errors and warnings, checkpoint events, connections and disconnections, and slow queries (if enabled). |
| Key parameters |
log_min_messages (minimum level), log_min_duration_statement (log slow queries), logging_collector (turn the collector on or off). |
| Why it is needed |
Monitoring (what is happening), troubleshooting (finding errors) and auditing (a record of events). |
4.6 Archiver (Optional)
| Point |
In simple words |
| What it does |
Copies each completed WAL segment file to an archive location for backup and recovery. |
| When it runs |
Only when archive_mode = on (default off) in postgresql.conf. It runs the archive_command each time a WAL segment is completed. |
| Why it is needed |
Enables Point-In-Time Recovery (PITR), is the base of a continuous backup strategy and protects against data loss. |
Example:
archive_command = 'cp %p /archive/%f'
4.7 Stats Collector (only up to PostgreSQL 14)
Note: The separate stats collector process was removed in PostgreSQL 15. Statistics are now kept directly in shared memory and saved to the pg_stat folder at a clean shutdown. You will not see this process in PostgreSQL 17.
| Point |
In simple words |
| What it did (PG 14 and older) |
Collected statistics about table usage, index usage, row counts and query activity. This is what the pg_stat_* views show. |
| In PostgreSQL 15 and later |
No separate process. Statistics live in shared memory and are saved to the pg_stat folder at a clean shutdown. |
4.8 Other Processes You May See
| Process |
When it exists |
What it does |
| logical replication launcher |
Always running |
Starts apply workers for logical replication subscriptions. Idle if there are none. |
| startup |
Crash recovery, and always on a standby |
Replays WAL. |
| walsender / walreceiver |
Streaming replication |
The primary runs one walsender per standby. The standby runs a walreceiver. |
| walsummarizer |
summarize_wal = on (new in 17) |
Tracks changed blocks for incremental backups. |
| parallel worker |
During a parallel query |
Shares the work of one query (max_parallel_workers_per_gather, default 2). |
4.9 Background Process Summary
| PostgreSQL Process |
When It Runs |
Key Parameters (default) |
| Background Writer |
Wakes up every bgwriter_delay, writes some dirty pages |
bgwriter_delay 200ms, bgwriter_lru_maxpages 100 |
| WAL Writer |
Every wal_writer_delay, or after 1 MB of new WAL (the backend also flushes at COMMIT) |
wal_writer_delay 200ms, wal_writer_flush_after 1MB |
| Checkpointer |
5 min interval, WAL limit reached, manual checkpoint, shutdown |
checkpoint_timeout 5min, max_wal_size 1GB |
| Autovacuum launcher / workers |
Launcher every autovacuum_naptime; workers when a table passes a threshold |
autovacuum_naptime 1min, autovacuum_max_workers 3 |
| Logger |
When a loggable event occurs (only if logging_collector = on) |
logging_collector off, log_min_messages warning |
| Archiver |
When a WAL segment completes (archive_mode = on) |
archive_mode off, archive_command empty |
| Stats Collector |
Only up to PostgreSQL 14 |
Removed in 15 |
5. Memory Architecture β Shared Memory and Local Memory
PostgreSQL uses two groups of memory. Shared memory is allocated
once, when the instance starts. Local memory is allocated by
each process only while it needs it, so more connections mean more local memory.
5.1 Shared Buffers
| Point |
In simple words |
| Memory type |
Shared (one area for the whole instance). |
| What it is |
The main cache in RAM for table and index data pages (8 KB each). |
| How it works |
Cache hit: the page is already in RAM and is read directly. Cache miss: the page is first read from disk into shared buffers. |
| Dirty pages |
A page changed in memory but not yet saved to disk. The Background Writer saves some gradually. The Checkpointer saves all of them at a checkpoint. |
| Parameter and default |
shared_buffers, default 128 MB (minimum 128 kB). |
| Restart needed? |
Yes. |
| Tip |
A common starting point on a dedicated server is about 25% of RAM. |
5.2 WAL Buffers (Write-Ahead Log Buffers)
| Point |
In simple words |
| Memory type |
Shared. Also called transaction log buffers. |
| What it holds |
WAL records before they go to disk. A record has enough information to redo a change, including the new row data, so the WAL can rebuild data after a crash. |
| Who writes it to disk |
The WAL Writer, and the backend at COMMIT. It goes into WAL segments (16 MB files in pg_wal). |
| Parameter and default |
wal_buffers, default -1 = automatic: 1/32 of shared_buffers, at least 64 kB and at most 16 MB (one WAL segment). |
| Restart needed? |
Yes. |
5.3 CLOG Buffers (Commit Log Buffers)
| Point |
In simple words |
| Memory type |
Shared. |
| What CLOG is |
Commit Log. It stores the status of every transaction: in progress, committed, aborted or sub-committed. It needs only 2 bits per transaction. |
| Where it is stored |
The buffers are a cache in shared memory. The full commit log is on disk in the pg_xact folder and is written by the checkpointer. |
| Why it is needed |
Backends read it to decide whether a row version is visible to their snapshot. |
| Parameter and default |
transaction_buffers (new in PostgreSQL 17), default 0 = automatic: 1/512 of shared_buffers, between 128 kB and 8 MB. |
| Restart needed? |
Yes. |
5.4 Lock Memory
| Point |
In simple words |
| Memory type |
Shared. |
| What it is |
The lock table, shared by all backends. It tracks locks that are held and locks that are waiting. |
| Size depends on |
max_locks_per_transaction (default 64) and max_connections. |
| Restart needed? |
Yes, to change them. |
5.5 Work Memory
| Point |
In simple words |
| Memory type |
Local (private to each process). |
| Used for |
Sort and hash operations in queries: ORDER BY, DISTINCT, hash joins and merge joins. |
| Limit applies to |
Each operation, not each user, session or query. One complex query can use it several times. |
| Hash operations |
May use work_mem Γ hash_mem_multiplier (default multiplier 2.0). |
| If data does not fit |
It is written to temporary files in base/pgsql_tmp (slower). |
| Parameter and default |
work_mem, default 4 MB. Can be changed per session with SET. |
5.6 Maintenance Work Memory
| Point |
In simple words |
| Memory type |
Local (private to each process). |
| Used for |
Maintenance commands: VACUUM, CREATE INDEX, REINDEX and ALTER TABLE ... ADD FOREIGN KEY. |
| Parameter and default |
maintenance_work_mem, default 64 MB. |
| Autovacuum workers |
Use their own limit, autovacuum_work_mem. Default -1 = use maintenance_work_mem. It belongs to the autovacuum worker processes, not to a client session. |
5.7 Temp Buffers
| Point |
In simple words |
| Memory type |
Local (private to each session). |
| What it is |
A private cache for the pages of temporary tables and their indexes (called local buffers). |
| Not used for |
Sorts and hashes. Those use work_mem. |
| Parameter and default |
temp_buffers, default 8 MB per session. |
| Good to know |
Memory is taken only when the session first uses a temporary table. The value cannot be changed after that in the same session. |
Important: effective_cache_size (default 4 GB) is not memory at all. It allocates nothing. It is only a hint for the query planner about how much data PostgreSQL and the operating system together may have cached. A larger value makes index scans look cheaper.
5.8 Memory Parameters Summary
| Memory Area |
Group |
Parameter |
Default |
Change Takes Effect |
| Shared Buffers |
Shared |
shared_buffers |
128 MB |
Restart |
| WAL Buffers |
Shared |
wal_buffers |
-1 (automatic) |
Restart |
| CLOG Buffers |
Shared |
transaction_buffers |
0 (automatic) |
Restart |
| Lock Memory |
Shared |
max_locks_per_transaction |
64 |
Restart |
| Work Memory |
Local (per operation) |
work_mem |
4 MB |
Session / reload |
| Maintenance Work Memory |
Local |
maintenance_work_mem |
64 MB |
Session / reload |
| Autovacuum Worker Memory |
Local (per worker) |
autovacuum_work_mem |
-1 (use maintenance_work_mem) |
Reload |
| Temp Buffers |
Local (per session) |
temp_buffers |
8 MB |
Session (before first temp table use) |
| Planner hint (not memory) |
β |
effective_cache_size |
4 GB |
Session / reload |
Check the values on your own server:
postgres=# SELECT name, setting, unit, context
FROM pg_settings
WHERE name IN ('shared_buffers','wal_buffers','transaction_buffers','work_mem',
'maintenance_work_mem','autovacuum_work_mem','temp_buffers','effective_cache_size')
ORDER BY context, name;
postgres=# SHOW shared_memory_size; -- total shared memory of the instance
Note: In pg_settings, context = postmaster means the parameter needs a restart. sighup means a reload is enough. user means any user can change it with SET in their session.
6. Physical Files in PostgreSQL
PostgreSQL stores data and logs in several types of physical files on disk. All of them live in the
data directory (
PGDATA) except the log files and the archive, which you can place anywhere.
6.1 Data Files
| Point |
In simple words |
| What it stores |
The actual database data: tables, indexes and other objects. Data pages only, no code or executable instructions. |
| Where it is |
base/ (one sub-folder per database) and global/ (cluster-wide tables). |
| File size |
Large tables are split into 1 GB files. |
6.2 WAL Files (Write-Ahead Log Files)
| Point |
In simple words |
| What it stores |
The WAL records of every change (committed or not), written before the data pages are written to the data files. |
| Where it is |
pg_wal/, as 16 MB segments. |
| Why it is needed |
Data safety. After a crash, the WAL is replayed to recover changes that were not yet in the data files. Rolled-back changes are skipped using the ABORT record. |
| The rule |
"Write the log first, then write the data." |
6.3 Log Files
| Point |
In simple words |
| What it stores |
The server messages and events. |
| Output formats |
Set by log_destination: stderr (plain text), csvlog (CSV, easy to import and analyze), jsonlog (JSON, new in 15) and syslog (system logger). |
| Why it is needed |
Useful for debugging, monitoring and troubleshooting. |
6.4 Archive Logs (Optional)
| Point |
In simple words |
| What it stores |
Copies of completed WAL files, kept in a separate archive directory. |
| When it exists |
Only when archive mode is on (archive_mode = on). |
| Why it is needed |
Used for backup and point-in-time recovery: restore the database to any moment you choose. |
6.5 The Data Directory (PGDATA) Layout
| Path |
Contents |
base/ |
One sub-folder per database (named by its OID). Tables and indexes are files here. base/pgsql_tmp/ holds temporary files from sorts and hashes. |
global/ |
Cluster-wide catalogs and the pg_control file. |
pg_wal/ |
WAL segment files (16 MB each). |
pg_xact/ |
Commit status of every transaction (the CLOG files). |
pg_multixact/, pg_subtrans/ |
Row locks shared by several transactions, and subtransaction parents. |
pg_tblspc/ |
Symbolic links to tablespaces. |
postgresql.conf, postgresql.auto.conf |
Main settings, and the file written by ALTER SYSTEM (read last, so it wins). |
pg_hba.conf, pg_ident.conf |
Client authentication rules and user name maps. |
PG_VERSION, postmaster.pid |
Major version, and the PID of the running server. |
Warning: Never delete or edit files in pg_wal, pg_xact or base by hand. This can corrupt the database. Back up with pg_basebackup or pg_dump, not by copying files from a running server.
7. Quick Summary Cheatsheet
| Concept |
Detail |
| Process model |
One backend process per client connection. The postmaster is the parent of all processes. |
| Default port |
5432 (port in postgresql.conf, restart needed). |
| Who writes dirty pages? |
Background Writer (a few pages, gradually) and Checkpointer (all pages, at a checkpoint). |
| Who writes WAL to disk? |
WAL Writer every 200 ms, and the backend itself at COMMIT. |
| Who does vacuum? |
Autovacuum workers, started by the autovacuum launcher. They are not part of any client session. |
| Shared memory |
Shared buffers, WAL buffers, CLOG buffers, lock memory. One area for the instance. |
| Local memory |
work_mem, maintenance_work_mem, temp_buffers (and autovacuum_work_mem per worker). Private to each process. |
| Not memory |
effective_cache_size is only a hint for the planner. |
| Which parameters need a restart? |
shared_buffers, wal_buffers, transaction_buffers, max_connections, autovacuum_max_workers. |
| List running processes |
ps -ef | grep postgres or SELECT pid, backend_type FROM pg_stat_activity; |
| Force a checkpoint |
CHECKPOINT; |
| Check a parameter |
SHOW parameter_name; or SELECT * FROM pg_settings WHERE name = '...'; |
Caution: Your use of any information or materials on this website is entirely at your own risk. It is provided for educational purposes only. It has been tested internally, however, we do not guarantee that it will work for you. Ensure that you run it in your test environment before using.
Thank you
Rajasekhar Amudala