Saturday, November 14, 2026

PostgreSQL Postmaster and Background Processes

 

PostgreSQL Postmaster and Background Processes

PostgreSQL has a multi-process architecture. Unlike Oracle (which is largely multi-threaded), PostgreSQL creates multiple OS processes.

1. Postmaster (Main PostgreSQL Process)

The Postmaster is the parent process of all PostgreSQL processes.

When PostgreSQL starts:

pg_ctl start

or

systemctl start postgresql

the first process created is:

Postmaster

Its responsibilities:

  • Listen for client connections
  • Spawn backend processes
  • Start background processes
  • Monitor child processes
  • Perform crash recovery
  • Restart failed workers

Architecture:

                    Postmaster
                         |
    -------------------------------------------------
    |          |           |          |             |
 Background  WAL       Checkpoint   Autovacuum   Backend
 Writer      Writer     Process      Workers     Sessions


2. Backend Processes

Every client connection gets its own backend process.

Example:

Application User-1
        |
    Backend PID 1001
Application User-2
        |
    Backend PID 1002
Application User-3
        |
    Backend PID 1003

Query:

SELECT pid,
       usename,
       application_name
FROM pg_stat_activity;

Each row corresponds to a backend process.


Important Background Processes

3. Background Writer (BgWriter)

Purpose:

Reduce checkpoint spikes.

When users modify data:

Shared Buffers
      ↓
Dirty Pages

These pages stay in memory.

The Background Writer gradually writes dirty pages to disk.

Without it:

Checkpoint would write everything

causing sudden I/O spikes.

View:

SELECT *
FROM pg_stat_bgwriter;


4. WAL Writer

One of the most important processes.

Purpose:

Flush WAL buffers to WAL files.

Flow:

INSERT/UPDATE/DELETE
       ↓
WAL Buffer
       ↓
WAL Writer
       ↓
pg_wal/

Example:

Shared Memory
      |
 WAL Buffer
      |
 WAL Writer
      |
 pg_wal files

Without WAL Writer:

Crash recovery impossible


5. Checkpointer

Purpose:

Create checkpoints

Checkpoint means:

Write dirty pages
to disk permanently

Flow:

Shared Buffers
      ↓
Disk Files

Checkpoint record also goes into WAL.

Benefits:

Faster crash recovery

Check settings:

SHOW checkpoint_timeout;
SHOW max_wal_size;

Monitor:

SELECT *
FROM pg_stat_bgwriter;


6. Autovacuum Launcher

Purpose:

Find tables needing vacuum.

It doesn't vacuum itself.

Rather:

Launcher
     ↓
Creates Workers

Architecture:

Autovacuum Launcher
        |
        +---- Worker 1
        +---- Worker 2
        +---- Worker 3

Check:

SHOW autovacuum;


7. Autovacuum Workers

Responsibilities:

  • Remove dead tuples
  • Update statistics
  • Freeze old tuples
  • Prevent XID wraparound

Example:

SELECT *
FROM pg_stat_progress_vacuum;

Shows currently running workers.


8. Statistics Collector (Older Versions)

In PostgreSQL before v14:

Stats Collector Process

maintained statistics used by:

pg_stat_activity
pg_stat_database
pg_stat_user_tables

In modern PostgreSQL versions:

Shared Memory Statistics

replaces much of the old collector architecture.


9. Archiver Process

Used when:

archive_mode = on

Purpose:

Copy WAL files
to archive storage

Used for:

PITR
Disaster Recovery

Check:

SELECT *
FROM pg_stat_archiver;

Example:

pg_wal
   ↓
Archive Command
   ↓
Backup Location


10. Startup Process

Runs during startup and recovery.

Responsibilities:

Read WAL
Replay transactions
Recover database

Example:

Crash
   ↓
Startup Process
   ↓
Replay WAL
   ↓
Consistent State

Oracle equivalent:

Instance Recovery


