A backup is a promise; a restore is the proof. Data-store reliability means knowing, for every database, queue, bucket, and cluster state store, how much data you can lose (RPO) and how long recovery takes (RTO), and having measured both in a restore drill, not estimated them. Good backups follow the 3-2-1 rule (three copies, two kinds of storage, one off-site), include an immutable copy that ransomware or a compromised admin cannot delete, and are verified automatically by restoring them. This lesson follows one Postgres database through a bad migration, and shows the two failures that drills exist to find: backups that could not be restored, and a restore far slower than anyone had assumed.
Difficulty: Advanced · Know this first: Lesson 228, Lesson 196
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from discovering the deletion to verified data. It is a worked example, not a measurement. The restore test and runbook hops decide whether the RTO is real.
Pick the backup method, how restores are tested, and where the backup lives. The database is 4 TB with an RPO of 1 minute and an RTO of 1 hour.
Three questions. No score is saved anywhere — this is just you against the material.
Backup and restore practice grows in four levels: knowing what is protected, restoring correctly, automating verification, and drilling every scenario.
At the basic level you can say how each data store you own is backed up and to which point you could restore.
Where it breaks: counting a replica as a backup.
Try it: Basic
What is the earliest point you can restore a Postgres database to with base backups and WAL archiving?
Now do it: Find the restore window for one of your databases.
At the intermediate level you can perform a restore safely.
Try it: Intermediate
A migration deleted rows an hour ago. Do you roll the production database back an hour?
Now do it: Practise a point-in-time restore to a new instance.
At the advanced level every backup is proven restorable.
Try it: Advanced
What should an automated restore test check, beyond "the restore command succeeded"?
Now do it: Add two business checks to a restore test.
At the master level recovery is measured for every scenario that matters.
Trade-off: full-size drills cost compute and people's time; the alternative is discovering the real RTO during an outage.
Try it: Master
In a ransomware scenario, which backups can you trust?
Now do it: Check whether your production admins can delete your backups.
Point-in-time recovery with pgBackRest onto a new host, then copying lost rows back (check the pgBackRest documentation for your version; run on a recovery host, never on production):
pgbackrest --stanza=orders info # backups and the WAL range available pgbackrest --stanza=orders --delta --type=time \ --target="2026-11-27 14:11:30+00" --target-action=promote restore # on the NEW host's data directory pg_ctl -D /var/lib/postgresql/16/main start psql -c "SELECT count(*) FROM orders WHERE created_at BETWEEN '2026-11-27 09:00' AND '2026-11-27 14:11'" # after validation, export the lost rows from the restored copy and load them into production psql "$RESTORED" -c "\copy (SELECT * FROM orders WHERE created_at BETWEEN '2026-11-27 09:00' AND '2026-11-27 14:11') TO 'lost_orders.csv' CSV" psql "$PROD" -1 -c "\copy orders FROM 'lost_orders.csv' CSV" # -1: one transaction
Equivalent methods elsewhere: managed point-in-time restore (RDS, Aurora, Azure Database for PostgreSQL, Cloud SQL) always restores to a new instance; MySQL uses XtraBackup plus binlogs; MongoDB uses oplog-based backups; Kubernetes cluster state uses etcd snapshots and Velero for resources and volumes; object storage uses versioning plus replication to a locked bucket.
A restore drill record, per store: date; scenario; backup used; steps with start and end times; measured RTO and RPO; validation done; problems found; actions with owners. Keep the records; they are the evidence auditors ask for and the trend you report.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. Six weeks of failed backups.
pgBackRest with continuous WAL archiving, a locked off-site copy, a nightly automated restore with checks, backup and restore failures paging the owner, and quarterly full-size drills with measured times reported to the reliability review.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: Linux with sqlite3 (sudo apt install sqlite3) and Python 3.
Type each one, read what it prints, and compare it with the note above it.
Make a small database and take an online backup of it.
mkdir -p ~/labs/restore && cd ~/labs/restore && rm -f prod.db backup.db sqlite3 prod.db "CREATE TABLE orders(id INTEGER PRIMARY KEY, total REAL); INSERT INTO orders(total) SELECT abs(random() % 10000)/100.0 FROM generate_series(1, 5000);" 2>/dev/null || sqlite3 prod.db "CREATE TABLE orders(id INTEGER PRIMARY KEY, total REAL); WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<5000) INSERT INTO orders(total) SELECT abs(random() % 10000)/100.0 FROM n;" sqlite3 prod.db ".backup backup.db" ls -la *.db
Make the mistake: delete rows, the way a bad migration would.
sqlite3 prod.db "DELETE FROM orders WHERE id > 4000; SELECT count(*) FROM orders;"
Restore drill: verify the backup, time it, and copy back only the lost rows.
time sqlite3 backup.db "PRAGMA integrity_check; SELECT count(*) FROM orders;" sqlite3 prod.db "ATTACH 'backup.db' AS b; INSERT INTO orders SELECT * FROM b.orders WHERE id > 4000 AND id NOT IN (SELECT id FROM orders); SELECT count(*) FROM orders;"
restore_drill.pyThis program audits a month of backups the way an automated restore test would (failed jobs, gaps in the change log), performs a point-in-time recovery from a base backup plus a change log to just before a bad change, and estimates the full-size restore time from data size, storage tier, and replay volume, against the RTO. Save it as restore_drill.py, then run it.
# restore_drill.py
BACKUPS = [(day, "ok" if day < 17 else "FAILED: auth error") for day in range(1, 31)] # nightly jobs, November
WAL_DAYS = set(range(1, 31)) - {22} # one gap in the archive
last_good = max(d for d, s in BACKUPS if s == "ok")
print(f"last restorable base backup: Nov {last_good}; failed since: {sum(1 for d, s in BACKUPS if s != 'ok')} nights")
gaps = sorted(set(range(last_good, 31)) - WAL_DAYS)
print(f"change-log gaps after it: {['Nov %d' % d for d in gaps] or 'none'} -> point-in-time recovery stops at the first gap")
print()
base = {1: 120.0, 2: 80.0, 3: 45.5} # orders at the base backup
log = [("10:02", "insert", 4, 19.9), ("10:40", "update", 2, 82.0), ("14:11", "insert", 5, 30.0),
("14:12", "delete-all", None, None), ("14:20", "insert", 6, 12.0)]
def recover(target):
db = dict(base)
for t, op, k, v in log:
if t > target:
break
if op in ("insert", "update"):
db[k] = v
elif op == "delete-all":
db.clear()
return db
restored = recover("14:11")
print("recovered to 14:11:", restored)
print("production after 14:12 has only:", recover("14:20"))
print("copy back the rows production is missing, keep row 6 written after the mistake")
print()
def restore_hours(size_tb, tier, wal_gb):
retrieve = {"standard": 0.0, "cold": 5.0}[tier] # hours to retrieve from the tier before copying
copy_h = size_tb * 1024 * 1024 / 3000 / 3600 # parallel restore at about 3 GB/s
replay_h = wal_gb / 40 # 40 GB of WAL replayed per hour
return retrieve + copy_h + replay_h
for size, tier, wal in ((0.02, "standard", 2), (4, "standard", 10), (4, "cold", 160)):
h = restore_hours(size, tier, wal)
print(f"{size:>5} TB from {tier:<8} tier, {wal:>3} GB of WAL: {h:5.1f} h {'within' if h <= 1 else 'MISSES'} the 1 h RTO")
Run it, and you should see this output:
$ python3 restore_drill.py
last restorable base backup: Nov 16; failed since: 14 nights
change-log gaps after it: ['Nov 22'] -> point-in-time recovery stops at the first gap
recovered to 14:11: {1: 120.0, 2: 82.0, 3: 45.5, 4: 19.9, 5: 30.0}
production after 14:12 has only: {6: 12.0}
copy back the rows production is missing, keep row 6 written after the mistake
0.02 TB from standard tier, 2 GB of WAL: 0.1 h within the 1 h RTO
4 TB from standard tier, 10 GB of WAL: 0.6 h within the 1 h RTO
4 TB from cold tier, 160 GB of WAL: 9.4 h MISSES the 1 h RTO
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/backup-and-restore-drills-and-data-store-reliability && cd ~/labs/backup-and-restore-drills-and-data-store-reliability) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Backup and Restore Drills: Proving RTO and RPO for Every Data Store", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Make a small database and take an online backup of it.'
'Make the mistake: delete rows, the way a bad migration would.'
'Restore drill: verify the backup, time it, and copy back only the lost rows.'
)
step_1() {
mkdir -p ~/labs/restore && cd ~/labs/restore && rm -f prod.db backup.db
sqlite3 prod.db "CREATE TABLE orders(id INTEGER PRIMARY KEY, total REAL); INSERT INTO orders(total) SELECT abs(random() % 10000)/100.0 FROM generate_series(1, 5000);" 2>/dev/null || sqlite3 prod.db "CREATE TABLE orders(id INTEGER PRIMARY KEY, total REAL); WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<5000) INSERT INTO orders(total) SELECT abs(random() % 10000)/100.0 FROM n;"
sqlite3 prod.db ".backup backup.db"
ls -la *.db
}
step_2() {
sqlite3 prod.db "DELETE FROM orders WHERE id > 4000; SELECT count(*) FROM orders;"
}
step_3() {
time sqlite3 backup.db "PRAGMA integrity_check; SELECT count(*) FROM orders;"
sqlite3 prod.db "ATTACH 'backup.db' AS b; INSERT INTO orders SELECT * FROM b.orders WHERE id > 4000 AND id NOT IN (SELECT id FROM orders); SELECT count(*) FROM orders;"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
mkdir, rm, ls, cd, Pipes, Redirection, If...Else.Your company has 40 data stores, nightly backups for most, and has never done a full restore. Design its backup, verification, and drill programme.
How do you inventory and tier the stores? What RPO and RTO apply, per scenario? Which backup method for each type? Where do immutable copies live? How are restores tested automatically? How often are full-size drills done, and what is reported?
Say 40 stores (12 Postgres, 6 MySQL, 4 MongoDB, Kafka, Redis, object storage, etcd, Vault), the largest 6 TB, and tier-1 targets of RPO 1 minute and RTO 1 hour.
An inventory with owners and tiers; RPO and RTO per scenario signed off; point-in-time backups (pgBackRest, XtraBackup with binlogs, oplog backups) for databases, versioning plus locked replication for object storage, etcd snapshots and Velero for clusters, Vault snapshots; an off-site backup account with object or vault lock; nightly automated restores with integrity and business checks and paging on failure; quarterly full-size drills for tier 1, yearly Region-loss and ransomware drills; measured RTO and RPO reported monthly.
Continuous archiving and locked copies add storage cost; nightly restore tests cost compute; full-size drills take team time, and they replace guesses with numbers you can promise.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Backups never restored | Hop 5: Automated restore test | Breaks | Backups are never restored, and the backup job's failures go to a log nobody reads. A credentials rotation six weeks earlier broke the nightly pg_dump; every run since has failed. With no WAL archive, the newest usable backup is six weeks old. |
| Restore never timed | Hop 6: Restore runbook | Breaks | The runbook was timed on a 20 GB sample. The full 4 TB restore pulls the base backup from a cold archive tier (hours to retrieve), then replays a day of WAL. It takes 11 hours. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.