Sub topic 12
Proving a backup works: test restores
This chapter assumes you can run pg_dump, pg_restore and pg_basebackup as shown in the earlier chapters. It also assumes you know what WAL archiving and recovery.signal do, and that you have a second machine, container or scratch directory to restore into.
A backup is only a hypothesis
A backup file existing does not mean you can restore it. Until a restore has succeeded, you only believe the backup works. These failures often stay hidden until the day you need the backup:
- The dump job exited early, or a pipe hid a failure, so the file is truncated.
- The dump is fine, but the roles it refers to were never saved with
pg_dumpall --globals-only. - The base backup is fine, but a WAL segment is missing from the archive, so recovery stops before your target.
archive_commandhas been failing for days, and nobody noticed that the archive stopped growing.- The restore works but takes six hours, and your recovery time objective (RTO) is one hour.
- The backup is encrypted and the key lives only on the server that just died.
A test restore finds all of these. It also gives you a measured restore time, which is the only honest input to an RTO.
Levels of verification
Checks differ in cost and in what they prove. Use the cheap ones on every backup and the expensive ones on a schedule.
| Check | What it proves | What it misses |
|---|---|---|
| Job exit status, file size, checksum | The job finished and the file was not altered in transit | Whether the content is usable |
| `pg_restore --list` | The custom or directory dump has a readable table of contents | Whether table data restores |
| `pg_verifybackup` | A plain-format base backup matches its backup manifest (needs PostgreSQL 13 or later) | Whether the archived WAL completes recovery |
| Full test restore | The data loads, and the restore time is realistic | Whether the application's queries return correct results |
| Test restore plus application checks | The restored data is usable for your workload | Corruption that already existed in the source |
The cheapest useful check from the earlier chapters is listing the table of contents:
pg_restore --list mydb.dump | head -n 20If this fails, the file is damaged. If it succeeds, you have learned only that the header and catalog are readable.
Testing a logical backup
A logical test restore creates a scratch database, loads the dump, stops at the first error, and runs a few queries. This script does that:
#!/usr/bin/env bash
set -euo pipefail
DUMP=${1:?usage: verify_dump.sh DUMPFILE}
SCRATCH="verify_$(date +%Y%m%d_%H%M%S)"
pg_restore --list "$DUMP" > /dev/null
createdb -U postgres "$SCRATCH"
trap 'dropdb -U postgres --if-exists "$SCRATCH"' EXIT
start=$(date +%s)
pg_restore -U postgres -d "$SCRATCH" --no-owner --exit-on-error -j 4 "$DUMP"
elapsed=$(( $(date +%s) - start ))
# Replace "orders" with a table that must never be empty in your database.
rows=$(psql -U postgres -d "$SCRATCH" -Atc "SELECT count(*) FROM orders")
test "$rows" -gt 0
echo "restore ok: ${rows} rows in orders, ${elapsed}s"Several choices in this script matter:
set -euo pipefailmakes the script stop on the first failed command. Withoutpipefail, a command such aspg_dump ... | gzip > filereports success even whenpg_dumpfails.--exit-on-errorstopspg_restoreat the first SQL error. By default it continues and prints a summary of errors at the end, which is easy to miss in an automated job.- The
trapdrops the scratch database even when a check fails, so failed runs do not pile up. --no-ownerlets the restore work without the original roles. That is convenient, but it hides a missing-globals problem. Run a full drill at least once, without--no-owner, on a fresh cluster. Replayglobals.sqlfirst, then restore the dump. This proves that the roles and the dump work together.- The elapsed time is recorded. Log it, and watch the trend as the database grows.
Restoring a plain SQL dump follows the same idea. Use the single-transaction form from the restore chapter, so a failure leaves an empty scratch database instead of a half-loaded one:
psql -U postgres -d mydb_restored -v ON_ERROR_STOP=1 --single-transaction -f mydb.sqlAfter any restore, run ANALYZE. Dumps contain data and definitions, but not planner statistics. A freshly restored database can run slowly until statistics exist, and you want to know that before an incident.
Testing a physical backup and WAL archive
A physical test restore proves more, because it exercises the base backup and the whole chain of archived WAL. The steps below assume the base backup was taken with -Ft -z -Xs, so it consists of base.tar.gz and pg_wal.tar.gz. Run them on a scratch host.
RESTORE=/var/lib/postgresql/restore_test
mkdir -p "$RESTORE/pg_wal"
tar -xzf /backups/base/base.tar.gz -C "$RESTORE"
tar -xzf /backups/base/pg_wal.tar.gz -C "$RESTORE/pg_wal"
chmod 700 "$RESTORE"
cat >> "$RESTORE/postgresql.conf" <<'EOF'
port = 5433
archive_mode = off
restore_command = 'cp /mnt/archive/%f %p'
recovery_target_time = '2026-11-27 10:15:00+00'
recovery_target_action = 'promote'
EOF
touch "$RESTORE/recovery.signal"
pg_ctl -D "$RESTORE" -w start
psql -p 5433 -U postgres -Atc "SELECT pg_is_in_recovery()"The last query should print f. If it prints t, recovery has not finished, or the server paused before reaching a target. Read the server log.
- Turn archiving off in the restored copy. The base backup contains the production
archive_modeandarchive_command. A test server that keeps them would start writing its own WAL into the production archive, and that can corrupt your real recovery path. Thearchive_mode = offline above prevents this. - Use a different port. Port 5433 keeps the test instance away from a live server on the same host.
- Read the log for the right lines. A successful recovery logs
archive recovery completeand thendatabase system is ready to accept connections. A recovery that stops withcould not open filefor a WAL segment means the archive has a gap. - Choose a target time inside your WAL range. If the target is later than the last archived WAL, recovery ends without reaching it, and the log says so.
Once the instance is up, run the same application-level queries as for the logical test, then stop it with pg_ctl -D "$RESTORE" stop and delete the directory.
What a restore does not prove
A successful test restore shows that the backup holds the data as it existed in the source. It does not show that the data was healthy.
- A logical restore rebuilds every index from table data, so it can mask a corrupted index in the source.
- A physical restore copies corruption faithfully. If the source had a damaged page, so does the backup.
Two tools help here. Create clusters with data checksums (initdb --data-checksums) so PostgreSQL detects damaged pages when it reads them. On PostgreSQL 14 and later, run pg_amcheck against the restored copy to check tables and B-tree indexes. Running it on the restored copy keeps the load off production.
Making verification routine
A drill you run once does not protect you for long. Put the checks into the schedule:
- Run the cheap checks (exit status, file size,
pg_restore --list) after every backup, and alert on any failure. - Run a full test restore automatically on a fixed schedule. Weekly suits many systems, and nightly suits critical ones.
- Run a full physical recovery with a time target at least monthly, using a target time you pick at random from the last week.
- Record the restore duration each time, and compare it with your RTO. If the trend is heading past it, change the approach before the deadline arrives. Options include parallel jobs, a faster disk, or a physical backup instead of a dump.
- Check that the archive keeps growing. A monitor that compares the newest archived WAL file's age with a threshold catches a silent
archive_commandfailure within minutes. - Write a short runbook with the exact commands, and have someone who did not write it follow it. Restore procedures usually fail on missing steps, such as where the encryption key is stored.
Common mistakes
- Treating
pg_dumpexit code 0 as proof of a good restore. The dump can be complete and still depend on roles, extensions or tablespaces that the target lacks. - Restoring onto the same server that holds the live database, which risks name clashes and extra load. Use a separate instance.
- Testing on a machine with a different major version or missing extensions than your real recovery target. Match the version, or you test a different system.
- Verifying only the newest backup. Occasionally test an older one too, because that is the one you need if corruption went unnoticed for days.
Exercise
Your nightly job runs pg_dump -Fc mydb > mydb.dump and then pg_restore --list mydb.dump, and both succeed. Name two failures a full test restore could still reveal, and name one setting that makes the restore stop at the first error.
Show answer
Possible failures: a role referenced by ownership or grants does not exist on the target because globals were not saved; a required extension is not installed; the data fails to load because of a bad row or constraint problem; the restore takes longer than the RTO. pg_restore --exit-on-error (or ON_ERROR_STOP=1 with psql for plain dumps) stops at the first error.
Exercise
You restore a base backup into a scratch directory, add a restore_command, create recovery.signal and start the server. The log shows it stuck waiting for a WAL file and never reaching your target time. What is the likely cause, and which setting must you change in the restored copy before starting it so it cannot damage the production archive?
Show answer
The archive probably has a gap or is missing the WAL segment that covers the target time, for example because archive_command failed for a period, or the target is later than the last archived WAL. Set archive_mode = off in the restored copy so it does not write into the production archive.