My SQLite job queue threw database is locked 287 times in one run. The connection had a 5-second busy timeout. The median failure took 0.3 milliseconds.
So I did the obvious thing and raised the timeout to 30 seconds. Next run: 279 errors. Still 0.3 ms.
That's when I stopped blaming contention and started reading how SQLite actually decides whether to wait. Turns out the SQLite database is locked error has a mode where busy_timeout is never consulted at all, and I had written my claim logic in exactly that shape.
TL;DR
-
busy_timeoutonly applies when a connection asks for a lock while holding no read snapshot. A deferred transaction that reads first and writes second skips the busy handler entirely when it tries to upgrade. - In WAL mode that upgrade fails instantly with
SQLITE_BUSY(another writer holds the lock) orSQLITE_BUSY_SNAPSHOT(someone committed after your read). Both surface in Python asdatabase is locked. - Raising the timeout from 5 s to 30 s changed nothing: 287 errors became 279.
-
BEGIN IMMEDIATE(or a singleUPDATE ... RETURNINGstatement) took the write lock up front, let the timeout do its job, and dropped errors to 0 of 2,000 jobs. - After any
OperationalErrorinside a transaction,ROLLBACK. A busy error does not end the transaction for you.
The setup: four workers, one SQLite file, 2,000 LLM jobs
This is a side project that summarizes documents with an LLM. I didn't want Redis or Postgres for a queue that processes a few thousand jobs a night, so the queue is a single SQLite table:
CREATE TABLE jobs (
id INTEGER PRIMARY KEY,
status TEXT NOT NULL DEFAULT 'pending',
worker TEXT,
payload TEXT,
result TEXT
);
Four Python worker processes, SQLite 3.45, journal_mode=WAL. Each worker loops: claim a job, call the model (about 1.2 s per call), write the result back.
I did the responsible thing and made the claim atomic, so two workers could never grab the same row:
conn = sqlite3.connect("queue.db", timeout=5.0, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL")
def claim(conn, worker_id):
conn.execute("BEGIN")
row = conn.execute(
"SELECT id, payload FROM jobs "
"WHERE status='pending' ORDER BY id LIMIT 1"
).fetchone()
if row is None:
conn.execute("COMMIT")
return None
conn.execute(
"UPDATE jobs SET status='running', worker=? WHERE id=?",
(worker_id, row[0]),
)
conn.execute("COMMIT")
return row
Read, then write, inside one transaction. Textbook. Also the bug.
Why does SQLite say database is locked when busy_timeout is set?
Because a plain BEGIN is a deferred transaction, and a deferred transaction that has already read cannot wait for the write lock. The SELECT gives the connection a read snapshot. The UPDATE then needs the single write lock. SQLite only runs the busy handler (which is what timeout= configures) for a connection that holds no snapshot yet. Once you're holding one, an upgrade that can't proceed returns immediately.
There's a good reason for that. Say worker A has read the queue and worker B currently holds the write lock. If A waited politely, B would commit, and A's snapshot would now describe a queue that no longer exists. A would be about to claim a job based on stale data. SQLite refuses to let you write on top of a stale read, so waiting would only end in failure. It skips the wait and fails now.
How I proved the timeout was never used
I wrapped the claim and logged two things per failure: the extended error name (Python 3.11+ exposes it as e.sqlite_errorname) and how long the failing call took.
t0 = time.perf_counter()
try:
job = claim(conn, worker_id)
except sqlite3.OperationalError as e:
if conn.in_transaction:
conn.execute("ROLLBACK")
elapsed_ms = (time.perf_counter() - t0) * 1000
log.warning("claim failed %s %.2fms", e.sqlite_errorname, elapsed_ms)
time.sleep(0.5)
Run 1, 2,000 jobs, 2,287 claim attempts:
-
201 ×
SQLITE_BUSY: another worker held the write lock at the moment of my upgrade -
86 ×
SQLITE_BUSY_SNAPSHOT: another worker had already committed after mySELECT - Median time to failure: 0.3 ms. p99: 2.1 ms. Not one failure came within a thousand times of the 5,000 ms timeout.
If the busy handler were running, the failures would cluster near 5 seconds. They clustered near zero. The timeout wasn't too short. It was never consulted.
Does raising the SQLite timeout fix database is locked?
Not for this failure mode. If your errors arrive instantly, the timeout is irrelevant and raising it is a placebo. I bumped it to 30 seconds to be sure:
| Run | Claim strategy | timeout | Errors | Median time to error |
|---|---|---|---|---|
| 1 |
BEGIN (deferred) |
5 s | 287 | 0.3 ms |
| 2 |
BEGIN (deferred) |
30 s | 279 | 0.3 ms |
| 3 | BEGIN IMMEDIATE |
5 s | 0 | n/a |
| 4 | single UPDATE ... RETURNING
|
5 s | 0 | n/a |
The 287 versus 279 difference is just run-to-run noise in how the four workers interleave. A quick diagnostic for your own logs: if your database is locked errors take milliseconds, you have an upgrade problem. If they take exactly your timeout, you have a contention problem. Different bugs, different fixes.
How do you fix SQLite database is locked with BEGIN IMMEDIATE?
Take the write lock at the start of the transaction, before you read anything. BEGIN IMMEDIATE asks for the write lock while the connection holds no snapshot, which is exactly the case where SQLite does run the busy handler. If someone else is writing, you wait (up to your timeout) and then read a fresh snapshot that nobody can invalidate until you commit.
The change is one word:
conn.execute("BEGIN IMMEDIATE")
If you use Python's default implicit transaction handling instead of isolation_level=None, you can get the same effect at connect time:
conn = sqlite3.connect("queue.db", timeout=5.0, isolation_level="IMMEDIATE")
Run 3 results over the same 2,000 jobs:
- 0 errors
- Claim wait: p50 0.2 ms, p99 41 ms, max 186 ms
- Total wall clock: 10m 02s, down from 10m 41s, almost all of it the 0.5 s retry sleeps I no longer paid
The even shorter fix: claim the job in one statement
SQLite 3.35 added RETURNING, which means the claim doesn't need a multi-statement transaction at all:
row = conn.execute(
"""
UPDATE jobs SET status='running', worker=?
WHERE id = (
SELECT id FROM jobs WHERE status='pending'
ORDER BY id LIMIT 1
)
RETURNING id, payload
""",
(worker_id,),
).fetchone()
A single autocommit write statement asks for the write lock from a clean state, so the busy handler applies. Run 4: 0 errors, and the claim function went from 14 lines to one query. This is what the queue uses now.
What traps are left after switching to BEGIN IMMEDIATE?
Two, and both are about holding the lock too long or forgetting to release it.
1. Never keep the transaction open across the LLM call. BEGIN IMMEDIATE serializes writers. My claim transaction lasts under a millisecond, so four workers barely notice. If I had claimed, called the model for 1.2 s, and then committed, all four workers would take turns, and throughput would drop to roughly one job per 1.2 s regardless of worker count. Claim, commit, do slow work, then open a new short transaction to write the result.
2. A busy error does not roll back your transaction. When the UPDATE fails with SQLITE_BUSY, the BEGIN is still in effect. If your retry loop catches the exception and jumps back to conn.execute("BEGIN"), you get cannot start a transaction within a transaction instead. Check conn.in_transaction and ROLLBACK in the except block, as in the logging snippet above.
What I'd tell myself before writing that queue
SQLite as a job queue for a few workers is completely fine. I'd still pick it over standing up Redis for this workload. But the "read the pending row, then update it" pattern that feels like the safe, atomic way to claim work is precisely the shape SQLite can't wait on. The fix costs one keyword, and the evidence was sitting in my logs the whole time: errors that should take five seconds were taking a third of a millisecond.
Time your lock errors before you touch the timeout. That one number tells you which bug you have.
So why does SQLite say database is locked despite busy_timeout?
SQLite returns database is locked despite busy_timeout when a deferred transaction (plain BEGIN) reads first and then tries to write. Once a connection holds a read snapshot, SQLite will not run the busy handler for the upgrade to a write lock, because waiting would leave it writing on stale data. In WAL mode the upgrade fails instantly with SQLITE_BUSY or SQLITE_BUSY_SNAPSHOT, so raising the timeout does nothing. Start write transactions with BEGIN IMMEDIATE, or collapse read-then-write into a single UPDATE ... RETURNING statement, and the timeout works as intended. In my four-worker queue that took errors from 287 to 0 across 2,000 jobs.
Written by the developer behind Preterview, an interview prep platform.
Top comments (0)