Sub topic 9
WAL and Checkpoint Tuning
This chapter assumes you can edit postgresql.conf, reload or restart the server, and read basic psql output. You should also know that PostgreSQL keeps data pages in shared_buffers and writes changed pages to disk later. Here you will learn how the write-ahead log (WAL) and checkpoints control that later write, and how to tune them so disk I/O stays smooth.
Why WAL and checkpoints exist
When a transaction commits, PostgreSQL does not write the changed data pages to their table files right away. It writes a compact description of the change to the WAL and flushes that to disk. Sequential WAL writes are cheap, and they make the commit durable. The changed pages stay in shared_buffers as dirty pages and reach the table files later.
If the server crashes, PostgreSQL replays the WAL from the last checkpoint to rebuild the lost changes. A checkpoint is a point where the server writes all dirty pages to the data files and records that fact in the WAL. WAL from before the last completed checkpoint is no longer needed for crash recovery. It can be recycled or removed, unless archiving or replication still needs it.
This creates a trade-off:
- Frequent checkpoints keep crash recovery short and WAL small, but they cause more writes.
- Infrequent checkpoints spread writes out and cut total I/O, but they use more disk for WAL and make crash recovery longer.
What triggers a checkpoint
A checkpoint starts when any of these happens:
checkpoint_timeoutseconds have passed since the last one. The default is 5 minutes.- The amount of WAL written since the last checkpoint approaches
max_wal_size. The default is 1GB. - Someone runs
CHECKPOINT, or an operation such as a shutdown orCREATE DATABASEforces one.
A checkpoint caused by time is called a timed checkpoint. One caused by WAL volume is called a requested checkpoint. Requested checkpoints are the ones to worry about. They mean the WAL limit is smaller than your write rate needs.
The key settings
| Setting | Default | What it controls |
|---|---|---|
| `max_wal_size` | 1GB | Soft limit on WAL size between checkpoints. Reaching it triggers a requested checkpoint. |
| `min_wal_size` | 80MB | WAL files below this size are recycled instead of removed. |
| `checkpoint_timeout` | 5min | Maximum time between automatic checkpoints. |
| `checkpoint_completion_target` | 0.9 | Fraction of the interval over which checkpoint writes are spread. |
| `wal_buffers` | -1 (auto) | Shared memory for WAL not yet written. Auto is about 1/32 of `shared_buffers`, capped at one 16MB segment. |
| `full_page_writes` | on | Writes a full page image on the first change after each checkpoint. |
max_wal_size is a soft limit. Under heavy load, replication slots, or a failing archive_command, WAL can grow past it.
Older PostgreSQL versions defaulted checkpoint_completion_target to 0.5. Since PostgreSQL 14 it is 0.9, which is the usual recommendation. Check your version's value instead of assuming.
All of these settings take effect with a reload, except wal_buffers, which needs a restart.
Why checkpoints cause I/O spikes
A checkpoint has to write every page that was dirty when it started. With a large shared_buffers and a busy workload, that can be gigabytes. PostgreSQL spreads those writes over checkpoint_completion_target * checkpoint_timeout to avoid a burst. With a 15 minute timeout and a target of 0.9, writes are paced over about 13.5 minutes.
Full-page writes add to this. After a checkpoint, the first change to any page writes the whole 8kB page into the WAL, not just the change. This protects against torn pages after a crash. A short checkpoint interval means many pages are "first touched" again, so WAL volume goes up. Lengthening the interval often cuts WAL volume noticeably, not just checkpoint writes.
Step 1: Log checkpoints
Turn on logging first, so you can see what is happening.
# postgresql.conf
log_checkpoints = on
log_temp_files = 0
max_wal_size = 4GB
checkpoint_timeout = 15min
checkpoint_completion_target = 0.9With log_checkpoints = on, each checkpoint writes a line like this to the server log:
LOG: checkpoint starting: wal
LOG: checkpoint complete: wrote 41820 buffers (6.4%); 0 WAL file(s) added, 12 removed, 0 recycled; write=95.2 s, sync=0.4 s, total=95.9 sThe word after checkpoint starting: gives the trigger. time means the timeout fired. wal means max_wal_size was reached (older versions print xlog). If most checkpoints say wal, raise max_wal_size.
Step 2: Count checkpoint types
The cumulative statistics show the same thing without reading logs. In PostgreSQL 17 and later, use pg_stat_checkpointer:
SELECT num_timed, num_requested, write_time, sync_time, buffers_written
FROM pg_stat_checkpointer;In PostgreSQL 16 and earlier, the counters live in pg_stat_bgwriter:
SELECT checkpoints_timed, checkpoints_req,
checkpoint_write_time, checkpoint_sync_time, buffers_checkpoint
FROM pg_stat_bgwriter;Read the ratio of requested to timed checkpoints. A healthy system has mostly timed checkpoints. If requested ones are a large share, WAL fills before the timeout, and checkpoints are happening more often than you intended.
These counters are cumulative since the last stats reset. Compare two snapshots taken some time apart, or reset them with SELECT pg_stat_reset_shared('bgwriter'); (use 'checkpointer' on version 17 and later) before a test.
Step 3: Check current values and what needs a restart
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name IN ('max_wal_size', 'min_wal_size', 'checkpoint_timeout',
'checkpoint_completion_target', 'wal_buffers');The context column shows sighup for settings that a reload applies. It shows postmaster for settings that need a restart. If pending_restart is true, the file has a new value that the running server has not picked up.
Step 4: Choose values
A practical order of work:
- Raise
max_wal_sizeuntil most checkpoints are timed, not requested. For write-heavy systems, 4GB to 16GB is common. Make sure the WAL disk can hold it with room to spare. - Set
checkpoint_timeoutto 15 to 30 minutes if your recovery time budget allows. Crash recovery replays up to one interval of WAL, so a longer interval means a longer restart after a crash. - Keep
checkpoint_completion_targetat 0.9. Going higher leaves too little time to finish before the next checkpoint starts. - Leave
wal_buffersat its automatic value unless you see WAL write contention under many concurrent writers.
A rough way to size max_wal_size: measure how much WAL your workload writes in one checkpoint_timeout period, then add headroom. You can measure with pg_current_wal_lsn():
SELECT pg_current_wal_lsn();
-- wait a known interval, for example 5 minutes, then:
SELECT pg_current_wal_lsn();
-- compute the difference in bytes between the two values:
SELECT pg_wal_lsn_diff('0/5A000000', '0/3A000000') AS wal_bytes;Replace the two literal LSN values with the ones you captured. Scale the result to your checkpoint interval and set max_wal_size to a comfortable multiple of it, because max_wal_size also has to cover the WAL kept across the checkpoint spreading period.
ALTER SYSTEM SET max_wal_size = '4GB';
ALTER SYSTEM SET checkpoint_timeout = '15min';
SELECT pg_reload_conf();Trade-offs and edge cases
- Crash recovery time. A longer interval and larger WAL budget mean more WAL to replay after a crash. Recovery commonly runs at tens to hundreds of MB per second, so test with your own data before committing to a 30 minute interval.
- Disk space. WAL can exceed
max_wal_size. Replication slots that fall behind, and a stuckarchive_command, keep WAL files that the checkpoint would otherwise remove. Monitor the size ofpg_wal. - Replicas. On standbys, restartpoints play the role of checkpoints. They follow the same timeout and size settings, so a primary tuned for long intervals also gives standbys longer replay.
- Flush storms. If
sync=times in the checkpoint log lines are large, the operating system is holding a lot of dirty data and flushing it all at fsync. Thecheckpoint_flush_aftersetting asks the OS to start writing earlier in small steps. It defaults to 256kB on Linux. - Unlogged tables and bulk loads. Bulk loads generate WAL quickly and can trigger requested checkpoints even when day-to-day load does not. Raise
max_wal_sizetemporarily for large loads.
Verifying the result
After changing the settings, check that:
- The log shows
checkpoint starting: timefor most checkpoints. - The ratio of requested to timed checkpoints drops in the statistics view.
write=times in the log are close tocheckpoint_completion_target * checkpoint_timeout. Much shorter times mean the checkpoint is being forced to finish early, often because WAL volume is hitting the limit.- Disk latency graphs show lower and flatter write peaks.
pg_walstays below the size you planned for.
Exercise
The log shows most checkpoints starting with "checkpoint starting: wal", and pgstatbgwriter shows checkpointsreq much larger than checkpointstimed. Which setting do you raise first, why, and what cost do you accept?
Show answer
Raise maxwalsize. Requested checkpoints mean WAL reaches the limit before checkpointtimeout fires, so checkpoints run more often than intended, causing extra writes and extra full-page images in the WAL. A larger maxwalsize lets the timeout trigger checkpoints instead. The costs are more disk space for pgwal and possibly a longer crash recovery, because more WAL may need replaying. A reload is enough to apply the change.
Exercise
You set checkpointtimeout to 20min and checkpointcompletion_target to 0.9. Over roughly how long will a checkpoint spread its writes, and why should you not raise the target to 1.0?
Show answer
About 18 minutes (0.9 x 20 minutes). At 1.0 the checkpoint would aim to finish exactly when the next one is due. Any slowdown would make checkpoints overlap or run back to back, and the spreading would give no safety margin.