How do you test a database backup before an outage hits?
Question
Your database takes a full base backup at 02:00 UTC and ships WAL (write-ahead log) segments every 5 minutes. Your targets are RPO = 15 minutes (max data loss) and RTO = 30 minutes (max recovery time).
A primary disk fails at 14:23 UTC; the last archived WAL closed at 14:20 UTC. Restoring the base image takes 14 minutes, replaying WAL takes 8 minutes, and running checks takes 4 minutes.
- Do actual data loss and recovery time meet RPO and RTO?
- Write Python 3.12 code using
sqlite3.Connection.backupto snapshot a live SQLite database into a fresh staging file in a temp directory, then checkPRAGMA integrity_check, row count, andSUM(cents).
Show hints (3)
- "CHECK RPO AND RTO"
Subtract the last archived WAL time (
14:20) from the crash time (14:23) for RPO. Add14 + 8 + 4minutes for total RTO. - "AVOID RAW FILE COPY"
Copying a live database file with
cprisks torn pages or missing WAL entries. Use SQLite's onlinesrc.backup(dst)API instead. - "CLOSE BEFORE CLEANUP"
On Windows, wrap
sqlite3.connect(...)incontextlib.closing(...)insidetempfile.TemporaryDirectory(), then runPRAGMA integrity_checkand row-sum queries on the restored file.
Show checked explanation
Yes. Actual data loss is 3 minutes (14:23 - 14:20, inside the 15-minute RPO), and total recovery takes 26 minutes (14 + 8 + 4, inside the 30-minute RTO). Because an untested backup is not a backup, run automated restore drills onto a clean staging target using the online backup API, PRAGMA integrity_check, and application row-sum checks.
from contextlib import closing from pathlib import Path import sqlite3 import tempfile with tempfile.TemporaryDirectory() as d: live, staged = Path(d, "live.db"), Path(d, "staged.db") with closing(sqlite3.connect(live)) as src: src.execute("CREATE TABLE orders (id INT PRIMARY KEY, cents INT)") src.executemany("INSERT INTO orders VALUES (?, ?)", [(1, 1500), (2, 2750), (3, 950)]) src.commit() with closing(sqlite3.connect(staged)) as dst: src.backup(dst) with closing(sqlite3.connect(staged)) as chk: ok = chk.execute("PRAGMA integrity_check").fetchone()[0] cnt, total = chk.execute( "SELECT COUNT(*), SUM(cents) FROM orders" ).fetchone() print(f"integrity={ok} rows={cnt} total_cents={total}")
integrity=ok rows=3 total_cents=5200
SQLite 3.49.1 online backup, PRAGMA integrity_check, WAL-mode snapshot, byte-corruption failure test, and RPO/RTO math run on CPython 3.12.10 (Windows x64). Checked by an editor other than the author.
Walkthrough
Start with the recovery math, then prove the files actually restore.
| Metric | Target | This incident | Margin |
|---|---|---|---|
| RPO (data loss) | <= 15 min | 3 min (14:23 - 14:20) | 12 min spare |
| RTO (downtime) | <= 30 min | 26 min (14 + 8 + 4) | 4 min spare |
That 4-minute RTO margin is tight. As the database grows, base restore plus 12+ hours of WAL replay can quietly cross 30 minutes unless you time restores regularly. Worse, if WAL shipping had stalled silently at 13:55 UTC, data loss would hit 28 minutes, breaching the 15-minute RPO without anyone noticing until the crash.
Why an untested backup is not a backup. Backup jobs fail in silent ways: wrong encryption key, missing WAL segments between base image and crash time, IAM permission drift, or a truncated upload that still exits 0. Copying a live database file with plain cp can also grab half-written pages or skip uncheckpointed -wal changes.
What a real staging restore drill checks every week:
- Consistent snapshot: Use engine-safe tools (
sqlite3.Connection.backupfor SQLite,pg_basebackupplus archived WAL for PostgreSQL) instead of raw file copies. - Clean staging host: Restore onto a separate, empty host or temp directory so hidden production credentials or existing files cannot mask missing artifacts.
- Low-level integrity: Run
PRAGMA integrity_check(checks pages, B-trees, indexes, andNOT NULL,UNIQUE, andCHECKconstraints; foreign keys needPRAGMA foreign_key_check) or PostgreSQL checksums and replay logs. - Data completeness: Compare row counts, latest timestamp, and aggregate totals (here
3rows and5200cents) against expected bounds, and record wall-clock restore duration against your 30-minute RTO.
Wrapping each SQLite connection in contextlib.closing ensures file handles close cleanly before the temporary directory exits.
Common mistakes
- Checking only that the nightly backup job exited 0 and created a non-empty file. Broken encryption keys or missing WAL segments only surface during a real restore.
- Backing up a live SQLite database with plain
cpwhile writers are active. Without the Online Backup API, you can capture torn pages or miss-waldata. - Testing restores on the production host or without timing them. Overwriting prod risks an outage, and an untimed restore hides slow RTO creep.
- Assuming
with sqlite3.connect(...)closes the connection in Python. It only commits or rolls back transactions; callclose()or usecontextlib.closing.
Follow-up questions
- "Your 02:00 base backup and WAL replay now take 34 minutes, breaching the 30-minute RTO. How do you cut recovery time?" Take base backups more often (every 6 hours instead of 24) to shorten WAL replay. You can also restore from parallel storage snapshots or promote a warm standby replica that already applies WAL continuously.
- "What if someone ran
DELETE FROM orderswithout a WHERE clause at 14:18 UTC?" A streaming replica immediately replays that delete too. Point-in-time recovery (PITR) restores the 02:00 base backup onto staging and stops WAL replay right before 14:18 UTC (recovery_target_timein PostgreSQL). - "Why check
PRAGMA integrity_checkon the restored backup instead of on the live production database?"PRAGMA integrity_checkscans every table and index page, adding heavy I/O load. Running it on the restored staging copy proves the backup is readable and valid without slowing live traffic.
What a strong answer covers
Computes the 3-minute RPO and 26-minute RTO, noting the tight 4-minute margin. Uses sqlite3.Connection.backup instead of raw file copy, runs PRAGMA integrity_check plus row-sum checks on staging, and covers PITR for logical deletes.
Open in interactive practice deck →