Sub topic 14
Proving the backups work with test restores
A base backup and a WAL archive only count as a backup once you have restored from them. This chapter shows how to run a repeatable test restore. It covers what the restore must prove, a script that does it, and the failures it tends to catch.
It assumes you have configured archiving, taken a base backup with pg_basebackup, and run a recovery with restore_command and recovery.signal. It also assumes you can read the PostgreSQL server log.
What a test restore must prove
A backup can fail in ways that stay silent until the day you need it. A test restore turns each of those failures into an error you see ahead of time.
| Risk | How a test restore exposes it |
|---|---|
| The base backup is incomplete or corrupt | The server cannot reach a consistent state at startup |
| A WAL segment is missing from the archive | Recovery stops early, or fails with "could not open file" for a segment |
| `restore_command` is wrong or lacks permissions | Recovery cannot fetch any archived segment |
| The target is unreachable | The server fails with "recovery ended before configured recovery target was reached" |
| Data is damaged although recovery succeeded | Validation queries or a full dump fail |
| Recovery is too slow | The measured duration exceeds your recovery time objective (RTO) |
A running standby does not replace this. A standby shows that streaming replication works. It does not show that your archive and base backups can rebuild a cluster, and it will faithfully replay an accidental DROP TABLE.
The shape of a test
Run the test on a scratch machine or a scratch directory. It must never touch the production data directory or the production archive.
A restore-test script
The script below assumes a few things:
- It runs as the
postgresOS user. - The base backup is a plain-format copy that contains
postgresql.conf. - The WAL needed by the backup was streamed into it with
-X stream. - The application database is named
appdband has anorderstable with acreated_atcolumn. Replace these with your own names.
#!/usr/bin/env bash
set -euo pipefail
BACKUP=/backups/base/20261127
ARCHIVE=/mnt/archive
TARGET='2026-11-27 14:30:00+00'
PGBIN=/usr/lib/postgresql/16/bin
PORT=5440
RESTORE_DIR=$(mktemp -d /var/tmp/restore-test.XXXXXX)
LOG="$RESTORE_DIR/restore.log"
cp -a "$BACKUP"/. "$RESTORE_DIR"/
chmod 700 "$RESTORE_DIR"
rm -f "$RESTORE_DIR/postmaster.pid"
cat >> "$RESTORE_DIR/postgresql.auto.conf" <<EOF
port = $PORT
listen_addresses = ''
unix_socket_directories = '$RESTORE_DIR'
archive_mode = off
restore_command = 'cp $ARCHIVE/%f "%p"'
recovery_target_time = '$TARGET'
recovery_target_action = 'promote'
EOF
touch "$RESTORE_DIR/recovery.signal"
"$PGBIN/pg_ctl" -D "$RESTORE_DIR" -l "$LOG" start
state=t
for _ in $(seq 1 720); do
state=$("$PGBIN/psql" -h "$RESTORE_DIR" -p "$PORT" -U postgres -d postgres \
-Atc 'SELECT pg_is_in_recovery()' 2>/dev/null || echo t)
[ "$state" = f ] && break
sleep 5
done
if [ "$state" != f ]; then
echo "recovery did not finish; last log lines:" >&2
tail -n 30 "$LOG" >&2
exit 1
fi
grep -E "archive recovery complete|selected new timeline" "$LOG"
"$PGBIN/psql" -h "$RESTORE_DIR" -p "$PORT" -U postgres -d appdb \
-Atc 'SELECT max(created_at) FROM orders'
"$PGBIN/pg_dump" -h "$RESTORE_DIR" -p "$PORT" -U postgres -d appdb -Fc -f /dev/null
"$PGBIN/pg_ctl" -D "$RESTORE_DIR" stop -m fast
echo "restore test passed in ${SECONDS}s (RTO evidence)"Several lines in this script matter:
archive_mode = offstops the restored copy from archiving WAL (see the warning below).listen_addresses = ''and a private socket directory keep the test server off the network and away from production sockets.rm -f postmaster.pidremoves a leftover PID file that a backup taken from a running server may contain.pg_basebackupnormally excludes it, but a file-level copy may not.- The wait loop polls
pg_is_in_recovery()instead of relying onpg_ctl -w. With hot standby enabled (the default), the server accepts connections as soon as it is consistent, which can be long before it reaches your target. recovery_target_action = 'promote'lets the script continue unattended. The default action,pause, would leave the loop waiting forever.SECONDSis a Bash built-in that counts seconds since the script started. Record it on every run and watch the trend.
Test different targets
One target does not cover everything. Vary what you ask recovery to do:
recovery_target = 'immediate'stops as soon as the base backup is consistent. This tests the base backup and its streamed WAL, and does not touch the archive.- No target at all replays the whole archive to its end. This checks that the segment chain is unbroken from the backup to the newest file.
- A recent
recovery_target_timechecks that recovery stops where you expect. Compare the result ofmax(created_at)with the target. It should be at or just before the target, never after. - A named restore point created before risky changes confirms that the label is in the archived WAL. See the earlier chapter on restore points.
If you run the test nightly, rotate through these targets so that each one is exercised regularly.
Validate the data, not only the startup
A server that starts and promotes proves the WAL replayed. It does not prove the data is intact. Layer a few checks:
- Log lines. Look for
archive recovery completeand for aselected new timeline IDmessage. A time or transaction target also logs arecovery stopping before/after ...line that names the exact transaction where replay stopped. - Freshness query. Compare the newest timestamp in a busy table against the target, as in the script.
- A full dump.
pg_dumpto/dev/nullreads every row of every table, so it surfaces unreadable pages and damaged TOAST data. It does not read indexes. - Index checks. If the
amcheckextension is installed,pg_amcheckverifies B-tree indexes and heap structure. - Application checks. Row counts for key tables, referential spot checks, or a small read-only test suite from your application.
Failures a test restore tends to catch
| Message in the log | Usual cause |
|---|---|
| `WAL ends before end of online backup` | WAL generated during the backup is missing. Streaming was not used, or the files were deleted before the copy finished. |
| `could not locate required checkpoint record` | `backup_label` is missing, or the wrong directory was restored. |
| `could not open file "pg_wal/..." ` followed by recovery stopping early | A gap in the archive, or `restore_command` points at the wrong path. |
| `recovery ended before configured recovery target was reached` | The target is later than the last archived WAL, or the archive is stale. |
| `requested timeline N is not a child of this server's history` | The base backup and the target timeline are from different branches of history. |
| Permission denied from `cp` | The user running recovery cannot read the archive directory. |
Fixing a test failure is cheap. The same failure during a real outage takes much longer to fix.
Scheduling and records
Make the test routine:
- Run it automatically, at least weekly and ideally after every new base backup.
- Alert on a non-zero exit or on a missing success record.
- Store the duration of each run. A restore that took 20 minutes last quarter and takes 3 hours now is a capacity warning.
- Restore on hardware similar to production when you can. Replay speed depends on disk and CPU, so a fast scratch machine can understate your real RTO.
- Test at least once with the same credentials and decryption keys that an on-call engineer would have at 3 a.m. If the archive is encrypted or lives in another account, include that step.
Exercise
Your nightly restore test starts the server and pg_ctl -w start returns success after a few seconds, so the script reports a pass. Weeks later, a real recovery stops at the wrong time. What was wrong with the test, and how do you fix it?
Show answer
With hot standby enabled, the server accepts connections once it reaches a consistent state, which can be well before it reaches the recovery target. A successful pg_ctl -w therefore says nothing about whether replay finished or reached the target. Fix the script to poll SELECT pg_is_in_recovery() until it returns false, set recovery_target_action = 'promote' so recovery ends on its own, check the log for archive recovery complete, and compare a freshness query such as max(created_at) against the target time.
Exercise
Why must a restore test set archive_mode = off (or use a scratch archive), and what can go wrong if it does not?
Show answer
When recovery ends, the server archives the last partial WAL segment and the timeline history file using the configured archive_command. If the restored copy still points at the production archive, it can write files there that collide with or overwrite files from the real cluster's history, which can corrupt the archive you depend on for recovery.