Sub topic 13
Retention: keeping the WAL your backups need
This chapter assumes you can already archive WAL with archive_command, take a base backup with pg_basebackup, and run a recovery. Here you will learn how long to keep each of those files and how to delete old ones without breaking the backups you still need.
Why retention is more than "delete old files"
A base backup alone cannot take you to a later point in time. It is a copy of the data files from one moment. To move forward from it, recovery replays archived WAL, starting at the segment that was current when the backup began. Each base backup therefore depends on a range of WAL segments:
- It needs every segment from the backup's start segment onward, with no gaps, up to the recovery target you want.
- It does not need segments older than its start segment.
This produces two rules:
- A base backup is useless if any segment between its start and your target is missing.
- A WAL segment is safe to delete only when no retained base backup needs it. That means it is older than the start segment of the oldest backup you keep.
If you delete WAL by age alone, you can break every backup you have. For example, a "delete files older than 7 days" job on the archive removes the segments that a 10-day-old backup needs. The backup directory still exists and looks fine, but it can only recover to the point where the chain breaks.
Finding where a backup starts
Every base backup records its starting WAL position in a file named backup_label at the root of the backup. Print it:
cat /backups/base/20261127/backup_labelTypical output:
START WAL LOCATION: 0/9000028 (file 000000010000000000000009)
CHECKPOINT LOCATION: 0/9000060
BACKUP METHOD: streamed
BACKUP FROM: primary
START TIME: 2026-11-27 02:00:01 UTC
LABEL: pg_basebackup base backup
START TIMELINE: 1The (file ...) value is the first WAL segment this backup needs. Segment names are 24 hexadecimal characters: 8 for the timeline, 8 for the log number, and 8 for the segment number. A name that sorts lower is older.
If you took the backup in tar format (-Ft), backup_label is inside base.tar. Extract it with tar -xOf base.tar backup_label.
The archive also holds a small backup history file for each backup, named like 000000010000000000000009.00000028.backup. The server writes it when the backup finishes. Its name contains the start segment, and it holds the same label data. pg_archivecleanup accepts it as a cutoff.
Removing old WAL with pg_archivecleanup
PostgreSQL ships pg_archivecleanup for this purpose. You give it the archive directory and the oldest segment to keep, and it deletes the older WAL files.
Always do a dry run first. With -n it prints what it would delete and removes nothing:
pg_archivecleanup -n /mnt/archive 000000010000000000000009When the list looks right, run it without -n:
pg_archivecleanup -d /mnt/archive 000000010000000000000009Details that matter:
- It only touches WAL segment files,
.partialfiles, and backup history files. It leaves other files alone, including timeline.historyfiles. Those are small, and recovery across a timeline switch needs them, so keep them. - It compares names as text. Segment names include the timeline ID, so a cutoff on timeline 1 and archived files on timeline 2 compare by that ID first. After a promotion, check the dry-run output before trusting it.
- Passing a
.backuphistory file name as the cutoff works. The tool uses the segment part of the name.
A retention policy you can automate
Choose the policy in terms of the recovery you must be able to perform, then derive the number of backups from it.
| Requirement | What it means for retention |
|---|---|
| Recover to any moment in the last 7 days | Keep at least one base backup that started before the 7-day mark, plus all WAL after it |
| Survive one bad or untested backup | Keep at least two backups, so there is a fallback |
| Keep a monthly backup for audit | Store it separately with its own WAL range, or as a standalone backup that includes WAL (`-X stream`) and is only restored to its own end |
| Disk is limited | Reduce the backup count, not the WAL range of backups you keep |
The following script keeps the newest three base backups, removes the older ones, and then removes the WAL that only the removed backups needed. It assumes plain-format backups in directories named by date, as in /backups/base/20261127, so a name sort puts them in time order.
#!/usr/bin/env bash
set -euo pipefail
KEEP=3
BASE_DIR=/backups/base
ARCHIVE=/mnt/archive
mapfile -t backups < <(find "$BASE_DIR" -mindepth 1 -maxdepth 1 -type d | sort)
count=${#backups[@]}
if (( count <= KEEP )); then
echo "Only $count backup(s); nothing to remove."
exit 0
fi
oldest_kept="${backups[$((count - KEEP))]}"
cutoff=$(sed -n 's/^START WAL LOCATION: .* (file \(.*\))$/\1/p' "$oldest_kept/backup_label")
if [[ -z "$cutoff" ]]; then
echo "Could not read the start segment from $oldest_kept/backup_label" >&2
exit 1
fi
# Remove old backups first, then the WAL that only they needed.
for dir in "${backups[@]:0:$((count - KEEP))}"; do
echo "Removing backup $dir"
rm -rf -- "$dir"
done
echo "Removing WAL older than $cutoff"
pg_archivecleanup -d "$ARCHIVE" "$cutoff"The order is deliberate. If the script stops partway, you may be left with extra backups or extra WAL, both harmless. The reverse order could leave a backup that still exists but cannot be restored.
What happens when the archive fills up
Retention is also a safety measure for the primary server. If /mnt/archive runs out of space, archive_command starts failing. PostgreSQL keeps every segment that has not been archived in pg_wal on the primary, and it keeps retrying. pg_wal then grows until the primary's own disk is full, and the server stops accepting writes and shuts down.
Two habits prevent this:
- Alert on free space in the archive filesystem well before it fills, not only on
failed_countinpg_stat_archiver. - Run retention on a schedule, directly after each successful base backup, so the archive does not grow without bound.
A common trap: archive_cleanup_command on a standby
A standby can also run pg_archivecleanup through archive_cleanup_command:
# standby postgresql.conf
archive_cleanup_command = 'pg_archivecleanup /mnt/archive %r'%r expands to the file holding the standby's last restart point. This is correct when the archive exists only to feed that standby. If the same directory also supports your base backups, the standby deletes WAL that old backups still need. It knows nothing about them. In that setup, leave archive_cleanup_command unset and let your backup retention job control deletion.
Checking that retention did not break anything
After changing a retention policy, verify the result:
- List the archive and confirm that the first segment, ignoring
.historyfiles, is at or after the oldest kept backup's start segment, and that no segments are missing after it. - Restore the oldest retained backup to a scratch location and recover it to a recent target. If the chain has a gap, recovery stops with an error asking for a missing segment.
- Record the oldest recoverable time. It is the end time of your oldest backup, since a backup is only consistent after it finishes, and your recovery window starts there.
A quick gap check is to list the archive and look for a jump in segment numbers:
ls /mnt/archive | grep -E '^[0-9A-F]{24}$' | head -n 5Run this on the archive and compare the first name with the cutoff from your script.
When to stop doing this by hand
This script covers one server and one simple policy. It does not handle several timelines well, tar-format backups, backups taken from a standby, expiring a full backup while keeping the incrementals that depend on it, or verifying checksums of the archive. Tools such as pgBackRest, Barman and WAL-G track which WAL belongs to which backup in their own catalogs and apply retention for you. The last chapter compares them.
Exercise
Your archive contains segments from 000000010000000000000004 onward. You keep two base backups. Their backuplabel files list start segments 000000010000000000000009 (older) and 00000001000000000000001C (newer). Which segment name do you pass to pgarchivecleanup, and which segments does it delete? What would go wrong if you passed 00000001000000000000001C instead?
Show answer
Pass 000000010000000000000009, the start segment of the oldest retained backup. pg_archivecleanup deletes segments 000000010000000000000004 through 000000010000000000000008 (everything lower than the cutoff). If you passed 00000001000000000000001C, it would also delete segments 000000010000000000000009 through 00000001000000000000001B. The older backup would lose the WAL it needs to reach consistency and replay forward, so it could no longer be restored. Only the newer backup would work.