Sub topic 12
Observing WAL and checkpoints
This chapter assumes you know basic SQL and psql, and that you have read the earlier chapters on the write-ahead rule, LSNs, segment files and checkpoints. It shows how to measure what the server is doing, so you can base tuning on evidence instead of guesses.
What you can observe
PostgreSQL exposes WAL and checkpoint activity at four levels:
| Question | Tool |
|---|---|
| Where is the WAL write position, and in which file? | `pg_current_wal_lsn()`, `pg_walfile_name()` |
| How much WAL did a statement produce? | `pg_wal_lsn_diff()` |
| Where would crash recovery start? | `pg_control_checkpoint()` |
| How often do checkpoints run, and why? | `pg_stat_checkpointer` or `pg_stat_bgwriter`, plus `log_checkpoints` |
| How much WAL is full-page images? | `pg_stat_wal` |
| What is inside the WAL? | `pg_waldump` |
The current WAL position
The current write position is an LSN (log sequence number). You can map it to the segment file that contains it.
SELECT pg_current_wal_lsn() AS current_lsn,
pg_walfile_name(pg_current_wal_lsn()) AS wal_file;Three related functions report different positions:
pg_current_wal_insert_lsn()is the position where the next record will be inserted into the WAL buffers.pg_current_wal_lsn()is the position written to the operating system.pg_current_wal_flush_lsn()is the position flushed to durable storage. It is the one that matters for commit durability.
On a busy server the three values differ slightly. On a standby these functions raise an error because the standby is not generating WAL. Use pg_last_wal_receive_lsn() and pg_last_wal_replay_lsn() there.
Measuring the WAL a statement generates
Subtracting two LSNs gives a byte count. Save the position before the work, run the work, then diff. The \gset command is a psql feature that stores a query result in a psql variable.
CREATE TABLE wal_demo (id int PRIMARY KEY, payload text);
SELECT pg_current_wal_lsn() AS before_lsn \gset
INSERT INTO wal_demo
SELECT g, repeat('x', 100) FROM generate_series(1, 10000) AS g;
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'before_lsn')) AS wal_generated;The result is larger than the roughly 1 MB of row data (10,000 rows of about 100 bytes). Each heap insert and each index insert is its own WAL record with a header, and the first change to a page after a checkpoint can add a full-page image.
Run the same script a second time on a fresh table, immediately after a CHECKPOINT, and then again without one. Comparing the numbers shows the full-page-write effect directly.
The measurement is server-wide. Any other session writing during your test inflates the number, so use a quiet test instance.
Where would crash recovery start?
pg_control_checkpoint() reads the control file. It shows the most recent completed checkpoint.
SELECT checkpoint_lsn, redo_lsn, redo_wal_file, timeline_id, checkpoint_time
FROM pg_control_checkpoint();The two LSNs mean different things:
redo_lsnis where recovery begins replaying WAL. It was the insert position when the checkpoint started.checkpoint_lsnis the position of the checkpoint record itself, written when the checkpoint finished.
The gap between them is the WAL generated while the checkpoint was running. After a crash, the amount of WAL to replay is roughly the distance from redo_lsn to the end of WAL. You can estimate that exposure right now:
SELECT pg_size_pretty(
pg_wal_lsn_diff(pg_current_wal_lsn(), redo_lsn)
) AS wal_since_redo_point
FROM pg_control_checkpoint();Immediately after a checkpoint this is small. It grows until the next checkpoint begins. If it regularly grows near max_wal_size, the server is checkpointing because of volume, not time.
Forcing a checkpoint to watch it move
CHECKPOINT;
SELECT redo_lsn, checkpoint_time FROM pg_control_checkpoint();CHECKPOINT requires superuser or the pg_checkpoint role. It runs at full speed and ignores checkpoint_completion_target, so it can cause an I/O spike on a loaded system. Use it for experiments and before planned operations, not as a routine.
Reading checkpoint statistics
Counters show whether checkpoints are triggered by the clock or by WAL volume. The view name depends on your version.
-- PostgreSQL 17 and later
SELECT num_timed, num_requested, write_time, sync_time, buffers_written
FROM pg_stat_checkpointer;
-- PostgreSQL 16 and earlier
SELECT checkpoints_timed, checkpoints_req, checkpoint_write_time,
checkpoint_sync_time, buffers_checkpoint
FROM pg_stat_bgwriter;How to read the columns:
- Timed checkpoints fire because
checkpoint_timeoutelapsed. They are the healthy default. - Requested checkpoints fire because WAL reached
max_wal_size, or because someone ranCHECKPOINT, a base backup started, or a similar event forced one. write_timeandsync_timeare cumulative milliseconds spent writing buffers and syncing files.buffers_writtenis the number of shared buffers written by checkpoints.
Divide the write and sync times by the number of checkpoints to get an average duration. Counters are cumulative since the last statistics reset, so a high requested count may be old history. Compare two snapshots taken some hours apart instead of reading one absolute value.
On PostgreSQL 17 and later the checkpointer columns moved out of pg_stat_bgwriter. Scripts that query the old names fail after an upgrade. Check for this when you upgrade.
WAL volume and full-page images
pg_stat_wal (PostgreSQL 14 and later) counts WAL records, full-page images and bytes.
SELECT wal_records, wal_fpi, pg_size_pretty(wal_bytes) AS wal_bytes, stats_reset
FROM pg_stat_wal;Full-page images (FPIs) are copies of whole 8 kB pages that WAL stores the first time a page changes after a checkpoint. Compare wal_fpi with wal_records. If FPIs are a large share of records, and wal_bytes is large relative to the records' payload, frequent checkpoints are probably inflating WAL.
Take two snapshots around a workload and subtract them, because the totals include everything since stats_reset. You can reset them with SELECT pg_stat_reset_shared('wal');, which affects everyone reading these counters.
Logging checkpoints
The statistics views give totals. The server log gives one line pair per checkpoint, with the trigger reason. Since PostgreSQL 15, log_checkpoints is on by default. On older versions you can enable it, and max_wal_size can be raised at the same time. Both settings change with a reload, so no restart is needed.
ALTER SYSTEM SET log_checkpoints = on;
ALTER SYSTEM SET max_wal_size = '4GB';
SELECT pg_reload_conf();A typical pair looks like this. The exact fields vary by version.
LOG: checkpoint starting: wal
LOG: checkpoint complete: wrote 18234 buffers (11.1%); 0 WAL file(s) added,
0 removed, 12 recycled; write=26.9 s, sync=0.04 s, total=27.1 s;
sync files=42, longest=0.02 s, average=0.01 s; distance=196608 kB,
estimate=196608 kBWhat to look for:
- The word after
checkpoint starting:is the reason:time,wal,immediate force wait(a manualCHECKPOINT), orshutdown. Manywalentries meanmax_wal_sizeis too small for your write rate. write=should be close tocheckpoint_timeoutmultiplied bycheckpoint_completion_targetfor a timed checkpoint. A much shorter write time means the checkpoint was triggered early and ran faster.sync=is the time spent infsync. Large values point at storage that cannot absorb the burst.distanceis the WAL consumed since the previous checkpoint. It is the best single number for sizingmax_wal_size.
Looking inside WAL with pg_waldump
pg_waldump is a command-line tool that decodes segment files into records. Run it as the operating system user that owns the data directory, or as a user who can read pg_wal.
pg_waldump -p "$PGDATA/pg_wal" -s 0/1000028 -n 10Replace 0/1000028 with an LSN from your own server, such as redo_lsn from pg_control_checkpoint(). The start LSN must fall inside a segment file that still exists and must be a valid record boundary or at least in the file. Each output line shows the resource manager (Heap, Btree, Transaction, XLOG), the record length, the transaction ID, the LSN and a description. A checkpoint appears as an XLOG record with CHECKPOINT_ONLINE or CHECKPOINT_SHUTDOWN.
Two options are particularly useful:
--statssummarizes records by resource manager and by record type. This answers "what is generating all this WAL?"-r Heaplimits output to one resource manager.
From PostgreSQL 15, the pg_walinspect extension offers similar information through SQL functions such as pg_get_wal_stats(), which is convenient where you cannot reach the server's file system.
Common mistakes
- Reading cumulative counters as rates. Always diff two snapshots.
- Measuring on a busy server.
pg_current_wal_lsn()includes every session's WAL, not just yours. - Using the wrong view name.
pg_stat_checkpointerexists only in PostgreSQL 17 and later. - Running
pg_current_wal_lsn()on a standby. It errors during recovery. - Forcing checkpoints to "clear" WAL. A checkpoint makes old segments eligible for recycling. It does not delete anything that archiving, replication slots or
wal_keep_sizestill need.
Exercise
After a day of normal load, your server shows numtimed = 40 and numrequested = 310 in pgstatcheckpointer, and the log lines say "checkpoint starting: wal". Which setting would you inspect first, which log value helps you choose a new size, and what other effect would you expect to see in pgstatwal after the change?
Show answer
Inspect maxwalsize first. Requested checkpoints triggered by WAL volume mean the server hits maxwalsize before checkpointtimeout elapses. The "distance" value in the checkpoint complete log line shows how much WAL is consumed between checkpoints, so set maxwalsize comfortably above it. Fewer checkpoints mean fewer first-touch page modifications after each checkpoint, so walfpi and walbytes should grow more slowly relative to walrecords. Verify by taking two snapshots of pgstatwal around a similar workload.
Exercise
Write a query that tells you how many bytes of WAL would have to be replayed if the server crashed right now, and explain why the answer is small immediately after a CHECKPOINT.
Show answer
SELECT pgsizepretty(pgwallsndiff(pgcurrentwallsn(), redolsn)) FROM pgcontrolcheckpoint(); Crash recovery starts replaying at redolsn. Right after a checkpoint, redo_lsn is close to the current WAL position, so only the small amount of WAL written since then needs replaying.