Platform Engineering · Lesson 229

Backup and Restore Drills: Proving RTO and RPO for Every Data Store

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: will the restore meet its targets?

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.

under 1 mindata lost
55 minto verified data
measuredRTO is

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Backup and restore practice grows in four levels: knowing what is protected, restoring correctly, automating verification, and drilling every scenario.

Basic — Know what is protected

At the basic level you can say how each data store you own is backed up and to which point you could restore.

  • Full backups, change logs, point-in-time recovery; replicas versus backups.
  • RPO and RTO per store and scenario.
  • Where backups live and who can delete them.

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.

Intermediate — Restore correctly

At the intermediate level you can perform a restore safely.

  • Point-in-time recovery to a new instance beside production.
  • Finding the target time from audit or migration logs.
  • Validating restored data against an independent source before using it.

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.

Advanced — Automate verification

At the advanced level every backup is proven restorable.

  • Nightly automated restores with integrity and business checks, timed and alerted.
  • Backup job failures page the owner.
  • Immutable copies in a separate account; keys available after an incident.

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.

Master — Drill every scenario

At the master level recovery is measured for every scenario that matters.

  • Full-size quarterly drills for tier-1 stores; yearly Region-loss and ransomware drills.
  • Measured RTO and RPO reported like SLOs; gaps funded and fixed.
  • Recovery for platform state too: etcd, secrets stores, cluster configuration in Git.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. Six weeks of failed backups.

Timeline

  • Week 0The database password is rotated. The nightly pg_dump job keeps the old one and starts failing; its errors go to a log file.
  • Week 6, 14:12A migration with a wrong WHERE clause deletes 40,000 order rows.
  • 14:30The team goes to restore and finds the newest successful dump is six weeks old. WAL archiving was never enabled.
  • Days 1–3Orders are rebuilt from payment records, confirmation emails, and the warehouse system. Some order notes are lost permanently.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make a small database and take an online backup of it.

    Potentially destructive

    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

    Options: .backup copies a live SQLite database consistently, like a base backup.

    Expect: prod.db and backup.db of similar size.

    Clean up: rm -rf ~/labs/restore.

  2. Make the mistake: delete rows, the way a bad migration would.

    Potentially destructive

    sqlite3 prod.db "DELETE FROM orders WHERE id > 4000; SELECT count(*) FROM orders;"

    Expect: 4000: a thousand orders gone from production.

  3. Restore drill: verify the backup, time it, and copy back only the lost rows.

    Reversible

    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;"

    Options: PRAGMA integrity_check validates the restored file; ATTACH reads the backup beside production instead of replacing it.

    Expect: ok and 5000 from the backup, the time taken, then 5000 in production: the lost rows copied back, nothing else changed.

2. Python: restore_drill.py

This 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

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your company has 40 data stores, nightly backups for most, and has never done a full restore. Design its backup, verification, and drill programme.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Backups never restoredHop 5: Automated restore testBreaksBackups 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 timedHop 6: Restore runbookBreaksThe 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.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Inventory → RPO and RTO → Backup methods → Immutable copy → Automated restore test → Restore runbook → Point in time → Validation → Drill record. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 230
Internal Developer Platforms

I spent years watching good developers lose whole days to work that had nothing to do with their feature. They needed a repo, a pipeline, a database, a dashboard.

Go to Lesson 230 →

Or browse the full course from the Lessons index.