Sub topic 3
Turning on continuous WAL archiving
This chapter assumes you can edit postgresql.conf, restart and reload a PostgreSQL server, and use the Linux shell with file ownership and permissions. It also assumes you know that PostgreSQL writes changes to the write-ahead log (WAL) before it writes them to data files. The commands use a Debian-style layout with data in /var/lib/postgresql/16/main and a local archive directory. Adjust the paths for your system.
What archiving does
PostgreSQL writes WAL into fixed-size files called segments. The default size is 16 MB. Once a segment is full, PostgreSQL normally recycles or removes it after a checkpoint. WAL archiving adds a step. Before PostgreSQL recycles a completed segment, it runs a command that you supply to copy the segment somewhere safe.
A base backup alone only restores the cluster to the moment the backup finished. The archived segments are the record of everything after that, and replaying them is what lets you stop at any chosen point.
The key rule is in the last branch. PostgreSQL treats exit status 0 from your command as a promise that the file is safely stored. Any other status means "try again", and the segment stays in pg_wal until the command succeeds.
The settings
Archiving needs four settings in postgresql.conf.
# postgresql.conf
wal_level = replica
archive_mode = on
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'
archive_timeout = 300| Setting | Purpose | How a change takes effect |
|---|---|---|
| `wal_level` | Controls how much information goes into WAL. `replica` is enough for archiving and recovery. `logical` also works, because it includes everything `replica` does. `minimal` cannot be used. | Restart |
| `archive_mode` | `off`, `on`, or `always`. Nothing is archived while it is `off`. | Restart |
| `archive_command` | The shell command that copies one completed segment. It is ignored while `archive_mode` is `off`. | Reload |
| `archive_timeout` | Forces a segment switch after this many seconds if the current segment has WAL in it. | Reload |
Since PostgreSQL 10, wal_level defaults to replica. Writing it explicitly in the file still helps, because a reader can see that archiving depends on it.
The placeholders
PostgreSQL substitutes two values before it runs the command.
%pis the path of the segment to copy, relative to the data directory.%fis the file name of the segment only, such as000000010000000000000007.
To write a literal percent sign, use %%. The command runs through the shell with the data directory as its working directory, as the operating-system user that runs the server. That user, usually postgres, must be able to read %p and write to the destination.
Why the command starts with `test ! -f`
The test ! -f /mnt/archive/%f part makes the command fail if a file with that name already exists. Overwriting an archived segment could destroy the only good copy. For example, a misconfigured second cluster might be archiving into the same directory. With the guard, the archiver keeps failing and keeps reporting the problem, and you find out. This is the minimum safeguard. The next chapter covers what else a reliable command needs, including flushing the copy to disk.
What `archive_mode` values mean
onarchives segments while the server is a primary, or while it is in archive recovery and about to be promoted.alwaysalso archives segments on a standby that receives WAL by streaming or from an archive. Use it only when you deliberately want a standby to archive as well, and make sure the two servers cannot write different files with the same name to the same directory.
PostgreSQL 15 added archive_library as an alternative to a shell command. This chapter uses archive_command. Set one or the other, not both.
Setting it up
First create the destination directory and give the server's operating-system user ownership.
sudo mkdir -p /mnt/archive
sudo chown postgres:postgres /mnt/archive
sudo chmod 700 /mnt/archiveIn production, /mnt/archive should be a different disk or a network mount, and not a directory on the volume that holds the data. If the archive shares a disk with the cluster, one disk failure destroys both the database and its backup.
Next, add the four settings to postgresql.conf. Because archive_mode is changing, restart the server.
sudo systemctl restart postgresqlYou can confirm that the server picked up the values.
SHOW wal_level;
SHOW archive_mode;
SHOW archive_command;
SHOW archive_timeout;If you only change archive_command or archive_timeout later, a reload is enough.
SELECT pg_reload_conf();Checking that a segment is archived
On an idle test server, no segment may fill for a long time. You can force a switch to the next segment so that the current one becomes complete.
SELECT pg_switch_wal();
SELECT archived_count, last_archived_wal, failed_count, last_failed_wal
FROM pg_stat_archiver;pg_switch_wal() returns the position where it switched. If there was no WAL written since the last switch, it does nothing. The archiver runs in the background, so the counters may take a moment to change. Run the second query again after a second or two. Then list the archive.
ls -l /mnt/archiveYou should see a file with a 24-character hexadecimal name. For example, 000000010000000000000003 breaks down as 8 characters of timeline (00000001), 8 of log number, and 8 of segment number. The timeline part matters later, when you recover.
A healthy result has archived_count rising and failed_count staying at 0. A later chapter covers monitoring in more depth.
What `archive_timeout` costs
A segment is archived only when it is complete. On a quiet database, a segment might take hours to fill. All of the changes in it exist only in pg_wal on the primary. If the primary's disk were lost, you could not recover them from the archive.
archive_timeout = 300 sets an upper bound of about five minutes on how stale the archive can be. It has a cost. Every forced switch produces a full 16 MB file, even if it holds only a few records. At 300 seconds, that is up to 288 files, or about 4.5 GB, per day on an idle server. Very small values such as 10 seconds generate large archives quickly. Choose a value that matches how much recent data you can afford to lose, and compress the files if the archive is large.
The timeout does not give you synchronous protection. Commits in the last few minutes can still be lost if the server's disk fails. If you cannot accept that, add streaming replication.
Common errors
- Failing on the first run. The
postgresuser cannot write to/mnt/archive. Check the owner and permissions. The error appears in the server log asarchive command failed with exit code 1, with the command text. - Forgetting to restart.
archive_modewas edited and reloaded. The setting staysoffuntil a restart. Check withSHOW archive_mode;. - A
wal_levelofminimal. The server refuses to start witharchive_modeon, because the WAL lacks the detail needed for recovery. - A missing destination. If the directory does not exist or the network mount is down,
cpfails every time and the archiver keeps retrying. - A duplicate file name. With the
test ! -fguard, the archiver fails permanently on that segment. It does not skip it, and later segments are not archived until the problem is fixed. Investigate before deleting anything. - A growing
pg_wal. While the command fails, PostgreSQL cannot remove the unarchived segments. They accumulate until the disk fills, and the server then shuts down with a PANIC. Treat any rise infailed_countas urgent.
Exercise
You set archivemode = on and archivecommand in postgresql.conf, then ran SELECT pgreloadconf();. Segments are not being archived, and SHOW archive_mode returns off. What went wrong, and what is the fix? After the fix, how do you quickly test that a segment reaches the archive?
Show answer
archivemode can only be changed by restarting the server, so the reload did not apply it. Restart PostgreSQL (for example sudo systemctl restart postgresql) and check that SHOW archivemode returns on. To test, run SELECT pgswitchwal(); to complete the current segment, then SELECT archivedcount, lastarchivedwal, failedcount FROM pgstatarchiver; and ls /mnt/archive. archivedcount should increase, failedcount should stay at 0, and a new 24-character segment file should be in the archive directory.