DEV Community

devbox-zero-ops
devbox-zero-ops

Posted on

Why cp app.db backup.db Silently Corrupts SQLite WAL Databases (And How to Build Encrypted Auto-Verified Backups in Python)

If you run SQLite in WAL mode (PRAGMA journal_mode=WAL) on a production VPS or Docker container and your cron job backs it up with cp app.db /backups/ or tar -czf, you are one concurrent write away from a silently corrupted backup.

Even worse: most teams never test whether their backups actually decrypt and restore until an outage hits.

Here are the three Python patterns that turn a fragile cron script into a real, encrypted, self-verifying backup system.


1. Use SQLite's Native Online .backup() API (Zero Lock Corruption)

Python's built-in sqlite3 module exposes Connection.backup(), which copies pages safely while live WAL writes continue:

import sqlite3
from pathlib import Path

def safe_sqlite_backup(src_db: Path, dst_db: Path) -> None:
    dst_db.parent.mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(f"file:{src_db}?mode=ro", uri=True) as src:
        with sqlite3.connect(dst_db) as dst:
            src.backup(dst, pages=256, sleep=0.05)
Enter fullscreen mode Exit fullscreen mode

2. Authenticated Encryption with Tamper Detection (Fernet + PBKDF2-HMAC-SHA256)

Never ship plaintext database dumps to object storage or external disks. Derive a strong key from your passphrase/env var and wrap the archive in authenticated encryption so any bit-flip or tampering fails immediately on restore:

import base64, hashlib, os
from cryptography.fernet import Fernet

def derive_fernet_key(passphrase: str, salt: bytes) -> bytes:
    dk = hashlib.pbkdf2_hmac("sha256", passphrase.encode(), salt, 390_000, dklen=32)
    return base64.urlsafe_b64encode(dk)
Enter fullscreen mode Exit fullscreen mode

3. Automated Restore-Drill Verification (PRAGMA integrity_check)

An untested backup is just a rumor. After every backup run, decrypt the latest archive into a temporary directory, verify every SHA-256 checksum in manifest.json, and run PRAGMA integrity_check on every restored .db file before sending your Telegram/Discord summary alert.


Want the Complete 19-File Production Kit (or the 3-in-1 Self-Hosted Ops Bundle)?

If you want all of this ready to deploy with GFS retention rotation (daily/weekly/monthly), SQLite WAL backup ledger, Telegram/Discord/HMAC webhooks, Dockerfile, systemd timer, and a verified 7/7 pytest suite (MIT commercial license):

Have you ever been burned by an untested backup or a corrupted SQLite copy? Share your war story below!

Top comments (0)