Sub topic 12
Combining Streaming with WAL Archiving
This chapter assumes you have a working primary and a hot standby built as in the earlier chapters. You should know what pg_basebackup, primary_conninfo, replication slots and pg_stat_replication do. You should also be able to edit postgresql.conf and restart a server.
Why add an archive to streaming
Streaming replication sends WAL over a network connection as the primary writes it. That connection depends on the primary still having the WAL the standby needs. If a standby is offline for a while, the primary may recycle those WAL segments, and the standby then fails with an error such as requested WAL segment ... has already been removed.
A WAL archive is a separate location, such as a shared directory, an NFS mount or object storage. The primary copies each completed 16 MB WAL segment there, and any server can read it back later. The archive gives you two things streaming alone does not:
- A catch-up source for standbys. A standby that falls behind can fetch old segments from the archive instead of the primary.
- Point-in-time recovery (PITR). With a base backup plus a continuous archive, you can restore to any moment, for example just before an accidental
DROP TABLE. A standby cannot do this. It only follows the present.
How a standby chooses its WAL source
A standby with both restore_command and primary_conninfo set cycles through three sources:
- It restores segments from the archive by running
restore_command. - When the archive has nothing more, it looks in its own
pg_waldirectory. - It then connects to the primary and streams from the last valid record it has.
If the stream breaks, the standby goes back to step 1. The archive is therefore a fallback and a catch-up path, and streaming is still the normal path for low latency.
Configuring archiving on the primary
Archiving needs three settings on the primary. archive_mode can only change with a restart, so plan for that.
# postgresql.conf on the primary
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /mnt/wal_archive/%f && cp %p /mnt/wal_archive/%f'
archive_timeout = 300%pis the path of the segment to archive, relative to the data directory.%fis its file name.- The command must return exit status 0 only when the file is safely stored. The
test ! -fguard refuses to overwrite an existing file. A non-zero exit makes PostgreSQL retry the same segment. archive_timeoutforces a segment switch after the given number of seconds. A segment is only archived once it is complete. On a quiet server, the last changes could otherwise sit unarchived for hours. Each forced switch still writes a full 16 MB file, so very small values waste archive space.
Plain cp is fine for a tutorial. For production, a command that also flushes the copied file to disk, or a dedicated tool such as pgBackRest or WAL-G, is safer. In PostgreSQL 15 and later you can use archive_library instead of a shell command.
Check that archiving works:
SELECT archived_count, last_archived_wal, last_archived_time,
failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;failed_count should stay flat. If it grows, the primary cannot archive some segment, and it will keep that segment and every later one in pg_wal.
Configuring the standby to read the archive
Add restore_command to the standby. It is the mirror image of archive_command.
# postgresql.conf on the standby
primary_conninfo = 'host=primary.example.com user=replicator password=change-me application_name=standby1'
primary_slot_name = 'standby1'
hot_standby = on
restore_command = 'cp /mnt/wal_archive/%f %p'
archive_cleanup_command = 'pg_archivecleanup /mnt/wal_archive %r'
recovery_target_timeline = 'latest'- For
restore_command,%fis the file name requested and%pis the destination path. The command must exit 0 only if it copied the file. It must exit non-zero if the file does not exist. A missing file is not an error. It tells the standby the archive has no more WAL, so it moves on to streaming. archive_cleanup_commandruns at each restartpoint on the standby.%ris the oldest segment still needed for restart.pg_archivecleanupdeletes everything older from the archive. Use it only when this standby is the only consumer of that archive. Other standbys, or a PITR backup that needs older segments, would lose WAL they still need.recovery_target_timeline = 'latest'makes the standby follow a new timeline after a failover. This is the default since PostgreSQL 12. The setting matters here because the archive holds the.historyfiles that describe timeline switches.
Restart or reload as needed. The standby log shows which source it is using:
LOG: restored log file "000000010000000000000042" from archive
LOG: started streaming WAL from primary at 0/43000000 on timeline 1Archive, slot, or both
A replication slot and an archive both protect a standby from missing WAL, but their costs differ.
| Approach | Where WAL is kept | Main risk |
|---|---|---|
| Slot only | `pg_wal` on the primary | An offline standby makes the primary retain WAL until its disk fills |
| Archive only (`wal_keep_size` as buffer) | Archive storage | A standby offline longer than the buffer needs the archive to catch up |
| Slot and archive | Both | Slot retention still needs a cap |
A common pattern is to use both and cap the slot:
# postgresql.conf on the primary
max_slot_wal_keep_size = '20GB'If a slot falls more than 20 GB behind, the primary invalidates it (wal_status becomes lost) instead of filling its disk. The standby then restores the missing segments from the archive and reconnects. Without an archive, an invalidated slot means rebuilding the standby from a new base backup.
Archiving from a standby
By default, archive_mode = on archives only on a server that is not in recovery. A standby does not archive. With archive_mode = always, a standby also runs archive_command, for the WAL it receives from the primary or restores from an archive. This lets you archive from a standby when the primary is under load, or keep a second archive in another location. Both servers then write the same segment file names, so the command must handle a file that already exists. If both write to one directory, they must produce identical content. The test ! -f guard would make the second writer fail, so use a command that succeeds when an identical file is already present.
Point-in-time recovery from the same archive
The same archive and a base backup let you build a server at an earlier moment. Take the base backup, restore it to an empty data directory, and configure recovery:
# postgresql.conf on the server being recovered
restore_command = 'cp /mnt/wal_archive/%f %p'
recovery_target_time = '2026-11-27 21:45:00+00'
recovery_target_action = 'pause'Create an empty recovery.signal file in the data directory, then start the server. It replays WAL from the archive up to the target time and pauses. Check the data, then run SELECT pg_wal_replay_resume(); or promote. recovery.signal selects targeted archive recovery. standby.signal selects continuous standby mode. If both files exist, standby.signal takes precedence.
Common errors
- Archive command path or permissions wrong.
failed_countrises andpg_walgrows. Run the command by hand as thepostgresuser with a real%pand%f. restore_commandreturns success when the file is missing. The standby believes it restored a segment that is not there and fails with a corrupt-record or invalid-header error. Make sure missing files give a non-zero exit.- Archive cleaned too aggressively.
pg_archivecleanuprun against a shared archive can remove WAL that a slower standby or a backup still needs. Base retention on your oldest restorable backup. archive_modechanged but no restart. The setting appears in the config file but archiving does not start. Check withSHOW archive_mode;after restarting.- Archiving only after the backup. The first backup's WAL range was never archived, so PITR from that backup fails. Verify with
pg_stat_archiverbefore relying on a backup.
Exercise
A standby was shut down for a weekend. When you start it, the primary has already recycled the WAL the standby needs, and there is no replication slot. The primary has archive_mode = on and a working archive_command. What setting on the standby lets it catch up without a new base backup, and what does the standby do when the archive runs out of segments?
Show answer
Set restore_command on the standby so it can fetch the missing segments from the archive. The standby replays everything the archive holds, then looks in its own pg_wal, and then connects to the primary and streams from the last record it has. If the stream later breaks, it goes back to the archive.
Exercise
On the primary, pg_stat_archiver shows failed_count rising and last_archived_time is hours old. What risk does this create, and what do you check first?
Show answer
The primary cannot recycle the segments it has failed to archive, so pg_wal keeps growing and can fill the disk, which stops the primary. First read last_failed_wal and the server log, then run the archive_command by hand as the postgres user to find the permission, path or connectivity problem.