Every time someone asks how to fix sqlite3.OperationalError: database is locked, the top two answers are always: "set busy_timeout" and "turn on WAL mode."
Both help — until your transaction reads before it writes. In that case, SQLite ignores your 5-second busy_timeout completely and fails in 0.4 milliseconds.
TL;DR
"database is locked"has two different causes, andbusy_timeoutonly fixes one of them.- On 8 concurrent writer threads with a 5,000 ms timeout, a plain
BEGIN(read, then update) threw 493 errors in rollback mode and 607 errors in WAL mode — failing in 0.4–0.8 ms, not 5 seconds.- Switching only to
BEGIN IMMEDIATEdropped both to 7 errors (~99% reduction) with zero lost updates.busy_timeoutis not a FIFO queue: even with a 5 s timeout, starved threads can still fail after ~7 s under heavy contention.
Test Setup
Everything below ran on Windows 11, Python 3.10.0, and SQLite 3.35.5 (25 October 2026): 8 threads hitting one SQLite file, one connection per thread, in 10-second runs.
First, I verified Python's defaults:
-
PRAGMA busy_timeoutdefaults to5000ms. - A second connection trying to acquire a held write lock waited 5.54 s before raising
database is locked(PRAGMA busy_timeout = 1500waited 1.73 s — roughly a ~10% overshoot, so treat it as a lower bound). - With
timeout=0, it failed in 0.2 ms.
Experiment 1: Pure Inserts (4 Configurations)
Each of the 8 threads ran a tight loop for 10 seconds: BEGIN IMMEDIATE, insert one row, COMMIT. I ran every configuration 3 times; the table shows the min–max range across runs:
| Configuration | Rows written |
database is locked errors |
|---|---|---|
Rollback journal, timeout=0
|
1,218 – 1,322 | 3,129 – 6,020 |
Rollback journal, timeout=5000 ms
|
1,280 – 1,415 | 5 – 7 |
WAL mode, timeout=0
|
2,610 – 3,201 | 253,030 – 265,602 |
WAL mode, timeout=5000 ms
|
1,452 – 4,147 | 7 (every run) |
Three surprises in those numbers:
-
busy_timeouthides errors; it does not make writers concurrent. Rollback journal wrote virtually the same number of rows (1,280–1,415vs1,218–1,322), because writers still serialize one at a time. -
WAL with
timeout=0is a quarter-million-error busy loop. Threads fail instantaneously and retry immediately. -
A wait is not a fair queue. Logging the 7 surviving errors showed that 7 threads started at
0.00 sand all gave up at7.09–7.19 s(in WAL, 4 failed at5.51 sand 2 more started at3.7 sand failed at5.6–5.7 s). One thread kept winning the lock repeatedly while others starved.
Experiment 2: Read, Then Write (Where busy_timeout Stops Working)
Now look at the most common real-world transaction: start a transaction, SELECT a counter, UPDATE it to counter + 1, and COMMIT — all with a 5,000 ms busy_timeout enabled:
| Configuration (5,000 ms timeout) | Committed | Errors | Median time to fail |
|---|---|---|---|
Rollback journal, plain BEGIN
|
1,574 | 493 | 0.8 ms |
Rollback journal, BEGIN IMMEDIATE
|
1,630 | 7 | 7,450 ms |
WAL mode, plain BEGIN
|
1,583 | 607 | 0.4 ms |
WAL mode, BEGIN IMMEDIATE
|
1,649 | 7 | 7,351 ms |
Why did it fail in 0.4 ms when busy_timeout was 5,000 ms?
Because of a lock upgrade deadlock:
- A plain
BEGIN(which isBEGIN DEFERRED) does not take a write lock yet. - The first
SELECTtakes a shared read lock. - Now two threads both hold read locks, and both run
UPDATE— asking SQLite to upgrade their read lock to a write lock. - Neither thread can proceed until the other releases its read lock. Waiting 5 seconds (or 5 hours) can never resolve that deadlock.
- SQLite knows this, so it skips
busy_timeoutcompletely and fails one of the writers immediately (SQLITE_BUSYin 0.4–0.8 ms).
With BEGIN IMMEDIATE, the connection asks for the write lock up front, before the SELECT. If another writer holds it, SQLite simply sleeps inside busy_timeout until the lock is free.
(Data integrity check: in all four runs, the final counter value equaled the exact number of commits — 1,574, 1,630, 1,583, and 1,649. Zero lost updates.)
The Fix in Python sqlite3
By default, Python's sqlite3 module implicitly opens a deferred BEGIN before DML statements — and if you start with a SELECT, you get a deferred read transaction that will fail on upgrade.
Set isolation_level=None (autocommit mode) and start write transactions explicitly with BEGIN IMMEDIATE:
import sqlite3
conn = sqlite3.connect("app.db", timeout=5.0, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=5000")
def increment_counter(conn: sqlite3.Connection) -> None:
conn.execute("BEGIN IMMEDIATE") # acquire write lock BEFORE reading
try:
n = conn.execute("SELECT n FROM counter WHERE id = 1").fetchone()[0]
conn.execute("UPDATE counter SET n = ? WHERE id = 1", (n + 1,))
conn.execute("COMMIT")
except Exception:
conn.execute("ROLLBACK")
raise
Priority order from the measurements
-
Use
BEGIN IMMEDIATEfor any transaction that will write (especially read-modify-write). That alone eliminated ~99% of errors here. -
Keep
busy_timeoutenabled (5,000 ms is a solid starting point), knowing it is a lower bound and not a fair FIFO queue. - Enable WAL primarily so readers do not block writers (and vice versa) — not as a guaranteed write-throughput boost.
- Keep write transactions tiny: grab the lock, write, commit. Never call an external API inside a write transaction.
What This Test Does Not Cover
Eight threads inside one Python process on one Windows machine (SQLite 3.35.5) running a tight busy loop. Multi-process workloads, network filesystems, slow disks, newer SQLite versions, and ORM transaction wrappers (Django, SQLAlchemy — check whether your ORM emits BEGIN or BEGIN IMMEDIATE!) will behave differently. Also, WAL's headline benefit (concurrent readers alongside a writer) was not exercised in these write-only runs.
Full benchmark write-up, chart, and FAQ: aiandsoftwarehub.com.
If you run SQLite in production (Django, FastAPI, Rails, Go): Did you configure BEGIN IMMEDIATE at the driver/ORM level, or funnel all writes through a single writer queue?
Top comments (0)