Your app runs on SQLite in production, and backups are a cron job doing cp app.db backups/. It works, until a restore produces:
Error: database disk image is malformed
Copying a live SQLite file is not a safe backup. Here's why, and what to do instead.
Why cp isn't safe
While the app is running, SQLite may be writing pages to the database file, and in WAL mode recent commits live in a separate app.db-wal file until a checkpoint copies them into the main file.
cpcan read the file halfway through a write, so the copy has pages from different moments: corruption.- Copying only
app.dbin WAL mode leaves out committed transactions that are still in-wal, and copying the files one after another doesn't give a consistent pair either.
A plain file copy is only safe when no process has the database open, or when you take a filesystem-level snapshot that's atomic across the database and its -wal file (LVM, ZFS, or cloud volume snapshots).
Option 1: the online backup API (.backup)
SQLite's backup API copies the database page by page while it's in use, and produces a consistent copy:
sqlite3 /var/app/app.db ".backup '/backups/app-$(date +%F-%H%M).db'"
It's available in most languages (sqlite3.Connection.backup() in Python, db.backup() in better-sqlite3). On a busy database, the backup restarts when another connection writes during the copy; in WAL mode, readers and the backup don't block writers.
Option 2: VACUUM INTO (SQLite 3.27+)
VACUUM INTO '/backups/app-2026-09-26.db';
It writes a consistent, compacted copy (no free pages) in one statement, and works from any connection. It's usually the simplest choice for periodic snapshots. It reads the whole database, so schedule it off-peak for large files.