11. WAL Sender Process

Used in Streaming Replication.

Primary server:

Primary DB
   |
 WAL Sender
   |
 Network
   |
 WAL Receiver
   |
 Standby

Check:

SELECT *
FROM pg_stat_replication;


12. WAL Receiver Process

Runs on standby.

Purpose:

Receive WAL
from primary

Apply changes continuously.

Check:

SELECT *
FROM pg_stat_wal_receiver;


13. Logical Replication Launcher

Used for:

Logical Replication
Debezium
CDC
Kafka

Launches logical replication workers.

Example:

SELECT *
FROM pg_stat_subscription;


Shared Memory Interaction

All background processes interact with shared memory.

               Shared Memory
      ----------------------------------
      | Shared Buffers                |
      | WAL Buffers                   |
      | Lock Manager                  |
      | Proc Array                    |
      ----------------------------------
                  ^
                  |
    ------------------------------------
    |      |      |       |           |
 Backend WAL    BGW   Checkpoint  Vacuum


Crash Scenario Example

Suppose:

UPDATE accounts
SET balance=4000
WHERE id=1;

Step 1

Backend updates shared buffer.

Backend
  ↓
Shared Buffer

Step 2

Backend creates WAL record.

Backend
  ↓
WAL Buffer

Step 3

WAL Writer flushes WAL.

WAL Writer
  ↓
Disk

Step 4

Checkpointer eventually writes data page.

Checkpointer
   ↓
Data File

Step 5

Server crashes.

Startup Process:

Reads WAL
Replays Missing Changes

Database becomes consistent again.


PostgreSQL vs Oracle Background Processes

PostgreSQLOracle Equivalent
PostmasterPMON + Listener coordination
Backend ProcessDedicated Server Process
WAL WriterLGWR
CheckpointerCKPT
Background WriterDBWR
Startup ProcessSMON Recovery
AutovacuumNo direct equivalent
WAL SenderData Guard Redo Transport
WAL ReceiverManaged Recovery Process
ArchiverARCn

Most Common Interview Question

Explain PostgreSQL Process Architecture

Answer:

PostgreSQL uses a process-based architecture where the Postmaster acts as the parent process. For every client connection, Postmaster creates a dedicated backend process. Several background processes support database operations, including the WAL Writer for durability, Checkpointer for writing dirty pages to disk, Background Writer for smoothing I/O, Autovacuum Workers for MVCC cleanup and freeze operations, Archiver for WAL archiving, and WAL Sender/Receiver processes for streaming replication. Together they ensure performance, crash recovery, and data consistency.

About the Author : Anurag Pandey | Database cloud Architect | Oracle | SQL Server | PostgreSQL | AI and Data Platform Enthusiast

Anurag Pandey is a Database Architect with expertise in Oracle, PostgreSQL, SQL Server, Linux, and enterprise database platforms and specializes in database architecture, performance tuning, high availability, disaster recovery, cloud modernization, and operational excellence. With extensive experience in enterprise-scale environments, Anurag is passionate about leveraging AI, automation, and modern data platforms to improve reliability, scalability, and business outcomes. He actively contributes to technical communities through knowledge sharing, architecture guidance, and thought leadership in database and data engineering domains.

Follow more articles at

Visit Blog

What is Write-Ahead Logging (WAL) in PostgreSQL ?

 

Write-Ahead Logging (WAL) in PostgreSQL

Write-Ahead Logging (WAL) is PostgreSQL's mechanism for ensuring durability, crash recovery, and replication.

The core principle is:

Before changing the actual data page on disk, PostgreSQL first writes a record describing the change to the WAL.

This follows the ACID property of Durability.


Why WAL Is Needed

Imagine an account table:

UPDATE accounts
SET balance = balance - 1000
WHERE id = 1;

Suppose:

Balance = 5000

New balance:

4000

Now consider:

