skip to content

An app backs up its SQLite database by copying the file while running; why can that copy be unusable, and what should it do instead?

level: middleimportance: must knowfreq 60%

answer

  1. a copy is not a transaction
  2. half old, half new pages
  3. recent commits sit in -wal
  4. let SQLite make the copy
  5. VACUUM INTO or the backup API

basics

~20 s

A file copy taken mid-transaction can mix old and new pages, and in WAL mode it misses commits still in the -wal file. Let SQLite make the copy: VACUUM INTO, the online backup API or sqlite3_rsync give a consistent snapshot of a live database.

solid answer

~50 s

A copy tool reads the file with no regard for SQLite's transactions, so a write that commits during the copy can leave it holding some old pages and some new ones: a corrupt database. In WAL mode, committed transactions not yet checkpointed live only in `app.db-wal`, so copying `app.db` alone silently loses them, and copying the `-wal` too still races the writer. Inside the app's own process, a plain `open()`, `read()` and `close()` on the file can even cancel the POSIX advisory locks its SQLite connections hold. The safe routes go through SQLite: `VACUUM INTO 'backup.db'` (3.27.0 or later) writes a consistent, compacted copy; the online backup API (`sqlite3_backup_init`, `sqlite3_backup_step`, `sqlite3_backup_finish`) copies pages incrementally into a snapshot; `sqlite3_rsync` (3.47.0 or later) copies a live database over SSH. A plain copy is safe only while no transaction is in progress, and in WAL mode only with the -wal copied too.

code

sql · 2 lines
sql
SELECT sqlite_version();
VACUUM INTO '/data/backups/app-2026-10-09.tmp';

go deeper

for a junior

Recall that a running SQLite database must not be backed up with a plain file copy, and name VACUUM INTO or the backup API as the safe alternatives.

for a middle

Explain the failure modes: a commit landing mid-copy, WAL commits that live only in the -wal file, and POSIX locks dropped by a close() in the same process.

for a senior

Show production practice: write backups to a temporary name and rename on success, check sqlite_version() on devices, handle backup API restarts and BUSY retries, and restore without leaving a stale -wal behind.

for a principal

Decide the backup contract for every app that embeds SQLite: which method, how often, where copies go, and how restores are rehearsed, since file-level tooling cannot be trusted here.

