PostgreSQL Architecture Fundamentals
PostgreSQL Data Flow


PostgreSQL Startup Sequence
Introduction
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 user connects to the database, PostgreSQL creates a separate process for that user.
- This process stays active until the user disconnects.
- PostgreSQL has a group of processes and memory structures called an instance.
- Each instance has its own memory and background processes.
- A single server can run multiple instances.
- Each instance works independently, which means:
- Memory cannot be shared between instances.
- Processes cannot be shared between instances.
- Client applications connect to a PostgreSQL instance to read or write data.
- The default port number for PostgreSQL is 5432.
- The port can be changed:
- During installation
- By editing the postgresql.conf configuration file
- After changing the port, the PostgreSQL service must be restarted.
Process Architecture
Postmaster Process
TheĀ PostmasterĀ is theĀ first processĀ that starts when PostgreSQL starts. It plays a central role in managing the entire PostgreSQL instance. Key responsibilities:- Acts as aĀ supervisorĀ ā monitors all other processes and restarts them if they crash or stop.
- ListensĀ for new connection requests from clients on portĀ 5432.
- HandlesĀ authentication and authorizationĀ ā checks the user's credentials and IP address against the configuration files, and verifies whether the user has permission to access the requested database.
- For each new client connection, it creates a new dedicated process called aĀ backend process (Postgres).
[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 ~]$Dedicated Backend Process
When a client connects to PostgreSQL, the Postmaster creates aĀ dedicated backend processĀ for that connection. Key points:- There isĀ one backend process per client connection.
- The backend process handles theĀ full lifecycleĀ of a session:
- Parses the SQL query
- Creates an execution plan
- Executes the query
- Returns results to the client
- It can accessĀ shared memoryĀ but also has itsĀ own private memory.
- The processĀ ends automaticallyĀ when the client disconnects.
PostgreSQL Background Processes
PostgreSQL runs several background processes to manage data, memory, logging, and maintenance.1. Background Writer (bgwriter)
What it does: The Background Writer continuously writesĀ dirty buffersĀ (modified data pages in shared memory) to the actualĀ data files on disk. When it is triggered:- RunsĀ continuouslyĀ in the background.
- Wakes up everyĀ
bgwriter_delayĀ milliseconds (default:Ā 200ms). - Gradually writes dirty pages to avoid sudden heavy disk activity.
- Works ahead of time so that backend processes do not have to write data themselves.
- At Checkpoint
- Prevents sudden spikes in disk I/O.
- Reduces delays for user queries.
- Keeps free buffers available in shared memory for new data.
2. WAL Writer
What it does: WritesĀ WAL (Write-Ahead Log)Ā records from WAL buffers in memory toĀ WAL files on disk. When it is triggered:- RunsĀ continuouslyĀ in the background.
- Wakes up everyĀ
wal_writer_delayĀ (default:Ā 200ms). - Also triggered immediately when:
- A transaction isĀ committed.
- WAL buffers becomeĀ full.
- A backend process forces aĀ WAL flushĀ for durability.
- EnsuresĀ transaction durability.
- WAL data must be safely written to disk before a commit is confirmed.
- Follows the rule:Ā "Write WAL first, then write data files."
CREATE TABLE wal_demo (
id SERIAL PRIMARY KEY,
fname TEXT
);
SHOW synchronous_commit;
SELECT pg_current_wal_lsn(), pg_walfile_name(pg_current_wal_lsn());
BEGIN;
INSERT INTO wal_demo (fname) VALUES ('RAJASEKHAR AMUDALA');
SELECT * FROM wal_demo;
SELECT pg_current_wal_lsn(), pg_walfile_name(pg_current_wal_lsn());
-- SELECT pg_switch_wal();
-- Open 2nd terminal
strings walfile | grep -i "RAJASEKHAR"
-- Come back to the first terminal
ROLLBACK;
SELECT * FROM wal_demo;
BEGIN;
INSERT INTO wal_demo (fname) VALUES ('RAJASEKHAR AMUDALA - COMMITTED COPY');
COMMIT;
SELECT pg_current_wal_lsn(), pg_walfile_name(pg_current_wal_lsn());
SELECT * FROM wal_demo;
strings | grep -i "RAJASEKHAR"
xxd walfile | grep -i -B2 -A2 "raja"
3. Checkpointer
What it does: The Checkpointer performs the following steps to create a safe recovery point:- Writes dirty pages to diskĀ ā All modified data pages (dirty buffers) in the shared buffer area are written to the data files on disk.
- Creates a checkpoint record in WALĀ ā A special checkpoint record is written to the Write-Ahead Log (WAL).
- Updates the control fileĀ ā The control file (
pg_control) is updated with the location (theĀ LSN ā Log Sequence Number) of the new checkpoint record.
- ReducesĀ crash recovery time.
- Ensures all committed data is safely written to disk.
- Creates a known safe recovery point for the database.
4. Autovacuum
What it does:- RemovesĀ dead rowsĀ left behind by UPDATE and DELETE operations.
- PreventsĀ table bloatĀ (tables growing unnecessarily large).
- UpdatesĀ table statisticsĀ used by the query planner.
- Freezes old transaction IDsĀ to prevent transaction ID wraparound.
- The number of dead rows in a table exceeds:
autovacuum_vacuum_threshold + (autovacuum_vacuum_scale_factor Ć table_size)- A table needsĀ statistics update (ANALYZE).
- To protect againstĀ transaction ID (XID) wraparoundĀ ā a critical condition that can cause data corruption.
- PostgreSQL usesĀ MVCC (Multi-Version Concurrency Control), which creates multiple versions of rows during updates and deletes.
- Old row versions must be regularly cleaned up.
- PreventsĀ database corruptionĀ from XID wraparound.
5.Ā Logger
What it does:- WritesĀ server messagesĀ and events to log files.
- Logs include:
- Errors and warnings
- Checkpoint events
- Connection and disconnection events
- Slow queries (if enabled)
- Triggered whenever aĀ loggable eventĀ occurs.
- Controlled by configuration parameters:
log_min_messagesĀ ā sets the minimum message level to loglog_min_duration_statementĀ ā logs queries that take longer than a set timelogging_collectorĀ ā enables or disables log collection
- MonitoringĀ ā tracks database activity
- TroubleshootingĀ ā helps find and fix errors
- AuditingĀ ā keeps a record of events for security and compliance
6. Archiver (Optional)
What it does: Copies completedĀ WAL segment filesĀ to a specified archive location for backup and recovery. When it is triggered:- Only active whenĀ
archive_mode = onĀ inĀpostgresql.conf. - Triggered when aĀ WAL segment is completed.
- Uses theĀ
archive_commandĀ to copy the file to the archive location.
archive_command = 'cp %p /archive/%f'- EnablesĀ Point-In-Time Recovery (PITR)Ā ā restoring the database to any specific moment.
- Essential for aĀ continuous backup strategy.
- Protects againstĀ data lossĀ in case of failure.
7. Stats Collector (Available till PostgreSQL v14 and older )
Note:Ā In newer versions of PostgreSQL, statistics are stored directly inĀ shared memoryĀ instead of using a separate collector process.What it does:
- Collects statistics about:
- Table usage
- Index usage
- Row counts
- Query activity
- Updates system catalog tables (
pg_catalog).
- RunsĀ continuously.
- Updates statistics when:
- Queries are executed
- Tables are scanned
- Rows are inserted, updated, or deleted
- Information becomes visible after the query completes.
- Helps theĀ Query PlannerĀ choose the best and most efficient execution plan.
- Improves overall databaseĀ performance.
Background Process Summary
| PostgreSQL Process | When It Is Triggered |
|---|---|
| Bgwriter | Runs continuously (every bgwriter_delay) |
| WAL Writer | Every wal_writer_delay, on commit, or WAL buffer full |
| Checkpointer | 5 min interval, WAL limit reached, manual checkpoint, shutdown |
| Autovacuum | Dead row threshold, stats update, XID protection |
| Stats Collector | Collects query statistics (till PostgreSQL v14) |
| Logger | When a loggable event occurs |
| Archiver | When WAL segment completes (archive_mode ON) |
Memory Architecture
PostgreSQL uses several memory areas to manage data efficiently.Main Memory Areas
- Shared Buffers
- WAL Buffers
- CLOG Buffers
- Work Memory
- Maintenance Work Memory
- Temp Buffers
Shared Buffers
- UsersĀ cannot directlyĀ read or write data files on disk.
- All database operations (SELECT, INSERT, UPDATE, DELETE) go through theĀ shared buffer area.
- When data is modified in memory, it is calledĀ dirty data.
- Dirty data is later written to disk by theĀ Background WriterĀ process.
- Parameter:Ā
shared_buffersĀ inĀpostgresql.conf - Default:Ā 128 MB (can be increased based on system needs)
WAL Buffers (Write-Ahead Log Buffers)
- Also calledĀ transaction log buffers.
- WAL storesĀ metadata about changesĀ (not the actual data).
- This metadata is enough toĀ rebuild dataĀ during crash recovery.
- WAL data is written to physical files on disk calledĀ WAL segments.
- Written from memory to disk by theĀ WAL WriterĀ process.
- Parameter:Ā
wal_buffersĀ inĀpostgresql.conf - Default:Ā
-1Ā (PostgreSQL automatically sets the size)
CLOG Buffers (Commit Log Buffers)
- CLOGĀ stands forĀ Commit Log.
- Stores theĀ commit statusĀ of every transaction.
- Indicates whether a transaction has beenĀ committed or not.
- CLOG buffers are kept inĀ system memory (RAM).
Work Memory
- Used forĀ sorting and hash operationsĀ during query execution.
- Examples: Queries withĀ
ORDER BY,ĀDISTINCT, hash joins, and merge joins. - AllocatedĀ per operation, not per user or database.
- Parameter:Ā
work_memĀ inĀpostgresql.conf - Default:Ā 4 MB
Maintenance Work Memory
- Reserved forĀ maintenance operationsĀ such as:
- VACUUM
- Index rebuild
- ANALYZE
- Parameter:Ā
maintenance_work_memĀ inĀpostgresql.conf - Default:Ā 64 MB (or system-defined)
Temp Buffers
- Used for accessingĀ temporary tablesĀ during a user session.
- Also used duringĀ large sort and hash operations.
- Parameter:Ā
temp_buffersĀ inĀpostgresql.conf - Default:Ā 8 MB
Physical Files in PostgreSQL
PostgreSQL stores data and logs in several types of physical files on disk.Data Files
- Store theĀ actual database dataĀ ā tables, indexes, and other objects.
- DoĀ notĀ contain any code or executable instructions.
- These are the core storage files of the database.
WAL Files (Write-Ahead Log Files)
- StoreĀ committed transaction recordsĀ before they are written to data files.
- EnsuresĀ data safetyĀ ā if the server crashes, WAL files are used to recover unsaved data.
- Follows the rule:Ā "Write the log first, then write the data."
Log Files
- Store allĀ server messages and events.
- Types of log output:
- stderrĀ ā Error messages
- csvlogĀ ā Logs in CSV format (easy to import and analyze)
- syslogĀ ā System-level log messages
- Useful forĀ debugging, monitoring, and troubleshooting.
Archive Logs (Optional)
- WhenĀ archive mode is enabled, completed WAL files are copied to a separateĀ archive directory.
- Used forĀ backup and point-in-time recovery.
- Allows restoring the database toĀ any specific point in time.
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
Email: br8dba@gmail.com
LinkedIn: linkedin.com/in/rajasekhar-amudala