1. Data page updated in memory
2. Power failure
3. Data page not written to disk

Without WAL:

Transaction committed
Change lost

Database corruption or inconsistency can occur.


WAL Principle

Instead of immediately writing the table page:

Transaction
     |
     v
Create WAL Record
     |
     v
Flush WAL to disk
     |
     v
Commit Success
     |
     v
Data page written later

PostgreSQL guarantees:

WAL reaches disk first

Hence the name:

Write Ahead Log


Internal Flow

Suppose:

UPDATE employees
SET salary = 10000
WHERE id = 1;

Step 1

Data page loaded into shared buffers.

Buffer Cache
salary=8000


Step 2

Update performed in memory.

Buffer Cache
salary=10000

The actual disk page is still unchanged.


Step 3

Generate WAL record.

Example (simplified):

Table: employees
Block: 123
Offset: 5
Old Salary: 8000
New Salary: 10000


Step 4

Write WAL record into WAL buffer.

Shared Buffers
      +
WAL Buffers


Step 5

COMMIT

COMMIT;

Before PostgreSQL returns:

COMMIT successful

it flushes WAL to disk.

pg_wal/

directory.


Step 6

Actual table page written later.

Background Writer
Checkpoint

may write table pages minutes later.


Crash Recovery Example

Before Crash

Table:

salary=8000

Memory:

salary=10000

WAL:

UPDATE salary=10000

WAL already flushed.


Power Failure

Server crashes

Memory lost.


Startup Recovery

PostgreSQL reads WAL:

salary=10000

and replays the operation.

Result:

salary=10000

is restored.


WAL Records

WAL does not store full tables.

Instead it stores changes.

Example:

Insert tuple
Delete tuple
Update tuple
Create index
Drop table

Everything important is logged.


WAL Files

Location:

$PGDATA/pg_wal/

Example:

000000010000000000000001
000000010000000000000002
000000010000000000000003

Typically:

16 MB

per WAL segment.

Check:

SHOW wal_segment_size;


WAL and Checkpoints

Without checkpoints:

Recovery would replay years of WAL

Very slow.

PostgreSQL periodically performs checkpoints.


Checkpoint

A checkpoint writes dirty pages from memory to disk.

Shared Buffers
        ↓
Disk

and records:

Checkpoint Position

in WAL.


Recovery After Checkpoint

Instead of replaying all WAL:

Start from last checkpoint
Apply newer WAL

Much faster.


WAL and COMMIT

A common interview question:

Does COMMIT write table data?

No.

COMMIT writes WAL

Not necessarily table pages.

Table pages can be written later.

This makes PostgreSQL much faster.


WAL Buffers

Parameter:

SHOW wal_buffers;

Example:

16 MB

Purpose:

Temporary memory
for WAL records

before flushing.


WAL Levels

Check:

SHOW wal_level;

Possible values:

minimal
replica
logical


minimal

Least WAL generation.

Used for:

Standalone database


replica

Default in modern PostgreSQL.

Supports:

Streaming Replication
PITR
Recovery


logical

Supports:

Logical Replication
Debezium
CDC
Kafka

Captures enough information to reconstruct row-level changes.


WAL and Replication

Primary server:

Generates WAL

Standby server:

Reads WAL

Applies the same changes.

Architecture:

Primary
   |
   | WAL Stream
   v
Standby

This is PostgreSQL Streaming Replication.


WAL and Point-In-Time Recovery (PITR)

One of PostgreSQL's strongest features.

Example:

10:00 Good
11:00 Good
11:30 User drops table

Need recovery to:

11:29

Restore:

Base Backup
+
WAL Records

Replay until:

11:29

Table restored.


Important WAL Parameters

wal_level

SHOW wal_level;

Usually:

replica


max_wal_size

SHOW max_wal_size;

Example:

4GB
8GB
16GB

Controls WAL growth before checkpoint.


min_wal_size

Example:

1GB

