SQLite is fully ACID, and its durability story is better than many server databases because there is no replication layer to be asynchronous about. What it does not have is concurrent writers.
The rollback journal, the historical default, works by copying original pages to a -journal file before modifying the database. A crash leaves the journal, and the next connection rolls back from it. Writers take an EXCLUSIVE lock, which blocks readers for the duration of the write.
WAL mode inverts this. Changes are appended to a -wal file and the main database is untouched until a checkpoint copies them back. The consequence that matters: readers do not block the writer and the writer does not block readers. Readers see a consistent snapshot from before the writer started. For any application with concurrent reads this is transformative, and journal_mode = WAL is persistent - set once, stored in the file.
WAL's costs are real and worth stating. It uses three files rather than one, so copying "the database" means copying all of them or checkpointing first. It does not work on network file systems, because it needs shared memory that NFS and SMB cannot provide correctly - and the failure mode is corruption, not an error. And the -wal file grows until a checkpoint, which on a database under constant read load may be a long time.
There is still exactly one writer at a time. WAL does not change that; it removes the reader-writer conflict, not the writer-writer one. A second writer gets SQLITE_BUSY.
Handling SQLITE_BUSY properly is the single most important thing in this module. PRAGMA busy_timeout = 5000 makes SQLite wait and retry internally, which handles most cases. But it does not help with a deadlock arising from a transaction that began as a reader and later tries to write - the classic upgrade deadlock. Two connections both holding read locks, both wanting to write, cannot both proceed, and the busy handler cannot resolve it.
The fix is BEGIN IMMEDIATE. A deferred BEGIN takes no lock until the first statement decides what it needs; BEGIN IMMEDIATE takes the write lock at once. If a transaction will write, start it with BEGIN IMMEDIATE - this one habit removes almost all SQLITE_BUSY problems in practice.
Savepoints give nested transactions. Triggers fire on insert, update and delete, and can enforce rules a CHECK cannot express because they can see other tables.
Laboratory exercise 3 - a service under concurrency.
Build a small service over your Module 2 schema with at least two operations: record an expense, and report a monthly total. Run it with concurrent clients - at least 20 simultaneous, mixing reads and writes.
Demonstrate the failure first. Run in rollback-journal mode with a deferred BEGIN and no busy timeout, and capture the SQLITE_BUSY errors. Then fix it: enable WAL, set busy_timeout, and use BEGIN IMMEDIATE for writing transactions. Measure the throughput at each step.
Then produce the upgrade deadlock deliberately: two connections that each BEGIN, read, and then attempt to write. Show that busy_timeout alone does not save you and that BEGIN IMMEDIATE does.
Deliverable: the service, the load script, the error counts and throughput at each of the three configurations, your captured deadlock with an explanation of why the busy handler could not resolve it, and the -wal file size over the run.
-- ------------------------------------------------------------------
-- WAL. Persists in the file; set it once at creation.
-- ------------------------------------------------------------------
PRAGMA journal_mode = WAL; -- returns 'wal' on success
PRAGMA wal_autocheckpoint = 1000; -- checkpoint every ~1000 pages
PRAGMA busy_timeout = 5000;
-- WAL means three files. "Back up the database" now means all three,
-- or checkpoint first:
-- app.db the database
-- app.db-wal committed changes not yet checkpointed
-- app.db-shm shared memory index for the WAL
--
-- And WAL does NOT work on NFS or SMB. The shared memory file cannot
-- be made correct over a network file system, and the failure mode is
-- silent corruption rather than an error. If the file must live on a
-- share, you do not want SQLite.
-- ------------------------------------------------------------------
-- THE MOST IMPORTANT LINE IN THIS MODULE.
-- ------------------------------------------------------------------
-- Deferred (the default): no lock taken until the first statement.
BEGIN;
SELECT sum(amount_minor) FROM expense; -- takes a READ lock
-- another connection writes here, and now we want to write too...
UPDATE expense SET reimbursed = 1 WHERE id = 1;
-- SQLITE_BUSY. And the busy handler CANNOT fix this: both
-- connections hold read locks and both want to upgrade. Waiting
-- longer cannot resolve a deadlock. One must roll back entirely.
COMMIT;
-- Immediate: take the write lock up front.
BEGIN IMMEDIATE;
SELECT sum(amount_minor) FROM expense;
UPDATE expense SET reimbursed = 1 WHERE id = 1;
COMMIT;
-- Now a second writer simply waits at BEGIN IMMEDIATE, where the busy
-- handler CAN help. If a transaction will write, say so at the start.
-- ------------------------------------------------------------------
-- Savepoints: nested, named, individually revocable.
-- ------------------------------------------------------------------
BEGIN IMMEDIATE;
INSERT INTO expense (category_id, amount_minor, currency, spent_at)
VALUES (1, 1500, 'GBP', '2026-11-30');
SAVEPOINT risky;
UPDATE expense SET amount_minor = amount_minor * 2 WHERE id = 1;
-- on second thoughts:
ROLLBACK TO risky; -- undoes the update, keeps the insert
RELEASE risky;
COMMIT;
-- ------------------------------------------------------------------
-- Triggers: rules a CHECK cannot express, because they see other rows.
-- ------------------------------------------------------------------
CREATE TABLE budget (
category_id INTEGER PRIMARY KEY REFERENCES category(id),
month TEXT NOT NULL,
limit_minor INTEGER NOT NULL,
spent_minor INTEGER NOT NULL DEFAULT 0
) STRICT;
CREATE TRIGGER expense_within_budget
BEFORE INSERT ON expense
FOR EACH ROW
WHEN EXISTS (SELECT 1 FROM budget b WHERE b.category_id = NEW.category_id)
BEGIN
SELECT CASE WHEN (
SELECT b.spent_minor + NEW.amount_minor > b.limit_minor
FROM budget b
WHERE b.category_id = NEW.category_id
AND b.month = strftime('%Y-%m', NEW.spent_at)
) THEN RAISE(ABORT, 'expense exceeds the category budget') END;
END;
-- Keep the denormalised total correct, in the same transaction as the
-- insert. This is the only way a cached aggregate stays true.
CREATE TRIGGER expense_updates_budget
AFTER INSERT ON expense
FOR EACH ROW
BEGIN
UPDATE budget
SET spent_minor = spent_minor + NEW.amount_minor
WHERE category_id = NEW.category_id
AND month = strftime('%Y-%m', NEW.spent_at);
END;
-- ------------------------------------------------------------------
-- Watching the WAL, which you must do in production.
-- ------------------------------------------------------------------
PRAGMA wal_checkpoint(PASSIVE); -- checkpoint if nothing is reading
-- returns: busy | log_pages | checkpointed_pages
--
-- PASSIVE gives up if a reader is active. Safe, may do nothing.
-- FULL waits for readers, then checkpoints.
-- TRUNCATE checkpoints and resets the -wal file to zero. This is the
-- one to run before copying the database.
--
-- A long-running read transaction prevents checkpointing entirely, so
-- the -wal file grows without bound. If your -wal is enormous, look
-- for a connection that opened a transaction and never committed.
Discussion
No questions on this topic yet. Sign in to ask the first one.