Sub topic 14
WAL beyond crash recovery: archiving, PITR and replication
This chapter assumes you have read the earlier chapters on WAL records, LSNs, segment files and checkpoints. It also assumes you can edit postgresql.conf and run psql against a test server. The commands use PostgreSQL 15 or later. The paths are examples, so change them to match your system.
One log, three jobs
Crash recovery replays WAL from the last checkpoint's redo point. The WAL stream is a complete, ordered record of every change, so other features reuse it:
- Continuous archiving copies each finished WAL segment to storage outside the server.
- Point-in-time recovery (PITR) restores an old base backup, then replays archived WAL up to a chosen moment.
- Streaming replication sends WAL to another server, called a standby, which replays it continuously.
All three depend on the same rule from earlier chapters: a change is described in WAL before it reaches a data page. A server that has the WAL from a known starting point can reconstruct the database.
wal_level controls how much is logged
The wal_level setting decides how much detail goes into each WAL record.
| Value | Adds | Needed for |
|---|---|---|
| `minimal` | Only what crash recovery needs | Standalone servers with no archiving or replication |
| `replica` | Data for archiving and physical replication (the default) | Base backups, PITR, streaming standbys |
| `logical` | Extra data to decode row changes | Logical replication and logical decoding |
Changing wal_level requires a restart. With minimal, some bulk operations skip WAL for new relations. That is why a minimal server cannot produce a usable base backup or archive.
Continuous archiving
A server only keeps WAL until a checkpoint makes it unnecessary for crash recovery, and then it recycles the segments. Archiving copies each segment out before that happens.
Set these parameters. archive_mode needs a restart. archive_command only needs a reload.
ALTER SYSTEM SET wal_level = 'replica';
ALTER SYSTEM SET archive_mode = 'on';
ALTER SYSTEM SET archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f';In the command, %p is the path of the segment to copy and %f is its file name. The test ! -f guard refuses to overwrite an existing file. The command must return exit status 0 only when the file is safely stored. If it returns non-zero, PostgreSQL keeps the segment in pg_wal and retries.
After restarting, check that archiving works:
SELECT pg_switch_wal();
SELECT archived_count, last_archived_wal, last_archived_time,
failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;pg_switch_wal() closes the current segment so it can be archived at once. If failed_count grows, fix archive_command quickly. Segments that cannot be archived pile up in pg_wal and can fill the disk.
Taking a base backup
Archived WAL is only useful with a starting point: a physical copy of the data directory taken while the server runs. pg_basebackup makes one. It starts with a checkpoint, so the backup has a known redo point.
pg_basebackup -h primary.example.com -U replicator \
-D /backups/base_2026-11-27 -X stream -P --checkpoint=fastThe -X stream option includes the WAL generated during the backup. The backup is consistent only once replay reaches the end-of-backup point, and the copied files alone are not consistent. That is why recovery always needs WAL.
Point-in-time recovery
Suppose someone ran DELETE FROM orders without a WHERE clause at 21:58. You restore the base backup, then replay archived WAL up to 21:57.
- Stop the server and move the damaged data directory aside.
- Copy the base backup into a new data directory.
- Add recovery settings to
postgresql.conf. - Create an empty file named
recovery.signalin the data directory. - Start the server.
restore_command = 'cp /mnt/archive/%f %p'
recovery_target_time = '2026-11-27 21:57:00+00'
recovery_target_action = 'promote'On start, the server sees recovery.signal and enters archive recovery. It asks restore_command for each segment, replays the records, and stops when it reaches the target. With recovery_target_action = 'promote' it then becomes a normal read-write server. The default action is pause, which stops replay and lets you inspect the data first. In that state, SELECT pg_wal_replay_resume(); ends recovery.
You can also target a transaction ID (recovery_target_xid), an LSN (recovery_target_lsn) or a named restore point created with pg_create_restore_point('before_cleanup').
Timelines
When recovery ends and the server promotes, it starts a new timeline. The timeline ID is part of every WAL file name, so the new history cannot overwrite WAL from the old one. You saw timeline_id in pg_control_checkpoint() earlier. If a later recovery picks the wrong branch, set recovery_target_timeline. The default is latest.
Streaming replication
Archiving ships whole 16 MB segments, so a standby fed only from the archive can lag by a full segment. Streaming replication sends WAL records over a network connection as they are written. A walsender process on the primary reads the WAL and sends it. A walreceiver process on the standby writes it to its own pg_wal, and the startup process replays it.
First create a role and allow it in pg_hba.conf (the entry must use the replication database keyword):
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'change-me';Then build the standby from the primary:
pg_basebackup -h primary.example.com -U replicator \
-D /var/lib/postgresql/standby -X stream -R -C -S standby1The -R option writes primary_conninfo and creates standby.signal. A standby uses standby.signal where PITR uses recovery.signal. The -C -S standby1 options create a physical replication slot. A standby with hot_standby = on (the default) accepts read-only queries while it replays.
Watching replication
Run this on the primary:
SELECT application_name, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes
FROM pg_stat_replication;The view reports four LSNs for each standby: sent_lsn, write_lsn, flush_lsn and replay_lsn. They mark how far the WAL has been sent, written, flushed to disk, and applied. The flush stage connects to synchronous_commit. With remote_write, on or remote_apply and a standby listed in synchronous_standby_names, COMMIT waits for the standby to pass the matching stage. The default setting on waits for the standby's flush. remote_apply waits for replay, so queries on the standby see the commit.
What keeps old WAL alive
Earlier you learned that a checkpoint lets the server recycle segments before the redo point. These extra holds can keep segments longer:
- A segment that failed archiving or has not yet been archived.
- A replication slot whose
restart_lsnis older than the segment. wal_keep_size, which keeps a fixed amount of recent WAL for standbys that do not use a slot.
A slot guarantees that a standby can always catch up, but a stopped standby makes the primary keep WAL forever. Watch for this:
SELECT slot_name, slot_type, active, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;A wal_status of reserved is normal. extended means the slot holds WAL beyond max_wal_size. unreserved means required WAL may be removed at the next checkpoint. lost means it has been removed and the standby must be rebuilt. To protect the primary's disk, set max_slot_wal_keep_size so a stalled slot is dropped from protection instead of filling the volume. Drop slots you no longer use with pg_drop_replication_slot('standby1').
Common errors
- Archive failures are ignored. A bad path or full archive disk makes
pg_walgrow. Alert onfailed_countand on the age oflast_archived_time. - Overwriting archive files. A command like plain
cpcan silently replace a segment. Use thetest ! -fguard or a purpose-built tool such as pgBackRest or WAL-G. - Never testing a restore. An archive you have not restored from is untested. Rehearse PITR on a scratch server.
- A standby's slot is forgotten. An abandoned slot is the most common cause of a full
pg_waldirectory. - Wrong
wal_level. Aminimalserver rejectsarchive_modeand replication. Also, areplicaserver cannot do logical replication until it is changed tologicaland restarted. - Replication is not a backup. A standby faithfully replays your accidental
DELETE. Only archived WAL plus a base backup lets you go back in time.
Exercise
A primary's pgwal directory has grown to 400 GB. pgstatarchiver shows failedcount is 0, and pgreplicationslots shows an inactive slot with wal_status "extended". What is the likely cause, and what are two ways to fix and prevent it?
Show answer
The inactive slot's restartlsn is old, so the primary keeps every segment since then, even though archiving is healthy. Fix it by bringing the standby back so it consumes the WAL, or by dropping the slot with pgdropreplicationslot() if the standby is no longer needed (rebuild the standby later if required). To prevent a repeat, set maxslotwalkeepsize so a lagging slot cannot hold unlimited WAL, and alert on retained bytes from pgreplicationslots.
Exercise
You restored a base backup and set recoverytargettime, but the server never leaves recovery and accepts only read-only connections after reaching the target. Which setting explains this, and how do you finish recovery?
Show answer
recoverytargetaction defaults to pause, so replay stops at the target and the server stays read-only. Inspect the data, then run SELECT pgwalreplayresume(); to end recovery and promote. Setting recoverytarget_action = 'promote' beforehand skips the pause.