Sub topic 3
Archiving WAL continuously
This chapter assumes you know basic SQL, can use psql and the Linux command line, can edit postgresql.conf and restart PostgreSQL, and have a base backup to start from.
Archiving WAL continuously
PostgreSQL records every change in the write-ahead log (WAL), a series of 16 MB segment files. Archiving copies each finished segment to a safe location. Combined with a base backup, the archived WAL lets you replay changes up to any moment after that backup.
Set these options in postgresql.conf:
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'Changing archive_mode requires a server restart, not just a reload. The test ! -f guard refuses to overwrite a file that already exists. If the command fails, PostgreSQL retries it, and unarchived WAL accumulates in pg_wal.
Recovering to a point in time
To recover, restore a base backup into the data directory. Then add the recovery settings below and create an empty recovery.signal file in that directory:
restore_command = 'cp /mnt/archive/%f %p'
recovery_target_time = '2026-11-27 10:15:00+00'
recovery_target_action = 'promote'PostgreSQL replays archived WAL until the target time, then promotes itself to a writable server. Pick a time just before the mistake, such as a dropped table.
Proving a backup works: test restores
An archive that has never been restored is untested. Restore regularly onto a separate machine, run row counts and application checks, and record the elapsed time. Compare that time with your recovery time objective (RTO).
Exercise
Why does the archive_command test for an existing file before copying?
Show answer
It prevents a copy from overwriting a WAL segment that is already archived, so archived files are never silently replaced.
Scheduling, retention, encryption, and offsite copies
Run base backups on a schedule with cron or a systemd timer. Keep enough base backups and WAL to cover your recovery window. Delete older files only after a newer base backup has been verified. Encrypt backups before they leave the server, and store a copy at another site or in a separate cloud account.
When to use pgBackRest or Barman
Hand-written scripts suit small systems. pgBackRest and Barman automate base backups, WAL archiving, retention, compression, encryption, and verification. Choose pgBackRest for parallel backups and built-in encryption. Choose Barman when one central server should manage backups for many databases.