WAL retained after checkpoints.


checkpoint_timeout

Default:

5 minutes

Maximum interval between checkpoints.


synchronous_commit

SHOW synchronous_commit;

Values:

on
off
remote_apply
remote_write


Performance Trade-off

ON

Safer.

OFF

Faster but may lose a few transactions during crash.


Oracle Comparison

Oracle also has a similar mechanism.

PostgreSQLOracle
WALRedo Logs
WAL WriterLGWR
CheckpointCheckpoint
Crash RecoveryInstance Recovery
PITRRMAN Recovery
WAL StreamingData Guard Redo Shipping

For Oracle DBAs:

PostgreSQL WAL is conceptually equivalent to Oracle Redo Logs.


Interview Answer

Write-Ahead Logging (WAL) is PostgreSQL's durability mechanism. Every database change is first recorded in the WAL and flushed to disk before the transaction commit is acknowledged. If the server crashes before data pages are written, PostgreSQL replays the WAL during recovery to restore committed transactions.

One-Line Summary

Data page later, WAL first. PostgreSQL always writes the change record to WAL before writing the actual table page, enabling crash recovery, replication, and point-in-time recovery.

About the Author : Anurag Pandey | Database cloud Architect | Oracle | SQL Server | PostgreSQL | AI and Data Platform Enthusiast

Anurag Pandey is a Database Architect with expertise in Oracle, PostgreSQL, SQL Server, Linux, and enterprise database platforms and specializes in database architecture, performance tuning, high availability, disaster recovery, cloud modernization, and operational excellence. With extensive experience in enterprise-scale environments, Anurag is passionate about leveraging AI, automation, and modern data platforms to improve reliability, scalability, and business outcomes. He actively contributes to technical communities through knowledge sharing, architecture guidance, and thought leadership in database and data engineering domains.

Follow more articles at

Visit Blog

VACUUM vs VACUUM FULL in PostgreSQL

 

VACUUM vs VACUUM FULL in PostgreSQL

A common misconception is:

"VACUUM removes dead tuples, so table size should shrink."

Wrong.

Regular VACUUM and VACUUM FULL have very different objectives.


Understanding the Problem

Suppose a table has grown to:

orders = 100 GB

Live data:

30 GB

Dead tuples:

70 GB

After many UPDATEs and DELETEs.


Regular VACUUM

VACUUM orders;

What it does

  1. Finds dead tuples.
  2. Marks their space as reusable.
  3. Updates visibility information.
  4. Helps index-only scans.
  5. Advances freeze information.

What it DOES NOT do

It does not return space to the operating system.


Example

Before:

Table Size = 100 GB
Page 1  Live rows
Page 2  Dead rows
Page 3  Live rows
Page 4  Dead rows

After VACUUM:

Page 1  Live rows
Page 2  Free space
Page 3  Live rows
Page 4  Free space

File size remains:

100 GB

But PostgreSQL can reuse that free space for future inserts/updates.


Analogy

Think of a hotel.

Before VACUUM:

100 rooms
70 empty
30 occupied

VACUUM:

Marks empty rooms available

Hotel building still has:

100 rooms

The building doesn't shrink.


VACUUM FULL

VACUUM FULL orders;

What it does

Instead of reusing space inside the file:

Creates a new compact copy
Copies only live rows
Drops old file


Example

Before:

100 GB table
30 GB live
70 GB dead

After:

30 GB table

Space is returned to:

Operating System

immediately.


Analogy

Using the hotel example:

Before:

100 rooms
30 occupied
70 empty

VACUUM FULL:

Build a new 30-room hotel
Move guests
Demolish old building

Now building size becomes:

30 rooms


Internal Architecture

Regular VACUUM

+------------------+
| Existing Table   |
+------------------+
         |
         +--> mark dead space reusable

No table rewrite.


VACUUM FULL

Old Table
     |
     v
Create New Table
     |
