A multi-threaded service logging requests to one SQLite file sets busy_timeout to 5000, yet transactions that read and then write still fail with SQLITE_BUSY instantly; why, and what fixes it?
answer
- the transaction already holds a read
- waiting here could deadlock
- WAL adds SQLITE_BUSY_SNAPSHOT
- take the write lock at BEGIN
- retry the whole transaction
basics
~20 sA deferred transaction that has already read cannot wait to become a writer: SQLite skips the busy handler and returns SQLITE_BUSY, or SQLITE_BUSY_SNAPSHOT in WAL mode once another connection has committed. Start such transactions with BEGIN IMMEDIATE.
solid answer
~50 sA plain `BEGIN` is deferred, so the `SELECT` opens a read transaction and the later write has to upgrade it. While another connection holds the write lock, SQLite runs the busy handler only for a connection that had no transaction open; one already holding a read gets the error back at once. In rollback-journal mode that avoids a deadlock: the other writer, holding `RESERVED`, is waiting for this connection's `SHARED` lock to clear before it can commit. In WAL mode, if another connection has already committed, the upgrade fails with `SQLITE_BUSY_SNAPSHOT` because the reader's snapshot is stale, and no wait can fix that. The fix is to start read-then-write transactions with `BEGIN IMMEDIATE`, so contention appears at `BEGIN` where the timeout does wait; on any busy error mid-transaction, `ROLLBACK` and rerun the whole transaction; and keep write transactions short.
code
sql · 13 linesCREATE TABLE IF NOT EXISTS request_log(id INTEGER PRIMARY KEY, path TEXT, status INTEGER);
-- Fragile: the SELECT opens a read transaction, so the INSERT is an upgrade
BEGIN;
SELECT count(*) FROM request_log WHERE status >= 500;
INSERT INTO request_log(path, status) VALUES ('/alerts', 200);
COMMIT;
-- Robust: the write lock is taken at BEGIN, where busy_timeout waits
BEGIN IMMEDIATE;
SELECT count(*) FROM request_log WHERE status >= 500;
INSERT INTO request_log(path, status) VALUES ('/alerts', 200);
COMMIT;go deeper
Remember that a transaction which reads first and writes later can fail at the write, and that BEGIN IMMEDIATE avoids it.
Explain why the busy handler is not used for a read-to-write upgrade, and what SQLITE_BUSY_SNAPSHOT means in WAL mode.
Diagnose it from the evidence: instant failures despite a timeout, the extended result code, leaked statements, and fix it with IMMEDIATE plus whole-transaction retries.
Make the remedy structural: a data layer that opens writing transactions with IMMEDIATE and retries them whole, so no feature team can reintroduce the upgrade.
## The symptom The request-log service has done the textbook things: WAL mode, and `PRAGMA busy_timeout = 5000` on every connection. Plain inserts now wait when they collide. One code path still fails instantly with `SQLITE_BUSY`: the one that opens a transaction with a plain `BEGIN`, runs a `SELECT` (say, counting recent 5xx responses to decide whether to write an alert row) and then runs an `INSERT` or `UPDATE`. The timeout is set, yet the failure takes no time at all. That combination points at a **read-to-write upgrade**. ## Why the busy handler is skipped A plain `BEGIN` is deferred: the `SELECT` starts a **read transaction**, and the later write must upgrade it to a write transaction. In SQLite's source, the loop that calls the busy handler while a write lock is held elsewhere runs only for a connection that had **no transaction open**; a connection already holding a read gets the error back at once. The reason differs by journal mode. **Rollback-journal mode.** The reader holds `SHARED` and now wants `RESERVED`. Suppose another connection holds `RESERVED` and is trying to reach `EXCLUSIVE` to commit: it is waiting for every `SHARED` lock to clear, including this one. If both waited, neither would move. SQLite therefore returns `SQLITE_BUSY` to the connection that wants `RESERVED`, so that it releases its read lock and lets the other commit. **WAL mode.** Readers never block the writer, so there is no deadlock, but there is a stale view: - if another connection holds the write lock, the upgrade fails with `SQLITE_BUSY` at once; - if another connection has already **committed** since this read transaction began, the upgrade fails with `SQLITE_BUSY_SNAPSHOT` (extended code 517). The reader's snapshot is no longer the latest version, and letting it write would fork the database's history. No amount of waiting fixes the second case: the snapshot stays stale until the transaction ends. | Situation | Result | Busy handler runs? | |---|---|---| | No transaction open, another connection writing | Waits; `SQLITE_BUSY` if the timeout expires | Yes | | `BEGIN IMMEDIATE`, another connection writing | Waits; `SQLITE_BUSY` if the timeout expires | Yes | | Read transaction open, another holds the write lock | `SQLITE_BUSY` at once | No | | WAL mode, read transaction open, another has committed since | `SQLITE_BUSY_SNAPSHOT` at once | No | ## The fix 1. **Take the write lock at `BEGIN`.** Start every transaction that will write with `BEGIN IMMEDIATE`. Contention then appears at `BEGIN`, where no transaction is open yet and the busy timeout does wait. 2. **Retry the whole transaction, not the statement.** If `SQLITE_BUSY` or `SQLITE_BUSY_SNAPSHOT` arrives mid-transaction, `ROLLBACK`, then run the transaction again from `BEGIN`, re-reading its data. Retrying only the failed statement keeps the old read lock or snapshot, which is exactly what blocks progress. 3. **Keep write transactions short.** Every other writer queues behind the one holding the write lock, and the timeout only helps if the holder finishes inside it. 4. **Finish your statements.** An implicit transaction lasts until the last active statement finishes, which is guaranteed only once the statement is reset or finalized. A `SELECT` left half-stepped keeps a read transaction open, so a later write on the same connection is an upgrade even without any `BEGIN`. ## Diagnosing it - **Read the extended code.** The C interfaces return primary codes by default, so `SQLITE_BUSY_SNAPSHOT` appears as plain `SQLITE_BUSY` unless the application calls `sqlite3_extended_errcode()` or turns extended result codes on. - **Look at the timing.** An instant failure on the first write after a read, with a timeout configured, is the upgrade; a failure after roughly the timeout is a write lock held too long by someone else. - **Hunt for leaked reads.** Unfinished statements and open cursors are the usual hidden source of a read transaction nobody meant to keep. `BEGIN IMMEDIATE` has a cost: the transaction holds the write lock during its reads too, so other writers wait longer. Readers on other connections are unaffected in WAL mode; in rollback-journal mode they are held off only when the writer takes `EXCLUSIVE` to write the file, at commit or on a cache spill.
- Why must the application retry the whole SQLite transaction rather than only the statement that failed?The failed statement's transaction still holds its read. In rollback-journal mode its `SHARED` lock is what the other writer waits on to commit, so retrying in place leaves the other writer stuck until its own timeout expires. In WAL mode the snapshot stays stale for the life of the transaction, so every retry gets `SQLITE_BUSY_SNAPSHOT` again. `ROLLBACK`, then rerun from `BEGIN`, re-reading the data.
- Can a SQLite connection in autocommit mode hit this upgrade failure without any explicit BEGIN?Yes. An implicit read transaction lasts until the last active statement finishes, which is only guaranteed after `sqlite3_reset()` or `sqlite3_finalize()`. If a `SELECT` on the connection has not been reset, its read transaction is still open, so an `INSERT` on the same connection must upgrade it and can fail at once despite the timeout.
- Raising busy_timeout to 30 seconds will make the instant SQLITE_BUSY go away.
- Retrying only the failed INSERT inside the same transaction is the right recovery.
- SQLITE_BUSY_SNAPSHOT means the WAL file is damaged.
- BEGIN IMMEDIATE blocks all readers until the transaction commits.
- A plain BEGIN takes the write lock, so the upgrade cannot happen inside it.