Sub topic 15
Testing restores
A backup you have never restored is a hope, not a backup. This chapter covers how to prove that your dumps are usable, how to measure how long a recovery takes, and how to turn those measurements into recovery objectives.
It assumes you can already take a logical backup with pg_dump or mysqldump, that you are comfortable with sudo and systemd, and that you know basic SQL. It builds on the backup chapter and uses the same appdb database.
Why restores fail
A dump file can exist, have a plausible size, and still be useless. Common causes are:
- The dump was truncated because the disk filled up or the job was killed.
- The dump command failed, but a wrapper script ignored the exit code and kept the empty file.
- Objects such as roles, extensions, stored routines or events were not included.
- The restoring server is a different version, or lacks an extension the dump needs.
- The credentials or storage location needed during a restore were never documented.
- The dump was taken on the same host that later failed, so it was lost together with the data.
Only a real restore into a working server finds these problems before an incident does.
Restore into a scratch database
The rule is to restore into a separate scratch database, never over production. A scratch database has a different name, so a mistake cannot overwrite live data.
# PostgreSQL: custom-format dump, then restore into a scratch database
pg_dump -Fc -f appdb.dump appdb
createdb appdb_restore_test
pg_restore --dbname=appdb_restore_test --exit-on-error appdb.dump
# MySQL: consistent dump of InnoDB tables, then restore into a scratch database
mysqldump --single-transaction --routines --events appdb > appdb.sql
mysql -e 'CREATE DATABASE appdb_restore_test'
mysql appdb_restore_test < appdb.sqlTwo details matter here:
pg_restorenormally continues after errors and reports a count at the end. Add--exit-on-errorin a test so that the first problem stops the run and fails the check.mysqldump --single-transactiongives a consistent snapshot only for InnoDB tables. MyISAM tables are not protected by it.
Run these commands as a user that has the privileges to create databases. The scratch database may also need the same roles and extensions as production. If pg_restore complains about a missing role, that is a useful finding: your backup procedure must also capture roles, for example with pg_dumpall --globals-only.
Verify the content, not just the exit code
A restore that finishes without errors proves the file is readable. It does not prove the data is complete. Compare something measurable between the source and the restored copy.
# PostgreSQL: compare row counts for a key table
psql -d appdb -Atc 'SELECT count(*) FROM orders'
psql -d appdb_restore_test -Atc 'SELECT count(*) FROM orders'
# MySQL: the same check
mysql -N -e 'SELECT COUNT(*) FROM appdb.orders'
mysql -N -e 'SELECT COUNT(*) FROM appdb_restore_test.orders'The counts can differ slightly if the live database took writes after the dump started. Compare against the numbers recorded at dump time, or against a table that does not change often. Better checks include:
- The newest timestamp in a table that records events.
- A checksum of a stable column, such as
SELECT md5(string_agg(id::text, ',' ORDER BY id)) FROM customersin PostgreSQL. - A short list of queries the application actually depends on.
- A table-by-table count of tables, views, indexes and routines.
Automate the test
A manual test happens once. A scheduled test keeps happening. The script below restores the latest PostgreSQL dump, checks it, records the elapsed time, and always removes the scratch database.
#!/usr/bin/env bash
set -euo pipefail
DUMP="${1:?usage: restore-test.sh /path/to/appdb.dump}"
SCRATCH="appdb_restore_test"
cleanup() { dropdb --if-exists "$SCRATCH"; }
trap cleanup EXIT
dropdb --if-exists "$SCRATCH"
createdb "$SCRATCH"
START=$(date +%s)
pg_restore --dbname="$SCRATCH" --exit-on-error "$DUMP"
END=$(date +%s)
TABLES=$(psql -d "$SCRATCH" -Atc \
"SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public'")
if [ "$TABLES" -lt 1 ]; then
echo "FAIL: restored database has no tables" >&2
exit 1
fi
echo "OK: restored $TABLES tables in $((END - START)) seconds"Because of set -e and the EXIT trap, a failure still exits non-zero and still cleans up. Run it from a systemd timer or cron job and alert on a non-zero exit. A timer that nobody monitors is no better than no timer.
Measure recovery objectives
Restore tests give you real numbers for two terms that are often guessed.
- Recovery point objective (RPO) is how much recent data you can afford to lose, measured in time. A nightly dump gives an RPO of up to 24 hours.
- Recovery time objective (RTO) is how long the service can stay down before the damage becomes unacceptable.
The elapsed time printed by the script is the restore portion of your RTO. A full recovery also includes provisioning or repairing a host, installing the same server version, fetching the backup, restoring, and repointing applications. Time each step at least once.
| Question | Where the answer comes from |
|---|---|
| How much data could we lose? | Backup schedule, and whether transaction logs or binary logs are also kept |
| How long does the restore take? | The timed restore test |
| Does the backup contain everything? | Comparing roles, extensions, routines and counts |
| Can someone else do it? | A teammate following the written runbook |
Restore time grows with data size. A dump that restores in two minutes today can take hours after the database grows. Keep the timings from each run and watch the trend.
# Append each result to a log you can graph or review later
echo "$(date -Is) restore_seconds=$((END - START))" >> /var/log/db-restore-tests.logEdge cases
- Restoring on a different version. A dump from an older major version generally loads into a newer one. The reverse often fails. Test against the version you would actually run during recovery.
- Large databases. A logical restore must rebuild every index, which is slow. If the measured time exceeds your RTO, you need physical backups or replicas, covered in later chapters.
- Encrypted or remote backups. Include the download and decryption in the test. Losing the key makes the backup worthless.
- Disk space. The scratch database needs room for the full data plus indexes. Check free space before the run so the test does not fill the volume that production uses. Ideally, run it on a separate host.
- Sensitive data. A scratch copy holds real data. Apply the same access controls, and drop it afterwards.
Practice
Exercise
A nightly PostgreSQL dump restores with no errors into a scratch database, but the application team says rows from the last two days are missing. Which restore-test practice would have caught this, and which recovery objective does the nightly schedule limit?
Show answer
Comparing content between the source and the restored copy, such as the newest timestamp in an events table or a row count recorded at dump time, would have shown the gap. A clean exit code only proves the file could be read. The nightly schedule limits the recovery point objective (RPO), since up to 24 hours of changes can be lost. Two missing days suggests the dump job was silently failing or reusing an old file, so the script should also check the dump's age and the exit code of the dump command.
Exercise
Your timed restore of a MySQL dump takes 3 hours, but the business requires the service to be back within 1 hour. Name two things you would investigate or change.
Show answer
First, confirm the full RTO by timing every step, not just the restore. Then consider changes that shorten recovery: physical backups, which copy data files instead of rebuilding indexes from SQL, or a replica that can be promoted quickly. Reducing database size by archiving old data also helps. A faster disk or tuning the restore settings may help, but they are unlikely to turn 3 hours into under 1 without changing the backup method.