Practical technical guides / Core IT: databases

Back Up Live SQLite Data Without Losing Committed WAL Changes

Copying a WAL-mode SQLite file can lose committed rows while passing integrity_check. Measured comparison of file copy, the backup API and VACUUM INTO.

By Sandeep Belgavi · Published 2026-11-21

Copying a WAL-mode SQLite file can lose committed rows while passing integrity_check. Measured comparison of file copy, the backup API and VACUUM INTO.

The copy that passes every check

SQLite is often the database of a single service, an edge device, a desktop application or an agent's local memory. Backups of such databases are frequently a file copy, scheduled next to the application's other files. In rollback-journal mode, copying a database that nobody is writing is reasonably safe. In write-ahead logging mode, which many applications enable for better concurrency, a copy of the main database file can be missing committed transactions, and still open cleanly and pass PRAGMA integrity_check.

This guide measures that failure and three ways to avoid it, with Python's bundled sqlite3 module and SQLite 3.49.1, on synthetic book orders from the fictional Belgavi's Book Store.

How WAL mode stores a commit

The SQLite documentation on write-ahead logging describes the inversion clearly. In rollback mode, changes are written into the database file and the original content is saved in a journal. In WAL mode the original content stays in the database file and changes are appended to a separate WAL file, the one ending in -wal. A commit happens when a commit record is appended to the WAL. The database file itself can remain unchanged.

Moving the WAL's transactions back into the database file is called a checkpoint. By default SQLite runs one automatically when the WAL reaches a threshold of pages, and applications can run one with PRAGMA wal_checkpoint. Until a checkpoint has copied a transaction, the only durable record of that transaction is in the WAL file. Readers see it, because SQLite consults the WAL. A program that copies just the database file does not.

The measurement

The companion example builds the state deliberately so the result is deterministic. It opens a database in WAL mode and turns automatic checkpoints off with PRAGMA wal_autocheckpoint=0. It inserts 100 orders, commits, and runs PRAGMA wal_checkpoint(TRUNCATE) so those 100 rows are in the main file. It then inserts and commits 50 more orders. Those 50 are committed and visible to every connection, but they exist only in the 4,152-byte WAL file.

It then takes four copies and opens each one, runs integrity_check, counts rows and computes a fingerprint over the sorted rows:

  • Copying only orders.db: integrity ok, 100 rows, a different fingerprint. Fifty committed orders are gone.
  • Connection.backup() into a new database: integrity ok, 150 rows, the same fingerprint as the source.
  • VACUUM INTO a new file: integrity ok, 150 rows, the same fingerprint.
  • A paged backup with pages=1 while a second connection commits three more orders from inside the progress callback: integrity ok, 153 rows, matching the source after the writes, with 5 progress callbacks.

The first line is the reason this guide exists. An integrity check validates the structure of the file it is given. The copied file is a perfectly consistent database, just an older one.

target = sqlite3.connect('backup_api.db')
source.backup(target)          # pages=-1 copies everything in one step
target.close()

source.execute('VACUUM INTO ?', ('vacuum_into.db',))

check = sqlite3.connect('backup_api.db')
assert check.execute('PRAGMA integrity_check').fetchone()[0] == 'ok'

In a real deployment the WAL will usually be smaller than in this setup, because automatic checkpoints run. That changes how much you lose, not whether you can lose it. Any write since the last checkpoint is at risk, and a busy reader can delay checkpoints indefinitely.

Why the backup API restarts

The SQLite page on the online backup API explains the behaviour seen in the fourth copy. A backup copies pages in steps. If another connection writes to the source between steps, SQLite detects it and usually restarts the backup on the next step. If the write comes from the same connection that is running the backup, and the source is a file database, the destination is updated along with the source and the backup continues. Either way, when the backup completes, the destination is a consistent snapshot. The documentation also warns that if writes from other connections are frequent enough, the backup may restart so often that it never finishes.

Python exposes this as Connection.backup(target, *, pages=-1, progress=None, name='main', sleep=0.250). With the default pages=-1, the whole database is copied in a single step, so there is no pause between steps in which another connection's write can force a restart. With a positive page count, the backup yields between steps, so writers can proceed, and the sleep argument sets the pause between steps. For a small database, a single step is simplest. For a large database under write load, a paged backup with a sleep lets the application keep writing, at the cost of possible restarts. Measure it on your own data and write rate before choosing.

VACUUM INTO versus the backup API

The SQLite VACUUM documentation describes VACUUM INTO as an alternative to the backup API for copying a live database. Its result is minimal in size, and deleted content is purged, so the copy carries no forensic traces of removed rows. The backup API uses fewer CPU cycles and can run incrementally. The target file of VACUUM INTO must not exist, or must be empty.

The documentation also notes that VACUUM INTO is transactional in the sense that its output is a consistent snapshot, but an unplanned shutdown during the command can leave the output incomplete. That points to a general rule for both methods: write the backup to a temporary name, verify it, and only then rename it to its final name.

A backup procedure that verifies itself

  1. Take the copy through SQLite: the backup API or VACUUM INTO. Never copy the database file alone while any connection may hold uncheckpointed writes.
  2. Write to a temporary file in the destination directory, then open the result with a fresh connection.
  3. Run PRAGMA integrity_check, or quick_check for very large files, and require ok.
  4. Compare a logical fingerprint: row counts per table, plus a checksum over a stable ordering of key columns for the tables that matter. A matching structure with mismatched contents is exactly the failure above.
  5. Rename into place, and record the time and the newest row's key next to the backup, so a later restore can say how current it is.
  6. Restore into a scratch location on a schedule and run the same checks. A backup you have never restored is a hope.

If you cannot change the backup tool, for example because a host-level snapshot copies files, the safe alternatives are narrower. A file-level copy is safe when no connection is open and the WAL has been checkpointed and truncated, or when a storage snapshot captures the database file and its WAL file atomically, at one instant. Copying the database file and the WAL file one after another at different moments is not the same thing.

Failure modes to test

  • The main-file copy, with automatic checkpoints disabled, as the example does. Assert that your backup job's output has the source's row count.
  • A backup while writes continue. Assert that the result equals the source at some point in time, and that the job completes within a deadline even under your heaviest write rate.
  • A full destination disk during the backup. Assert that the temporary file is removed and the previous backup is untouched.
  • An interrupted VACUUM INTO. Assert that the incomplete file is never renamed into place.
  • A restore drill that opens the backup with the application's own schema migrations, not just with the SQLite shell.

When the simple copy is fine

For a database that is closed while the copy runs, such as a nightly export from a tool that is not running, a file copy after a final checkpoint is correct and fast. For an application that keeps its database in rollback-journal mode and copies only while holding its own write lock, the main file is complete. The danger is specifically WAL mode with open connections, which is the configuration most applications reach for once they have more than one reader.

Verification checklist

  • The backup job uses the backup API or VACUUM INTO, writes to a temporary name and renames after verification.
  • Verification checks a logical fingerprint, not only integrity_check.
  • A test reproduces the example's 100-versus-150 rows result against your job's code path.
  • A restore drill runs on a schedule, and its result is reported where someone reads it.

Run the example yourself

The WAL setup with automatic checkpoints off, the four copies and the fingerprint checks, with four tests. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 21 November 2026. Original explanation, measurements and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.

Related on this site: