SQLite: Why "Database Is Locked" Ignores Your Timeout

Outline

Transcript

0:00 Imagine a checkout service on SQLite. Its connection timeout is 5 seconds, yet a stock update fails with "database is locked" in about 30 microseconds. Nothing waited. My first thought would be to raise that timeout to 30 seconds and close the ticket. Isn't that the usual production fix? Yeah, it's the common fix, and here it changes nothing. People assume a locked database means "wait longer." In this failure, the wait never started. Never started? Then what exactly is SQLite refusing? A write from a transaction that already read data it can't trust anymore.

0:36 That comes straight from SQLite's documentation, its version 3.51 source code, and a reproduction we ran five times on a one-row table. Source links are in the description. Okay, let's hear it. Walk me through that run. So, the setup. One stock table, one widget, quantity 10, and two connections we'll call A and B. Both with that 5-second timeout, and the database in write-ahead log mode. And A plays our checkout, so it begins a transaction and reads the quantity? Yep. A plain BEGIN, which SQLite treats as deferred: it locks nothing until the read, which makes it a reader, and it only asks for write access at its first write.

1:17 The read says 10. Meanwhile B sells one widget and commits, so the table says 9. Which leaves A holding a stale 10. To store 9, A has to upgrade from reader to writer, and that's where it fails? Right at the upgrade. "Database is locked," well under a millisecond in all five runs, and Python's error also carries a more specific name: busy snapshot. Microseconds, not a 5-second wait. Then the timeout itself needs a closer look. What does it do inside SQLite? It installs a busy handler, a little loop that sleeps and retries until the total sleep reaches your limit.

1:56 It doesn't watch the other connection. It just naps and tries again, and SQLite decides when that loop is even allowed to run. So when does SQLite let it run? I didn't realize this until I read the B-tree code. When a connection asks for a transaction, the retry only runs at the front door, while it holds no transaction at all. And A did its SELECT first, so it's already holding a read transaction. Right, so the busy result comes straight back. 30 seconds, 5 seconds, 5 minutes: that handler never runs.

2:29 The timeout isn't too short. It was never consulted. Yeah, and I've definitely shipped that timeout bump as an incident fix. Let me guess. The ticket came back. It did. So why refuse at all, instead of just waiting? Because waiting can't fix what A is holding. With the write-ahead log, every reader works from a snapshot. Right. When a read starts, SQLite notes where the log ends, and the docs call that point the end mark. That reader keeps seeing the database as of that mark. So, for example, A's widget stays at 10 for the rest of its transaction, while the real table already says 9.

3:06 Yeah. And when A finally tried to write, nobody was holding the lock anymore. B had already committed, so A actually got the single write lock. Hold on. It got the lock and still failed? Right after taking it, A checks whether anyone committed since its read began. It compares the log header it saved at that moment, basically a version stamp, with the live one every connection sees. They differ, so it lets go and returns busy snapshot. Now suppose it had written 9 anyway: that would have erased B's sale, and SQLite's isolation docs say it would fork the history of the database.

3:44 Oh, so "locked" is a little misleading here. It really means "you're reading an old version," and no amount of sleeping makes an old snapshot current. Exactly. And I like that the check comes after taking the lock, rather than before, so nobody can sneak a commit in between. Before we fix it, one quick variation. Turn off write-ahead logging, which puts us back on SQLite's default, the rollback journal. No snapshots there, so A should get through, right? You'd think so, but it's the same error, for a different reason. That mode uses locks instead of snapshots.

4:19 In that run B has written its 9 but hasn't committed, and it can't while A's SELECT still holds a read lock. Meanwhile B is sitting on the one writer's lock. Right, and A now wants B's lock. So A waits for B, while B waits for A. Yep, a deadlock. SQLite's busy-handler documentation describes this very case: SQLite hands busy to the reader at once instead of letting both sleep. In our runs, about 15 microseconds. So two modes, two reasons, one rule. Once a transaction has read, it can't wait its way into writing.

4:53 So the fix changes when A asks to write, not how long it waits. BEGIN IMMEDIATE takes the write lock before the first read. Yeah, and at that moment A has no transaction open yet, which is exactly when the busy handler gets to run. The waiting moves to the front door. So the timeout finally gets a job. Right. Every time, A took the lock up front, read 10, held it on purpose for about three tenths of a second, then wrote 9. B's own BEGIN IMMEDIATE waited about four tenths of a second before selling its widget. Final quantity: 8.

5:29 Nice. Both sales counted. But why four tenths, if A only held it for three? Those naps grow to a tenth of a second each, so B can wake up about a tenth after A lets go. Okay. And the first thing a reviewer will ask is, "So now every checkout waits in line behind the slowest one?" Partly, yes. Writers now queue from their first statement, so honestly, say you put a slow API call inside one checkout's transaction: it holds up every other writer until that checkout commits. Keep calls like that outside, and let pure reads stay deferred rather than queueing behind them.

6:08 And if a deferred transaction does hit busy snapshot anyway, there's a second fix: retry the whole thing from its read. Why start over? Why not just let SQLite refresh the snapshot and rerun the update? Because your code computed that 9 from the stale 10. SQLite can't redo your math, so the read has to run again. Okay, that makes sense. But I'm realizing most of us never type BEGIN ourselves. Take a Django atomic block that reads a row and then saves it: Django sends BEGIN up front, so that block can hit the same failure.

6:43 Can you make Django send BEGIN IMMEDIATE instead? Since version 5.1, yes, with a transaction mode option. Django's docs say to set it to immediate so transactions wait until the timeout before raising "database is locked." And Rails went further. A merged Rails pull request made immediate the default for SQLite transactions, and its description blames those locked errors on this deferred upgrade. Yeah. Python's built-in SQLite module is the trap, though. Its isolation level setting only picks which BEGIN it sends, and in its default mode it sends that BEGIN just before your first write, not before your SELECT.

7:20 So even set to immediate, the read isn't inside the transaction? Right. We tried that setting, which sounds like the fix: A reads 10, B commits 9, A writes 9. No error at all, final quantity 9, and B's sale is silently gone. Oh, that's nastier than the error. A silent lost update is not a failure anyone gets paged for. So in plain Python, I'd issue BEGIN IMMEDIATE myself, before the read, and if anything I leave deferred fails instantly, I'd rerun it from the read. In code review, I'd look for a transaction that read before it wrote.

7:58 Yeah. If "database is locked" arrives faster than your timeout, it almost certainly wasn't a waiting problem. A timeout only helps when waiting can actually succeed. Thanks for listening to Learning Podcasts.