Sub topic 4
Making archive_command safe
This chapter assumes you have read the previous chapter on turning on continuous archiving. You should know that archive_mode = on makes PostgreSQL run archive_command for each completed WAL segment. You should also be comfortable with shell scripts, file permissions, and reloading PostgreSQL configuration.
The command in the previous chapter works on a quiet test system. In production it has failure modes that can stall archiving or leave a damaged file in your archive. This chapter covers the contract PostgreSQL expects from the command, how the one-line version breaks, and a script that holds up.
The contract between PostgreSQL and your command
PostgreSQL decides whether a segment was archived by looking at one thing: the exit status of the command.
- Exit status 0 means the segment is safely stored. PostgreSQL may now recycle or remove the local copy in
pg_wal. - Any non-zero exit status means the segment was not archived. PostgreSQL logs the failure, keeps the segment, and retries the same segment after a short delay.
- Segments are archived in order. If one segment keeps failing, later segments wait behind it.
- The command runs as the operating system user that owns the server process, with the data directory as its working directory.
%pis the path of the segment relative to that directory.%fis the file name only. Write%%for a literal percent sign. - The command is also run for timeline history files, such as
00000002.history, and for.partialfiles after a promotion. Your command must handle any file name PostgreSQL passes and must not assume a 24-character segment name.
A command that returns 0 without storing the file is the worst case. PostgreSQL deletes the only copy, and you find the gap during a restore.
A command that fails forever is less dangerous but still serious. Unarchived segments pile up in pg_wal. If the disk fills, the server stops accepting writes and may shut down.
How the one-line command fails
The example from the previous chapter was:
archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'The test ! -f part is a good idea. It refuses to overwrite an existing archive file, which protects you if two clusters accidentally share one archive. The rest has several weaknesses.
| Situation | What happens with the one-liner |
|---|---|
| `cp` is interrupted halfway (disk full, network mount drops, process killed) | A partial file stays at the final name. Every retry fails at `test ! -f`, so archiving is stuck. If the partial file is later left alone or removed by hand, a restore may read a truncated segment. |
| The copy completes and the file is written, but the machine crashes before the data reaches disk | The archive holds a file that is empty or short after reboot, but PostgreSQL already considered it archived. |
| `cp` succeeds, but PostgreSQL crashes before recording success | After restart the archiver retries the same segment. `test ! -f` now fails, so archiving is stuck even though the archived copy is fine. |
| The archive is on the same disk as the data directory | Both fail together. This is a placement mistake rather than a command bug, but the one-liner does nothing to catch it. |
Two properties fix most of these. The first is that the file appears at its final name only when it is complete and on disk. The second is that the command is idempotent. If the same segment is submitted again and the archived copy is identical, the command reports success.
A safer script
The script below copies to a temporary name in the archive directory, flushes it to disk, and then publishes it with a hard link. ln fails if the destination exists, so publishing is atomic and never overwrites. If the file already exists, the script compares contents. Identical content is success, and different content is a failure that needs a human.
#!/bin/bash
# /usr/local/bin/archive_wal.sh (owned by postgres, mode 0750)
# Usage: archive_wal.sh <path-from-%p> <name-from-%f>
set -euo pipefail
src="$1"
name="$2"
dest_dir=/mnt/archive
dest="$dest_dir/$name"
tmp="$dest_dir/.$name.tmp.$$"
trap 'rm -f "$tmp"' EXIT
# Already archived? Identical content means a harmless retry.
if [ -e "$dest" ]; then
if cmp -s "$src" "$dest"; then
exit 0
fi
echo "archive_wal: $name exists in archive with different content" >&2
exit 1
fi
cp "$src" "$tmp" # write under a hidden temporary name
sync "$tmp" # flush file data to disk
ln "$tmp" "$dest" # atomic publish; fails if $dest appeared meanwhile
sync "$dest_dir" # flush the directory entryPoint PostgreSQL at it:
# postgresql.conf
archive_command = '/usr/local/bin/archive_wal.sh %p %f'You can change archive_command with a reload (SELECT pg_reload_conf();). Only archive_mode needs a restart.
The decision flow of the script is:
Details worth knowing:
set -euo pipefailmakes any failed step end the script with a non-zero status. Without it, a failedcpfollowed by a successful later command could return 0.- The
trapremoves the temporary file on exit. After a hard crash, a stale.name.tmp.NNNNfile may remain. It has a dot prefix and no valid segment name, so recovery never reads it, but remove such files during housekeeping. - Comparing with
cmpcosts a read of both files, 16 MB each by default. This only happens on a retry, so the cost is small. syncwith a file argument needs GNU coreutils 8.24 or later. On older systems use a small program orpython3 -cthat callsos.fsync.
Archiving off the machine
The archive should live in a different failure domain from the data directory: another host, a network share, or object storage. If you use rsync, scp, or a cloud CLI, the same two rules apply. The file must not appear at its final name until it is complete, and a retry of an identical segment must succeed.
Object stores publish an object only when the upload completes, so the temporary-name step is not needed there. You still need to treat "already exists with identical content" as success and "already exists with different content" as an error. For anything beyond a small setup, the tools covered later in this tutorial (pgBackRest, Barman, WAL-G) implement these rules, plus compression and parallel transfer, so you do not maintain them yourself.
PostgreSQL 15 and later also offer archive_library, which loads a shared library instead of running a shell command. The bundled basic_archive module copies through a temporary file, fsyncs it, and renames it into place. It is a reasonable alternative if you want the safe behavior without writing a script. You set either archive_library or archive_command, not both.
Testing the command before you rely on it
Test the script as the postgres user, outside the server, with a fake segment:
sudo -u postgres bash -c '
head -c 16777216 /dev/urandom > /tmp/000000010000000000000099
/usr/local/bin/archive_wal.sh /tmp/000000010000000000000099 000000010000000000000099; echo "first: $?"
/usr/local/bin/archive_wal.sh /tmp/000000010000000000000099 000000010000000000000099; echo "retry: $?"
head -c 16777216 /dev/urandom > /tmp/other
/usr/local/bin/archive_wal.sh /tmp/other 000000010000000000000099; echo "different: $?"
rm -f /mnt/archive/000000010000000000000099 /tmp/000000010000000000000099 /tmp/other
'The expected output is first: 0, retry: 0, and different: 1. Also try it with /mnt/archive unwritable, or on a full filesystem, to confirm it exits non-zero and leaves no file at the final name.
After enabling it on the server, force a switch with SELECT pg_switch_wal(); and check that pg_stat_archiver shows archived_count increasing and failed_count staying put. The PostgreSQL log also records each failure with the command's stderr output, so write useful messages to stderr as the script does.
Recovering from a stuck archiver
If failed_count climbs and last_failed_wal never changes, the archiver is stuck on one segment. Read the server log for the reason. Common causes are a full or unmounted archive volume, wrong permissions, or the "exists with different content" error from the script.
Fix the cause, and the next retry succeeds on its own. You do not restart PostgreSQL. Do not delete segments from pg_wal by hand to free space. That creates a permanent gap in the archive, and every backup taken before the gap becomes unusable for recovery past it.
Exercise
Your archive volume fills up overnight and cp fails midway through writing a segment. Using the one-line command test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f, what state is the archive in once you free space, and why does the script in this chapter avoid it?
Show answer
The truncated segment remains at its final name. Every retry now fails at test ! -f because the file exists, so archiving stays stuck even after space is freed, and the archive holds a bad copy. The script writes to a hidden temporary name and publishes it with ln only after cp and sync succeed, so a failed copy never appears at the final name. The trap removes the temporary file, and the next retry starts clean.
Exercise
PostgreSQL crashes right after the script publishes segment 000000010000000000000042 but before it records the success. After restart the archiver submits the same segment again. What does the script do, and what would it do if the archived copy had different content?
Show answer
The destination exists, and cmp -s finds the contents identical, so the script exits 0 and PostgreSQL treats the segment as archived. If the content differed, the script would write an error to stderr and exit 1. Archiving would stop on that segment until an administrator investigated, for example because two clusters share one archive.