Copy Live Rows
     |
Swap Files
     |
Delete Old Table

Complete rewrite.


Locking Behavior

VACUUM

VACUUM table_name;

Lock:

SHARE UPDATE EXCLUSIVE

Practical impact:

✅ SELECT works

✅ INSERT works

✅ UPDATE works

✅ DELETE works

Usually invisible to users.


VACUUM FULL

VACUUM FULL table_name;

Lock:

ACCESS EXCLUSIVE

Impact:

❌ SELECT blocked

❌ INSERT blocked

❌ UPDATE blocked

❌ DELETE blocked

Everything waits.


Example:

500 GB table

VACUUM FULL might run:

Several hours

During which the table is unavailable.


Extra Disk Requirement

VACUUM

Needs very little additional disk.


VACUUM FULL

Needs enough space to hold:

Old table
+
New table

Example:

Current size = 500 GB

May require:

~500 GB extra

temporarily.


Index Impact

VACUUM

Indexes stay as-is.

Some index bloat may remain.


VACUUM FULL

Indexes are rebuilt.

Example:

Table bloat removed
Index bloat removed

Result:

Faster scans
Smaller indexes


Performance Comparison

FeatureVACUUMVACUUM FULL
Removes dead tuplesYesYes
Reclaims internal spaceYesYes
Returns disk to OSNoYes
Rewrites tableNoYes
Rebuilds indexesNoYes
Requires exclusive lockNoYes
AutoVacuum uses itYesNo
Suitable for production useYesRarely

Check Whether VACUUM Is Enough

Query:

SELECT
    relname,
    n_live_tup,
    n_dead_tup
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC;

If:

dead tuples present
but table size reasonable

Use:

VACUUM;


When VACUUM FULL Makes Sense

Case 1: Massive Delete

DELETE FROM orders
WHERE order_date < '2020-01-01';

Deleted:

90% of rows

Table remains:

1 TB

Live data:

100 GB

VACUUM won't shrink it.

VACUUM FULL can reduce:

1 TB -> 100 GB


Case 2: One-Time Data Purge

Archive and remove old data.

Then run:

VACUUM FULL;


Case 3: After Bulk Migration Cleanup

Drop old rows
Keep small dataset

Reclaim storage.


Why Production DBAs Prefer pg_repack

Instead of:

VACUUM FULL

many DBAs use:

pg_repack

Benefits:

✅ Removes bloat

✅ Rebuilds indexes

✅ Minimal locking

✅ Works online

Very common on:

Large OLTP systems
Financial databases
E-commerce databases


Interview Answer

VACUUM removes dead tuples and makes the space reusable inside the table file, but it does not reduce the file size on disk. It runs without blocking normal application activity and is what Autovacuum uses.

VACUUM FULL rewrites the entire table and indexes into a new compact copy, returning unused space to the operating system. However, it requires an ACCESS EXCLUSIVE lock, blocks all access to the table, and needs additional temporary disk space.

One-line summary:

VACUUM reuses free space inside the table; VACUUM FULL shrinks the table by rebuilding it.

About the Author : Anurag Pandey | Database cloud Architect | Oracle | SQL Server | PostgreSQL | AI and Data Platform Enthusiast

Anurag Pandey is a Database Architect with expertise in Oracle, PostgreSQL, SQL Server, Linux, and enterprise database platforms and specializes in database architecture, performance tuning, high availability, disaster recovery, cloud modernization, and operational excellence. With extensive experience in enterprise-scale environments, Anurag is passionate about leveraging AI, automation, and modern data platforms to improve reliability, scalability, and business outcomes. He actively contributes to technical communities through knowledge sharing, architecture guidance, and thought leadership in database and data engineering domains.

Follow more articles at

Visit Blog

Important Database Global Monitoring Metrics

Below is the baseline I would use for Oracle 19c production databases , especially RAC/Data Guard environments. 1. Severity model Severity M...