Sub topic 11
WAL recycling, removal and what keeps old WAL alive
This chapter assumes you know what a WAL segment, an LSN and a checkpoint are, and that you can read pg_settings and run queries in psql. It covers what happens to a WAL segment after it is no longer needed for crash recovery, and which features can stop that from happening.
The life of a WAL segment
A WAL segment is a file in pg_wal, 16 MB by default. PostgreSQL fills segments in order. Once a segment is full, it stays in pg_wal until nothing needs it, and then PostgreSQL does one of two things with it:
- Recycle it. The file is renamed to a future segment name and reused, so PostgreSQL doesn't have to create and preallocate a new file later.
- Remove it. The file is deleted.
The server makes this decision during and after each checkpoint. A checkpoint writes dirty buffers and records a new redo point. Crash recovery never needs WAL older than the redo point of the latest completed checkpoint, so the checkpointer cleans up segments that end before that point. This holds only on PostgreSQL 11 and later. Earlier versions kept WAL back to the previous checkpoint as well.
Why recycle instead of delete
Creating a WAL file is not free. PostgreSQL has to allocate the space and, by default, fill it with zeros, so that later writes don't have to extend the file. Reusing an old file avoids that cost on the commit path.
The server can't recycle every old segment, though. It estimates how much WAL the next checkpoint cycle will need, based on how much was used in recent cycles, and keeps that many segments ready. The estimate is clamped between min_wal_size and max_wal_size. Old segments beyond the estimate are deleted.
| Setting | Effect on cleanup |
|---|---|
| `min_wal_size` | Floor for how much recycled WAL is kept, even when the server is idle. The default is 80 MB. |
| `max_wal_size` | Soft limit on WAL between checkpoints. Reaching it triggers a checkpoint. |
| `wal_recycle` | When `on` (the default), old segments are renamed for reuse. When `off`, they are deleted. Available in PostgreSQL 12 and later. |
| `wal_init_zero` | When `on` (the default), new WAL files are zero-filled. Available in PostgreSQL 12 and later. |
Setting wal_recycle = off and wal_init_zero = off can help on copy-on-write file systems such as ZFS or Btrfs. There, overwriting a preallocated file gives no benefit, and the zero-fill only adds work. On ordinary file systems, leave both on.
What keeps old WAL alive
A segment is kept if any one of these conditions applies. Each of them can make pg_wal grow well beyond max_wal_size.
1. The checkpoint redo point
This is the normal case. WAL from the redo point of the latest checkpoint onward is needed for crash recovery. If checkpoints are far apart, more WAL is retained. A checkpoint that can't finish, for example because it is still being spread over a long time, delays cleanup.
2. Archiving that hasn't caught up
When archive_mode is on or always, a segment can't be recycled or removed until it has been archived successfully. For each completed segment, PostgreSQL creates a marker file archive_status/<segment>.ready. After archive_command (or the archive library) succeeds, the marker becomes .done. If the command keeps failing, .ready files pile up and pg_wal grows until the disk is full.
SELECT archived_count, failed_count,
last_archived_wal, last_archived_time,
last_failed_wal, last_failed_time
FROM pg_stat_archiver;A last_failed_time newer than last_archived_time means archiving is currently broken. Fix the archive command, its destination or its credentials. Don't delete the segments by hand.
3. Replication slots
A replication slot records the oldest WAL that its consumer still needs, in a column called restart_lsn. The slot can belong to a physical standby or a logical decoding client. PostgreSQL won't remove WAL at or after that position. A standby that is down, or a logical subscriber that has stopped reading, makes the primary keep every segment since the slot's restart_lsn.
SELECT slot_name, slot_type, active, restart_lsn, wal_status,
pg_size_pretty(safe_wal_size) AS safe_wal_size,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;wal_status and safe_wal_size exist in PostgreSQL 13 and later. The wal_status values mean:
reserved: the slot's WAL is withinmax_wal_size.extended: the slot holds WAL beyondmax_wal_size, kept by the slot or bywal_keep_size.unreserved: the slot is about to lose required WAL, and the next checkpoint may remove it.lost: required WAL has already been removed, and the consumer can't continue from the slot.
An inactive slot with a large retained value is the most common cause of a full pg_wal directory. If the consumer is gone for good, drop the slot:
SELECT pg_drop_replication_slot('old_standby_slot');4. `wal_keep_size`
wal_keep_size (called wal_keep_segments before PostgreSQL 13) tells the server to keep at least this much WAL for standbys that don't use slots. The default is 0. The retained WAL is a minimum. Other conditions can keep more.
5. Backups and other consumers
An online base backup (for example with pg_basebackup) needs the WAL generated since its starting checkpoint. The server protects that WAL while the backup runs. A backup that is started and never finished, such as an abandoned low-level exclusive-style backup on an old version, can pin WAL too.
Capping the damage
By default, a slot can keep unlimited WAL, so one stuck consumer can fill the disk. PostgreSQL 13 added max_slot_wal_keep_size. When a slot's retained WAL would exceed this limit, a checkpoint removes the old segments anyway and the slot becomes lost. You trade a broken replica, which can be rebuilt, for a primary that stays up.
ALTER SYSTEM SET max_slot_wal_keep_size = '50GB';
SELECT pg_reload_conf();Pick a value below the free space on the pg_wal volume, with room for normal WAL and for max_wal_size. The default of -1 means unlimited.
Finding out why `pg_wal` is large
Start by measuring what is in the directory. pg_ls_waldir() requires superuser or the pg_monitor role.
SELECT count(*) AS segments,
pg_size_pretty(sum(size)) AS total_size,
min(name) AS oldest,
max(name) AS newest
FROM pg_ls_waldir()
WHERE name ~ '^[0-9A-F]{24}$';The regular expression excludes .history files and similar entries. Then check the causes in order of likelihood:
- Run the
pg_replication_slotsquery. Look for inactive slots and largeretainedvalues. - Run the
pg_stat_archiverquery. Look for recent failures. - Compare with
SHOW max_wal_size;andSHOW wal_keep_size;. - Check the checkpoint statistics from the previous chapter. If checkpoints are failing or very slow, WAL can't be cleaned up.
Also remember that max_wal_size is a soft limit. A burst of write activity can exceed it for a while, and so can any of the retention causes above.
What happens when the disk fills up
If the volume holding pg_wal runs out of space, PostgreSQL can't write new WAL. A failure to write WAL is a PANIC, and the server shuts down. It can usually restart once you have freed space, but it can't accept writes while the disk is full. Free space safely by adding capacity, removing the cause of retention, or moving non-WAL files off the volume. Avoid deleting pg_wal contents.
Key points
- After a checkpoint, segments older than its redo point are no longer needed for crash recovery. They are recycled or removed.
- The checkpointer recycles up to an estimated need, bounded by
min_wal_sizeandmax_wal_size, and deletes the rest. - Pending archiving, replication slots,
wal_keep_sizeand backups each keep WAL alive independently. max_slot_wal_keep_sizelimits slot retention and makes a stuck slotlostinstead of filling the disk.- Diagnose with
pg_ls_waldir(),pg_replication_slotsandpg_stat_archiver.
Exercise
A primary's pg_wal directory has grown to 400 GB, though max_wal_size is 4 GB and checkpoints complete on schedule. pg_stat_archiver shows no failures and archiving is off. pg_replication_slots shows an inactive logical slot with wal_status = 'extended'. What is the cause, what are two ways to fix it, and how can you stop it from happening again?
Show answer
The inactive slot's restart_lsn is far behind the current LSN, so checkpoints can't remove the WAL it still requires. max_wal_size is only a soft limit and doesn't cap slot retention. Fix it by restarting the consumer so it reads and advances the slot, or by dropping the slot with pg_drop_replication_slot() if the consumer is gone for good. Once the slot advances or is dropped, the next checkpoint removes the old segments. To prevent a repeat, set max_slot_wal_keep_size to a value below the free space on the WAL volume (PostgreSQL 13 and later), and monitor pg_replication_slots for inactive slots with large retained WAL.
Exercise
Why does PostgreSQL recycle old WAL segments by renaming them, and when might you turn wal_recycle off?
Show answer
Renaming avoids the cost of creating and zero-filling a new segment file when WAL reaches it, which keeps that work off the commit path. You might turn wal_recycle off (and wal_init_zero too) on a copy-on-write file system such as ZFS or Btrfs, where overwriting a preallocated file has no advantage and zero-filling is wasted work.