Sub topic 10
Archiving WAL continuously
This chapter assumes you have read the base backup chapter and know what the data directory is. It also assumes you can edit postgresql.conf and restart a server. The chapter explains how PostgreSQL copies its write-ahead log (WAL) to safe storage while it runs. A base backup alone only restores the cluster to the moment the backup finished. A base backup plus a continuous WAL archive lets you restore to almost any later moment.
What WAL archiving does
PostgreSQL writes every change to the WAL before it changes the data files. The WAL is stored as numbered segment files in pg_wal/, 16 MB each by default. Once a segment is full, the server normally recycles or removes it after a checkpoint.
With archiving on, the server runs a command of your choice for each completed segment. The command copies the segment somewhere outside the data directory. The server keeps the segment in pg_wal/ until the command reports success.
The result is an unbroken series of segments covering everything that happened after the base backup. Recovery replays them in order. The next chapter covers that replay in detail.
Required settings
Three settings control archiving.
| Setting | Value | Notes |
|---|---|---|
| `wal_level` | `replica` or higher | `replica` is the default since PostgreSQL 10. `minimal` cannot be archived. |
| `archive_mode` | `on` or `always` | Changing it requires a server restart. |
| `archive_command` | shell command | Changing it needs only a reload. |
The always value of archive_mode makes a standby archive WAL it receives as well. Use on for a single primary.
Here is a minimal configuration. It is the one from the topic plan, and the copy-without-overwrite behavior is deliberate:
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'PostgreSQL substitutes two placeholders before running the command:
%pis the path of the segment to copy, relative to the data directory.%fis the file name only.
The command runs as the operating system user that owns the server process, usually postgres. That user needs write permission on the archive directory.
Prepare the directory, set the parameters, and restart:
sudo mkdir -p /mnt/archive
sudo chown postgres:postgres /mnt/archive
sudo chmod 700 /mnt/archive
psql -U postgres -c "ALTER SYSTEM SET archive_mode = 'on';"
psql -U postgres -c "ALTER SYSTEM SET archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f';"
sudo systemctl restart postgresqlThe service name varies by distribution, for example postgresql@16-main on Debian and Ubuntu. Adjust it for your system.
The contract for archive_command
The server judges your command only by its exit status.
- Exit status 0 means the segment is safely stored. The server may recycle it.
- Any non-zero status means failure. The server keeps the segment and retries, with a short pause between attempts.
A lie in either direction causes damage. If the command exits 0 without storing the file, you lose WAL and recovery will stop at the gap. If it exits non-zero after storing the file, the server retries and may overwrite or duplicate it.
The test ! -f ... && cp ... pattern follows two rules from the PostgreSQL documentation:
- Never overwrite an existing archive file. If a file with that name already exists, something is wrong, and the command should fail loudly instead of replacing history.
- Return failure when the copy did not complete.
The plain cp version has two weaknesses. It does not flush the copy to disk, so a power loss right after exit 0 can leave a truncated or missing file. It also leaves a partial file under the final name if the copy is interrupted, and then the test ! -f check fails forever on retry. A wrapper script fixes both problems. It copies to a temporary name, flushes, then renames. It also treats an identical existing file as success, so a retry after a lost acknowledgment does not block the archive.
#!/bin/bash
# /usr/local/bin/archive_wal.sh usage: archive_wal.sh %p %f
set -eu
src=$1
name=$2
dest=/mnt/archive
if [ -f "$dest/$name" ]; then
# Already archived: succeed only if the content is identical.
cmp -s "$src" "$dest/$name"
exit $?
fi
cp "$src" "$dest/$name.tmp"
sync "$dest/$name.tmp"
mv "$dest/$name.tmp" "$dest/$name"Make it executable and point the server at it:
archive_command = '/usr/local/bin/archive_wal.sh %p %f'A rename within one file system is atomic, so a reader never sees a half-written segment under its final name.
What lands in the archive
Besides numbered segments such as 000000010000000000000042, expect other files:
.historyfiles record timeline switches, for example after a promotion or a recovery. A later chapter on recovery explains why they matter..backupfiles are label files written at the end of a base backup. They record the start and stop WAL positions of that backup..partialfiles appear when a standby is promoted and archives its last, incomplete segment.
Keep all of them. Recovery needs the history files to follow timelines correctly.
Forcing and bounding archive delay
A segment is archived only when it fills. On a quiet server this can take hours, and every change in the half-filled segment exists only on the primary's disk until then. That sets your real recovery point (RPO) for a total disk loss.
Two tools shorten the delay:
archive_timeoutforces a segment switch after the given number of seconds, even if the segment is not full. Setting it to60limits exposure to about a minute of changes.SELECT pg_switch_wal();forces a switch immediately. It is useful before taking a manual backup or testing your setup.
A forced switch still produces a full 16 MB file, mostly padding. A very small archive_timeout on a quiet server wastes archive space, although compression removes most of the padding. For a tighter RPO than a minute or so, use streaming replication to a standby, or a tool that streams WAL such as pg_receivewal.
Verifying that archiving works
Never assume the setup works because the server restarted cleanly. Force a segment switch and check the statistics view:
psql -U postgres -c "SELECT pg_switch_wal();"
sleep 5
psql -U postgres -x -c "SELECT archived_count, last_archived_wal, last_archived_time, failed_count, last_failed_wal, last_failed_time FROM pg_stat_archiver;"
ls -l /mnt/archive | tail -n 5Read the output this way:
archived_countshould grow, andlast_archived_walshould name a file that now exists in/mnt/archive.failed_countandlast_failed_timeshow failures. Iflast_failed_timeis later thanlast_archived_time, archiving is currently broken.- The server log shows the error from your command, such as
cp: cannot create regular file ... Permission denied.
Put failed_count and the age of last_archived_time into your monitoring. A stale archive is silent until the day you need it.
Failure modes
The archive fills or the command fails, and pg_wal grows
When archive_command keeps failing, the server cannot remove segments that were not archived. pg_wal/ grows until the disk is full. At that point the server panics and shuts down, and writes stop.
Recovery from this state:
- Fix the cause, usually permissions, a full archive volume, or a missing mount.
- Reload the configuration if you changed it. Archiving resumes and the backlog drains in order.
Do not delete files from pg_wal/ by hand. Doing so breaks the archive sequence and can corrupt the server.
An unused replication slot also holds WAL. Check pg_replication_slots when pg_wal/ is large but pg_stat_archiver looks healthy.
Gaps in the sequence
Recovery replays segments in strict order. If one segment is missing, recovery stops there, and everything after it is unreachable. The usual causes are a command that returned 0 without storing the file, or manual cleanup of the archive that removed segments still needed by an older base backup.
Archive on the same disk as the data
An archive in /mnt/archive that is a directory on the same volume protects against nothing except logical mistakes. Use a separate device, a network mount, or an upload to object storage from your script. If the script uploads, it must exit 0 only after the upload is confirmed.
Base backup and archive out of step
A base backup is only restorable together with the WAL from its start position onward. Delete old WAL only when no base backup you intend to keep needs it. The retention chapter returns to this rule.
Exercise
You set archivemode = on and a valid archivecommand, then reload the server with pg_ctl reload. pgstatarchiver shows archivedcount = 0 even after you run pgswitch_wal(). What is the most likely cause, and which setting did you change that needs a different action?
Show answer
archivemode can be changed only at server start, so a reload does not apply it. Restart the server, then run pgswitchwal() again and check that archivedcount increases. (archive_command alone can be changed with a reload.)
Exercise
Your archive_command is cp %p /mnt/archive/%f. The archive volume fills up halfway through copying a segment, and cp exits with a non-zero status. Name two problems this setup has beyond the full volume.
Show answer
First, the partial file stays under its final name, and a later retry may leave a truncated segment in the archive or, with a no-overwrite check, fail forever. Second, the command never flushes the copy to disk, so even a successful exit 0 does not guarantee the file survives a crash. Writing to a temporary name, syncing, and renaming fixes both.