Sub topic 3
What triggers a checkpoint
This chapter assumes you know how WAL records and LSNs work, can run psql, and can read postgresql.conf settings.
A checkpoint writes all dirty data pages to disk and records a redo point, the place where crash recovery would start replaying WAL. PostgreSQL starts a checkpoint for these reasons:
- The
checkpoint_timeoutinterval has passed (default 5 minutes). - WAL written since the last checkpoint approaches
max_wal_size(default 1GB). This is a requested checkpoint. - A role runs the
CHECKPOINTcommand, which needs superuser or thepg_checkpointprivilege. - The server shuts down cleanly, or a base backup starts.
SHOW checkpoint_timeout;
SHOW max_wal_size;Spreading checkpoint writes over time
checkpoint_completion_target (default 0.9) sets the fraction of the checkpoint interval over which writes are spread. With a 5-minute timeout and 0.9, the checkpointer writes pages across about 4.5 minutes, which smooths disk I/O.
WAL recycling, removal and what keeps old WAL alive
After a checkpoint, WAL segments older than the redo point are no longer needed for crash recovery. PostgreSQL recycles them for future use. Three things can keep old WAL on disk: a failing archive_command, a replication slot that has not consumed the WAL, and wal_keep_size. Check slots with SELECT slot_name, restart_lsn FROM pg_replication_slots;.
Observing WAL and checkpoints
-- PostgreSQL 17 and later
SELECT num_timed, num_requested FROM pg_stat_checkpointer;
-- PostgreSQL 16 and earlier
SELECT checkpoints_timed, checkpoints_req FROM pg_stat_bgwriter;A high count of requested checkpoints means max_wal_size is too small for your write rate.
Tuning checkpoint and WAL settings
| Setting | Default | Starting point |
|---|---|---|
| checkpoint_timeout | 5min | 15min |
| max_wal_size | 1GB | Large enough that requested checkpoints are rare |
| checkpoint_completion_target | 0.9 | 0.9 |
> Note: Change these in small steps and compare checkpoint counts and I/O before and after.
WAL beyond crash recovery: archiving, PITR and replication
With archive_mode on, archive_command copies finished WAL segments to safe storage. Point-in-time recovery (PITR) restores a base backup and replays archived WAL up to a chosen time. Streaming replicas consume WAL continuously, so their progress also determines which WAL can be removed.
Exercise
Exercise
Why might a server show many requested checkpoints even though checkpoint_timeout is generous?
Show answer
Because WAL volume reaches maxwalsize before the timeout expires, so PostgreSQL triggers a checkpoint early. Raising maxwalsize reduces these requested checkpoints.