download

How do you test a database backup before an outage hits?

DevOps~12 minReviewed 2 Dec 2026Free · No sign-in

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.

  1. Do actual data loss and recovery time meet RPO and RTO?
  2. Write Python 3.12 code using sqlite3.Connection.backup to snapshot a live SQLite database into a fresh staging file in a temp directory, then check PRAGMA integrity_check, row count, and SUM(cents).
Show hints (3)
  1. "CHECK RPO AND RTO"

    Subtract the last archived WAL time (14:20) from the crash time (14:23) for RPO. Add 14 + 8 + 4 minutes for total RTO.

  2. "AVOID RAW FILE COPY"

    Copying a live database file with cp risks torn pages or missing WAL entries. Use SQLite's online src.backup(dst) API instead.

  3. "CLOSE BEFORE CLEANUP"

    On Windows, wrap sqlite3.connect(...) in contextlib.closing(...) inside tempfile.TemporaryDirectory(), then run PRAGMA integrity_check and 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.

"SOLUTION · PYTHON"
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}")
"OUTPUT"
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.

MetricTargetThis incidentMargin
RPO (data loss)<= 15 min3 min (14:23 - 14:20)12 min spare
RTO (downtime)<= 30 min26 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:

  1. Consistent snapshot: Use engine-safe tools (sqlite3.Connection.backup for SQLite, pg_basebackup plus archived WAL for PostgreSQL) instead of raw file copies.
  2. Clean staging host: Restore onto a separate, empty host or temp directory so hidden production credentials or existing files cannot mask missing artifacts.
  3. Low-level integrity: Run PRAGMA integrity_check (checks pages, B-trees, indexes, and NOT NULL, UNIQUE, and CHECK constraints; foreign keys need PRAGMA foreign_key_check) or PostgreSQL checksums and replay logs.
  4. Data completeness: Compare row counts, latest timestamp, and aggregate totals (here 3 rows and 5200 cents) 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 cp while writers are active. Without the Online Backup API, you can capture torn pages or miss -wal data.
  • 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; call close() or use contextlib.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 orders without 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_time in PostgreSQL).
  • "Why check PRAGMA integrity_check on the restored backup instead of on the live production database?" PRAGMA integrity_check scans 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 →

Original OfferVibe question. SQLite Online Backup API · PRAGMA integrity_check · Python sqlite3.Connection.backup · PostgreSQL Continuous Archiving · Google SRE: Data Integrity.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.