## Why copying a live file is not a backup A file-copy tool reads `app.db` from start to end with no idea that SQLite is using it. Three things can go wrong while the app is running: - **A transaction commits mid-copy.** The copy then holds some pages from before the commit and some from after it. SQLite's own list of ways to corrupt a database names exactly this: a background backup that copies the file in the middle of a transaction. - **WAL mode keeps recent commits outside the main file.** In WAL mode a committed transaction lives in `app.db-wal` until a checkpoint copies it home. Copy only `app.db` and those commits are silently missing. Copy the `-wal` as well and you are still racing a writer that can append to it, or a checkpoint that can rewrite the main file, during the copy. - **The copy runs inside the app's own process.** On Unix, SQLite coordinates access with POSIX advisory locks, and a `close()` on any file descriptor for the database cancels every such lock the process holds on it. A backup routine that does a plain `open()`, `read()` and `close()` can silently drop the locks the app's SQLite connections believe they still hold. A plain copy *is* safe when no transaction is in progress for the whole duration of the copy and every file that belongs to the database travels with it: in WAL mode that means the `-wal` too, unless every connection has been closed, in which case the last one checkpointed and removed it. If the last write transaction failed, copy any `-journal` or `-wal` file together with the database, because it holds what recovery needs. ## The safe ways: let SQLite make the copy | Method | What it produces | Notes | |---|---|---| | `VACUUM INTO 'file'` | A consistent, fully vacuumed copy | Plain SQL; 3.27.0 or later; the target must not exist or must be empty | | Online backup API | A bit-wise identical snapshot of the source | C API: `sqlite3_backup_init()`, `sqlite3_backup_step()`, `sqlite3_backup_finish()`; fewer CPU cycles; can run incrementally | | `sqlite3_rsync` | A copy of a live database to or from another host over SSH | Separate program, 3.47.0 or later; bandwidth-efficient | All three work on a live database. They go through SQLite rather than around it, so they see committed data wherever it lives, including the `-wal`, and they respect SQLite's locking instead of bypassing it. ## VACUUM INTO `VACUUM INTO` writes a new database file with the same logical content as the original, fully vacuumed, and leaves the original unchanged. The output is a consistent snapshot of the source. Points worth knowing: - the target file must not already exist, or must be empty, or the command fails with an error; - the result is as small as it can be and carries no traces of deleted content, which cuts I/O and matters when the backup leaves the device; - if a crash or power loss interrupts the command, the output may be incomplete and corrupt, so write to a temporary name and rename it only after the command has succeeded; - since 3.40.0 it honours the source's `PRAGMA synchronous`: with `NORMAL` or `FULL` it syncs the output to disk after writing it. ```sql VACUUM INTO '/data/backups/app-2026-10-09.tmp'; ``` ## The online backup API The backup API copies pages from a source connection to a destination connection, which may be a file or an in-memory database: 1. `sqlite3_backup_init()` names destination and source; it fails if the destination already has a transaction open; 2. `sqlite3_backup_step(B, N)` copies up to N pages, or all remaining pages if N is negative, returning `SQLITE_OK` while pages remain and `SQLITE_DONE` at the end; 3. `sqlite3_backup_finish()` releases the backup object, rolling back the destination if the copy did not finish. The source is read-locked only during each step call, so the app keeps reading and writing between steps. If another connection or process writes to the source in between, the next step **restarts** the backup; if the source is a file and the write goes through the same connection the backup reads from, the destination is updated along with it. Either way the finished copy is a consistent, up-to-date snapshot, but under constant writes from other connections a restarting backup may never finish. `SQLITE_BUSY` and `SQLITE_LOCKED` from a step can be retried; `SQLITE_READONLY`, `SQLITE_NOMEM` and I/O errors are fatal. ## Restoring, and checking the library version Restoring has its own trap. Overwriting a database file without also removing a hot journal or `-wal` that belonged to the old file pairs the new file with the wrong journal, which is a documented route to corruption. Close every connection before swapping files, or restore through the backup API into the open database, which replaces its contents under SQLite's locks. On a phone, the SQLite that the operating system provides can be older than the current release. `SELECT sqlite_version();` tells you whether `VACUUM INTO` (3.27.0) is available before you rely on it.

  • When would you prefer SQLite's online backup API over VACUUM INTO?
    The backup API uses fewer CPU cycles and can copy a few pages per step with pauses in between, holding the source's read lock only briefly; it produces a bit-wise copy, free pages included. VACUUM INTO rebuilds the content into a minimal file with no deleted traces, which saves I/O and storage. Under heavy writes from other connections the backup API keeps restarting, while VACUUM INTO takes one snapshot.
  • How do you restore a SQLite backup over a running app's database without corrupting it?
    Either close every connection before replacing the file and make sure no -journal or -wal from the old file is left beside the restored one, or open the backup and use the backup API to copy it into the app's open database, which replaces the contents under SQLite's own locks. Swapping the file under live connections, or leaving the old -wal behind, pairs data and journal wrongly.
  • Is a VACUUM INTO copy safe if power fails right after the statement returns?
    Since 3.40.0, VACUUM INTO honours the source's PRAGMA synchronous: with NORMAL or FULL it syncs the output to disk after writing it, so a power loss after it completes should not corrupt the copy. With synchronous OFF there is no such sync, and an interruption during the command can always leave the output incomplete.

  • Copying the .db file is fine as long as the app is usually idle.
  • In WAL mode the main .db file always holds every committed transaction.
  • VACUUM INTO overwrites the target file if it already exists.
  • The online backup API locks the source database for the whole copy.
  • Reading the database file with plain open, read and close inside the app is harmless.

Assumes SQLite 3.53; VACUUM INTO needs 3.27.0 or later and sqlite3_rsync 3.47.0 or later, and an OS-bundled SQLite can be older than the release you build against.