Reliability, Backup and Recovery

Article · 7:00

Why copying the file is not a backup, the online backup API, integrity_check, VACUUM, and the synchronisation problem SQLite does not solve.

Copying a live database file is not a backup. If a write is in progress you copy a torn file; in WAL mode you may copy the database without its -wal, which loses every committed transaction not yet checkpointed. The result is not reliably detectable as broken, which is the worst property a backup can have.

There are three correct methods.

VACUUM INTO 'backup.db' (3.27+) writes a compact, consistent copy of a live database while readers and writers continue. It is one statement, it is transactional, and for most applications it is the right answer.

The online backup API copies pages incrementally with a handle in each database, restarting automatically if the source is written during the copy. It is what you use from inside an application to back up without pausing.

.dump produces SQL text. It is the most portable, survives a partially corrupt file better than anything else - it can frequently extract most of the data from a database the engine refuses to open - and is the slowest to restore.

PRAGMA integrity_check verifies the whole database: page structure, index consistency, and that every index entry has a corresponding row. quick_check skips the expensive index cross-check. Run integrity_check after any suspected incident and as a scheduled job - corruption that is detected is recoverable, and corruption that is not is eventually replicated into every backup you hold.

VACUUM rebuilds the database into a fresh file, reclaiming free pages and defragmenting. It needs free disk space of roughly twice the database size, takes an exclusive lock for the duration, and cannot run inside a transaction. PRAGMA auto_vacuum = INCREMENTAL plus periodic incremental_vacuum is the online alternative.

Causes of corruption are almost always external to SQLite. The documented list is instructive: a database on a network file system, a file copied while being written, two processes with different locking assumptions, a crashed device that lied about flushing, or an application that deleted the -journal or -wal file because it looked like a leftover. SQLite itself is extraordinarily well tested; the environment is where corruption comes from.

And SQLite does not synchronise. There is no replication. Two devices with two copies of a file that both accept writes is a distributed systems problem that you must solve above SQLite - with a server, a sync service, or a conflict-resolution design of your own. Module 6 returns to this for the mobile case.

Laboratory exercise 5 - break it and recover.

In a disposable directory, build a database with the loaded data from Module 4. Take backups by all three methods and record the time and resulting size of each.

Then corrupt it deliberately - truncate the file, or overwrite a page in the middle with random bytes using dd. Run integrity_check and record exactly what it reports. Attempt recovery with each of your three backups and with .recover, and record what each gets back.

Then simulate a crash: kill the process mid-transaction with SIGKILL, reopen, and show that the database is consistent and the incomplete transaction is absent.

Measure the RPO and RTO for each recovery path.

Deliverable: a recovery runbook, the integrity_check output from the corrupted file, a table of RPO and RTO per method, and evidence of verification - a row count and a checksum that prove the data is right, not merely that the file opens.

-- ------------------------------------------------------------------
-- BACKUP. Three correct methods, and the wrong one.
-- ------------------------------------------------------------------

-- WRONG, and it is what everybody does first:
--   cp app.db /backup/app.db
-- In WAL mode you have just copied the database WITHOUT its -wal, and
-- every committed transaction since the last checkpoint is gone. The
-- copy opens cleanly and is silently out of date.

-- 1. VACUUM INTO - one statement, consistent, compact, online. For
--    most applications this is the answer.
VACUUM INTO '/backup/app-2026-11-30.db';

-- 2. The online backup API, from inside an application. Copies pages
--    incrementally and RESTARTS if the source is written during the
--    copy, so a busy database still yields a consistent result.
--
--    sqlite3_backup_init(dest, "main", source, "main");
--    while (sqlite3_backup_step(b, 100) == SQLITE_OK) { /* yield */ }
--    sqlite3_backup_finish(b);
--
--    From the CLI, the same mechanism:
--      sqlite3 app.db ".backup '/backup/app.db'"

-- 3. .dump - SQL text. Most portable, slowest to restore, and the one
--    that survives a partially damaged file:
--      sqlite3 app.db .dump | gzip > app.sql.gz
--      zcat app.sql.gz | sqlite3 restored.db

-- Checkpoint before any file-level copy, so the -wal is empty:
PRAGMA wal_checkpoint(TRUNCATE);

-- ------------------------------------------------------------------
-- INTEGRITY. Run this on a schedule, not only after an incident.
-- ------------------------------------------------------------------
PRAGMA integrity_check;     -- 'ok', or a list of problems
-- Checks page structure, index consistency, and that every index
-- entry has a matching row. Expensive on a large file.

PRAGMA quick_check;         -- skips the index cross-check. Much faster.
PRAGMA foreign_key_check;   -- orphaned children. Separate, and worth
                            -- running after any migration.

-- Corruption that is detected is recoverable. Corruption that is not
-- detected is eventually copied into every backup you hold, and that
-- is how a company discovers it has no good copy of anything.

-- ------------------------------------------------------------------
-- RECOVERY from a damaged file.
-- ------------------------------------------------------------------
--   sqlite3 broken.db ".recover" | sqlite3 recovered.db
--
-- .recover walks the B-tree pages directly, ignoring the parts the
-- engine refuses to read. It frequently extracts most of the data
-- from a file that will not open at all. It is the last resort and it
-- is remarkably effective - and it does NOT recover what was never
-- written, so verify the result rather than trusting it:
SELECT count(*), sum(amount_minor), max(spent_at) FROM expense;
PRAGMA integrity_check;

-- ------------------------------------------------------------------
-- VACUUM: reclaim and defragment.
-- ------------------------------------------------------------------
PRAGMA page_count;  PRAGMA freelist_count;
--   freelist_count / page_count is your fragmentation. Over ~25% is
--   worth acting on.

VACUUM;
-- Rebuilds into a fresh file. Needs ~2x the database size in free
-- space, takes an EXCLUSIVE lock for the duration, and cannot run
-- inside a transaction. On a 10 GB file that is a real outage.

-- The online alternative, decided at creation time:
PRAGMA auto_vacuum = INCREMENTAL;    -- must be set before data exists
PRAGMA incremental_vacuum(1000);     -- reclaim 1000 pages, any time

-- ------------------------------------------------------------------
-- Crash recovery, which needs no action at all.
-- ------------------------------------------------------------------
-- Kill the process mid-transaction with SIGKILL and reopen. SQLite
-- replays or rolls back from the -wal or -journal automatically, and
-- the incomplete transaction is simply absent.
--
-- The durability setting that decides what survives:
--   synchronous = FULL    survives power loss. Slowest.
--   synchronous = NORMAL  survives process crash; with WAL a power
--                         loss may lose the last transactions. The
--                         right default for most applications.
--   synchronous = OFF     survives nothing. Bulk loads only.

-- ------------------------------------------------------------------
-- Where corruption actually comes from. All of these are external.
-- ------------------------------------------------------------------
--   * the file on NFS, SMB or a Dropbox/iCloud folder
--   * a file copied while being written
--   * two processes with different locking assumptions, e.g. one of
--     them a shell script
--   * a device or VM that lied about flushing to disk
--   * an application that deleted the -journal or -wal because it
--     looked like a leftover - this one is common and always fatal

Discussion

No questions on this topic yet. Sign in to ask the first one.