Cobalt Field Notes

SQLite in WAL mode

· 2 min read

For a service that runs on one machine, SQLite is often all the database it needs. The default rollback journal works, but write-ahead logging (WAL) is usually the better fit for a server process that reads and writes at the same time.

What changes

In rollback mode a writer copies the original pages into a journal, changes the database file in place, and needs readers out of the way while it commits. In WAL mode the changes are appended to a separate -wal file instead. A reader sees the database as it was when its transaction began, so readers do not block the writer and the writer does not block readers. There is still only one writer at a time.

PRAGMA journal_mode=WAL;   -- persistent: stored in the database file
PRAGMA busy_timeout=5000;  -- per connection, in milliseconds

The journal mode is remembered by the database file, but busy_timeout has to be set on every connection. Without it, a second writer gets SQLITE_BUSY at once instead of waiting for the lock.

Checkpoints

The WAL file grows until a checkpoint copies its pages back into the main database. SQLite runs one automatically when the WAL reaches about a thousand pages (wal_autocheckpoint). A checkpoint cannot finish while a read transaction still needs the old pages, so a reader that never ends lets the WAL grow without bound. Short transactions avoid the problem.

When not to use WAL

Backups

Copying the database with cp while the service runs can produce a file that lacks recent commits or is not consistent. Use the online backup instead, for example sqlite3 app.db ".backup /var/backups/app.db", or VACUUM INTO '/var/backups/app.db', which also compacts the copy.