Measured on SQLite 3.49.1: a transaction that reads and then writes fails with SQLITE_BUSY in 0 ms despite busy_timeout. Use BEGIN IMMEDIATE and retry whole transactions.
A lock error that ignores the timeout
Dinky maintains a small stock service for Belgavi's Book Store: a SQLite file, a web process and a nightly import job. Both open the database with a busy timeout of a few seconds, because the documentation says that is how SQLite waits for locks. Every so often a request still fails with database is locked, and the log shows it failed in under a millisecond. The timeout never had a chance to help.
That is not a bug in SQLite. It is the documented behaviour of a transaction that starts by reading and then tries to write while another connection is writing. This guide shows the cases with measurements, explains why the busy handler is skipped, and gives the fix: decide at BEGIN whether a transaction will write.
All measurements below were taken on Windows 11 with CPython 3.13.5 and its bundled SQLite 3.49.1, using two connections to one file with a busy timeout of 2,000 ms, except where stated. The companion example replays each timeline against real SQLite and against a small deterministic model, and checks that they agree.
How SQLite starts transactions
SQLite has three kinds of BEGIN. The default, BEGIN DEFERRED, takes no lock. The first SELECT starts a read transaction, and the first write statement starts, or upgrades to, a write transaction. BEGIN IMMEDIATE starts a write transaction at once. BEGIN EXCLUSIVE is the same as IMMEDIATE in WAL mode and also blocks readers in the other journal modes.
The transaction documentation states the upgrade rule directly: if another connection "has already modified the database or is already in the process of modifying the database, then upgrading to a write transaction is not possible and the write statement will fail with SQLITE_BUSY".
The busy-handler documentation explains why waiting would not help. If SQLite determines that invoking the busy handler could deadlock, it returns SQLITE_BUSY without calling it. Its example is the situation behind these failures: one connection holds a read lock and wants to promote it, and another holds the reserved lock and wants to commit, which needs the first connection's read lock gone. Neither can proceed, so waiting is pointless.
Measured: the read-then-write race
Two connections each run BEGIN, then SELECT qty, then UPDATE stock SET qty = qty - 1. Connection B gets its update in first.
| Time | Connection | Statement | Result |
|---|---|---|---|
| 0 ms | A | BEGIN, SELECT | OK, qty 5 |
| 100 ms | B | BEGIN, SELECT | OK, qty 5 |
| 150 ms | B | UPDATE | OK |
| 300 ms | A | UPDATE | SQLITE_BUSY after 0 ms |
| 600 ms | A | COMMIT | OK (nothing to commit) |
| 700 ms | B | COMMIT | OK, final qty 4 |
The same timeline in WAL mode gives the same result: A's update fails at once with SQLITE_BUSY. WAL lets readers and the writer run side by side, but there is still only one writer, and a read transaction cannot wait to become one.
Connection A's decrement is simply gone unless the application notices the error and retries the whole transaction. Retrying only the UPDATE inside the same transaction fails the same way, because A still holds its read snapshot.
Measured: the stale snapshot
WAL mode adds a second immediate failure. Connection B opens a read transaction and reads. Connection A then runs an autocommit UPDATE, which commits at once. When B tries to update, it gets SQLITE_BUSY_SNAPSHOT, again after 0 ms. The result-code documentation describes this as a connection trying to promote a read transaction after another connection "has already written to the database and thus invalidated prior reads". Even if the write lock is free, B's snapshot is out of date, and writing on top of it would be a lost update. The only fix is to roll back and start again.
Measured: when the timeout does work
The busy timeout is used whenever a connection asks for a lock with no transaction of its own in the way:
BEGIN IMMEDIATEwhile another connection writes: in the measurement, B waited 500 ms and then proceeded, and both decrements landed, final qty 3;- an autocommit
UPDATEwhile another connection holds a write transaction: it waited 800 ms and succeeded when the writer committed at 900 ms, or failed withSQLITE_BUSYafter the full timeout when the writer held the lock longer (busy timeout 1,000 ms, writer commit at 2,500 ms); - a rollback-journal
COMMITthat needs an open reader to finish: B's commit waited 1,000 ms until A closed its read transaction.
| Preset | Journal | Busy errors | Waited | Final qty |
|---|---|---|---|---|
| both read, then both write | rollback | 1, without waiting | 0 ms | 4 |
| BEGIN IMMEDIATE on both | rollback | 0 | 500 ms | 3 |
| both read, then both write | WAL | 1, without waiting | 0 ms | 4 |
| another commit after this read | WAL | 1, without waiting | 0 ms | 4 |
| writer holds the lock past the timeout | rollback | 1, after waiting | 1,000 ms | 4 |
| writer finishes inside the timeout | rollback | 0 | 800 ms | 3 |
| COMMIT waits for an open reader | rollback | 0 | 1,000 ms | 4 |
The fix: declare writes at BEGIN
If a transaction may write, start it with BEGIN IMMEDIATE. It then takes the write lock up front, waits with the busy timeout if another writer is active, and can never be caught holding a read snapshot it cannot upgrade. Readers that only read can keep using BEGIN or autocommit.
import sqlite3, time
def decrement_stock(path, isbn, attempts=3):
db = sqlite3.connect(path, isolation_level=None, timeout=2.0) # timeout sets the busy handler
try:
for attempt in range(attempts):
try:
db.execute('BEGIN IMMEDIATE') # write lock now, or wait
(qty,) = db.execute('SELECT qty FROM stock WHERE isbn = ?', (isbn,)).fetchone()
if qty < 1:
db.execute('ROLLBACK')
return False
db.execute('UPDATE stock SET qty = qty - 1 WHERE isbn = ?', (isbn,))
db.execute('COMMIT')
return True
except sqlite3.OperationalError:
if db.in_transaction:
db.execute('ROLLBACK')
time.sleep(0.05 * (attempt + 1)) # whole transaction retried
raise RuntimeError('stock update failed after retries')
finally:
db.close()Two details in that function matter. isolation_level=None puts the Python module in autocommit mode so that the explicit BEGIN IMMEDIATE is the only transaction control. And the retry wraps the whole transaction, including the read, so a retry always reads fresh data.
What Python does by default
The sqlite3 module's default, legacy transaction control, issues an implicit BEGIN before INSERT, UPDATE, DELETE and REPLACE, but not before SELECT. The measurement confirms it: after a SELECT on a default connection, in_transaction was false, and after an UPDATE it was true. So a default connection's "read, then update" does not hit the upgrade failure. It has a different bug: the read and the write are in separate transactions, so another connection can change the row between them. The default timeout of 5.0 seconds is the busy timeout. Python 3.12 added an autocommit attribute that replaces the legacy behaviour; whichever mode you choose, make transaction boundaries explicit in code that writes.
Failure modes
Upgrading inside long read transactions. A report that reads for seconds and then writes a summary row will fail whenever any other write happened meanwhile. Split it, or start it with BEGIN IMMEDIATE if it must be atomic.
Retrying the statement, not the transaction. After SQLITE_BUSY or SQLITE_BUSY_SNAPSHOT on an upgrade, roll back and rerun from the first read.
Raising the timeout to fix it. A larger busy timeout changes nothing for the immediate failures above, and makes real contention slower to surface.
Long writers starving everyone. BEGIN IMMEDIATE serialises writers, so keep write transactions short and move slow work, such as network calls, outside them.
Verification
The companion example's tests run all seven timelines through the model and through real SQLite, compare every statement's outcome and the final quantity, and check the timeout boundary in the model. The interactive lab replays the same timelines and lets you change the journal mode, the timeout and every statement. Run the real comparison on the SQLite version you ship, because locking behaviour is part of SQLite's documented contract but your build and file system are part of the result.
Interactive experiment
SQLite transactions: deferred upgrades versus BEGIN IMMEDIATE. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.