It is a common story. A small service uses SQLite and runs fine for weeks.
Then one afternoon the logs start to fill with database is locked. Not all
the time. A few times an hour, always on writes, always when two requests land
together.
The usual advice is to set a busy timeout of five seconds. The errors go down, but they don’t go away. Some of them still come back after a few microseconds, not after five seconds. That is the confusing part. A timeout that does not wait looks like a bug until you know how SQLite hands out locks.
Short version:
- SQLite locks the whole database file. There are no row locks and no table locks in normal use. Many connections can read, but only one can write.
- A second writer gets
SQLITE_BUSY(“database is locked”). The default busy timeout is 0, so it fails at once. SetPRAGMA busy_timeouton every connection. - A transaction that reads first and writes later can fail right away, even
with a timeout. Start every transaction that will write with
BEGIN IMMEDIATE.
The problem: one writer per database file
SQLite is a library that runs inside your process. There is no server to queue requests for you. Each connection talks to the same file on disk, and the connections agree on who goes first by taking locks on that file.
The rule is simple. Any number of connections can read at the same time. Only
one can write at a time. When a connection asks for a lock that another
connection holds, SQLite has two options. It can return SQLITE_BUSY
straight away, or it can call a busy handler that sleeps and tries again.
The busy handler is what busy_timeout turns on. The docs say it plainly: the
default busy callback is NULL, and then SQLITE_BUSY is returned immediately
when SQLite meets the lock. So out of the box a second writer does not wait.
Some drivers set their own default. Python’s sqlite3 module waits up to 5
seconds. The sqlite3 command line tool waits 0 seconds. Check what your
connection really uses:
PRAGMA busy_timeout; -- 0 means "fail at once"
PRAGMA busy_timeout = 5000; -- wait up to 5000 ms
The setting belongs to the connection, not to the file. Every connection in your pool needs it.
What “database is locked” actually means
The message is the text for the result code SQLITE_BUSY (code 5). The docs
say it means the file could not be written, or sometimes read, because of
another connection, usually one in a separate process.
There is a second, similar code, SQLITE_LOCKED (code 6). It means a conflict
inside the same connection, or with another connection that shares a cache.
Shared-cache mode is the one place where SQLite does lock per table. The docs
call that mode obsolete and discourage it, and say WAL mode serves most of
those use cases better. So for normal use, think “one lock for the whole
file”.
The five lock states (rollback journal mode)
By default, SQLite uses a rollback journal. In this mode a connection moves through five lock states. This is the part of the locking docs worth knowing by heart.
Here is the order a write takes, with what each step blocks:
UNLOCKED idle, nobody is blocked
|
SHARED reading. Many at once. Blocks: any write to the file
|
RESERVED "I will write soon". Only ONE at a time.
| Blocks: a second RESERVED. New readers are still let in.
|
PENDING "I want to commit now". Waits for readers to finish.
| Blocks: new SHARED locks. Old readers may finish.
|
EXCLUSIVE writing the file. Blocks: everything, even readers.
While a connection holds RESERVED, it can already change pages, but at
first only in memory. The database file stays as it was, so other connections
keep reading.
The connection needs EXCLUSIVE only at commit time, when it writes the
changes into the file. PENDING is there to stop a steady stream of new
readers from starving the writer.
Two things follow from this:
- Only one connection can get
RESERVED. That is the “one writer” rule. A second connection that asks for it getsSQLITE_BUSY. - A reader can stop a commit. Commit needs
EXCLUSIVE, and that waits for everySHAREDlock to go. A connection that read something and never finished its transaction keeps writers from committing. The docs say aCOMMITcan returnSQLITE_BUSYfor this reason, and that you can retry it later.
WAL mode: readers and the writer stop blocking each other
Write-ahead logging (WAL) is the fix most people reach for first. Turn it on once:
PRAGMA journal_mode = WAL;
It is saved in the database file, so it stays on after you close and reopen
the database. In WAL mode, changes go to a separate -wal file instead of
overwriting the main file. The WAL docs
state the result: readers do not block the writer, and the writer does not
block readers. Each reader sees the database as it was when its transaction
began.
WAL does not give you more than one writer. The docs are clear: there is
only one WAL file, so there can only be one writer at a time. A second writer
still gets SQLITE_BUSY. WAL only removes the readers from the fight.
WAL has costs:
- All processes must run on the same machine. WAL does not work over a network file system, because it needs shared memory.
- There are two extra files next to the database,
-waland-shm. Keep them together with the database if you copy or move it. SQLITE_BUSYcan still appear for readers in a few cases: another connection uses exclusive locking mode, the last connection is cleaning up the WAL files while you open the database, or a connection is running crash recovery.
My production defaults, including the other pragmas that go with WAL, are in the SQLite for high-traffic websites post.
The trap: a deferred transaction that reads, then writes
A plain BEGIN starts a deferred transaction. It takes no lock when it
starts. The docs say it begins when the database is first used: if the first
statement is a SELECT, it is a read transaction. A later write “will upgrade
the transaction to a write transaction if possible, or return SQLITE_BUSY”.
When the upgrade is not possible, busy_timeout is not used. The write fails
at once:
-- connection A -- connection B
BEGIN; BEGIN;
SELECT balance FROM accounts SELECT balance FROM accounts
WHERE id = 1; WHERE id = 1;
UPDATE accounts SET ...; -- A holds RESERVED
UPDATE accounts SET ...;
-- B: SQLITE_BUSY, at once
B does not wait because waiting could not help. A needs B’s SHARED lock to go
away before it can commit, and B would be waiting for A. The
sqlite3_busy_handler docs describe this case: if both called their busy
handlers, neither would make progress. So SQLite returns SQLITE_BUSY to the
first one and never calls the busy handler. There is no deadlock detector that
picks a victim. SQLite avoids the deadlock by failing one side early.
I ran it with SQLite 3.51.0 and a 5000 ms timeout on both connections. B failed
in 0.0 seconds. The same test in WAL mode also failed at once. WAL has its own
form of this error, SQLITE_BUSY_SNAPSHOT (517), when another connection has
written since the read began. Waiting cannot help there either, because the
reads are stale. The transaction has to start over.
The fix: BEGIN IMMEDIATE
If you know a transaction will write, say so at the start:
BEGIN IMMEDIATE;
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;
BEGIN IMMEDIATE takes the write lock right away. The failure, if any, now
happens at the very start, before you read anything, where the busy handler
is allowed to wait. In my test, the first connection held the lock for one
second. The second connection waited about one second, then ran, in both
rollback and WAL mode. Both updates were kept. If a transaction still fails
with SQLITE_BUSY after BEGIN IMMEDIATE, the timeout ran out. Retry the
whole transaction, not only the last statement.
Drivers often open the transaction for you, and not always with the BEGIN you
want. The settings for Python, Django, Go, Node and Rust, the 517 case in WAL
mode and an eight-thread test with counts are in
SQLITE_BUSY in WAL mode with busy_timeout set.
Long transactions and checkpoints
Locks last as long as the transaction does. The most common real cause of
database is locked that I see is not two fast writers. It is one slow
transaction.
- A write transaction that calls the network. It holds the write lock the whole time. Every other writer waits, then fails when the timeout ends. Do slow work outside the transaction.
- A read that never finishes. An implicit transaction ends when its last
statement finishes, and a statement only reliably finishes when you reset or
finalize it. A cursor left half read, or a forgotten
BEGIN, can hold a read lock for as long as the connection lives. In rollback mode that stops every commit.
In WAL mode a long reader does not block the writer, but it causes a
different problem. Changes pile up in the -wal file until a checkpoint
copies them back into the main file. SQLite runs one automatically when the
WAL reaches 1000 pages. That automatic checkpoint is the PASSIVE kind: it does
as much as it can without getting in the way, and it may not finish if readers
are active.
The docs warn about the bad case. A checkpoint can only run to completion, and reset the WAL, when no connection is using the old data. If there is always at least one active reader, with overlapping transactions and no gap, no checkpoint finishes and the WAL file grows without bound.
What helps:
PRAGMA wal_checkpoint(TRUNCATE); -- run a checkpoint now and shrink the WAL
PRAGMA journal_size_limit = 67108864; -- cut the WAL back to 64 MB after resets
Run the TRUNCATE checkpoint at a quiet moment. The docs warn that readers might block while such a checkpoint runs, and the pragma tells you if it was blocked. The size limit is only a cap on the leftover file. It does not fix the reader that causes the growth. The real fix is short read transactions.
Faster queries also mean shorter locks. See SQLite index optimisation for how to find the slow ones.
“database is locked” checklist
Work through these in order. The diagram is the same list.
- Check the timeout on the connection that fails. Run
PRAGMA busy_timeout;there. A pool can contain connections that were opened without it. - Find the read-then-write transactions. Look in your code or ORM for a
SELECTfollowed by anUPDATEinside one transaction. Switch it toBEGIN IMMEDIATE. - Find the long transactions. Log how long each write transaction stays open. Anything over a second or so is a suspect. Look for network calls, file work or user waits inside the transaction.
- Look for forgotten readers. A script, an admin tool or a debugger
session left open on the same file can hold a read lock. On Linux or macOS,
lsof app.dbshows which processes have the file open. - Check the journal mode.
PRAGMA journal_mode;should saywalfor most web apps. - Check the file system. A database on a network share or a shared volume breaks locking. WAL does not work there at all.
- Look at your backups. A copy of the file while a write is running can be inconsistent, and a long dump holds a read lock. Use SQLite’s own backup tools.
If all of that is clean and writes still collide, you have more write traffic than one file can take. Send writes through one connection (a small queue in your app is enough), or use a database that has real row locks. I wrote about how Postgres locks work and how to build a job queue in Postgres if you get there.
The result codes at a glance
| Code | Number | Meaning |
|---|---|---|
SQLITE_BUSY | 5 | Another connection, usually in another process, holds a lock you need |
SQLITE_BUSY_SNAPSHOT | 517 | WAL: you tried to write after another connection wrote since your read began |
SQLITE_BUSY_RECOVERY | 261 | WAL: another process is recovering the database after a crash |
SQLITE_LOCKED | 6 | A conflict inside one connection, or with a shared-cache connection |
With a 5000 ms timeout on both connections, the second update failed in 0.0
seconds. The timeout never got a turn. WAL does not change that. The write has
to be declared at BEGIN, which is what
BEGIN IMMEDIATE is for.
Questions people ask
Does busy_timeout fix “database is locked”?
It fixes the plain case, where a writer has to wait for another writer. It
does not help in a read-then-write upgrade that SQLite cannot allow, because
SQLite returns SQLITE_BUSY there without calling the busy handler. For that
case you need BEGIN IMMEDIATE.
Does SQLite have deadlocks?
Not in the usual sense. SQLite does not detect a deadlock and pick a victim.
It sees that two waits could block each other, and it fails one side early with
SQLITE_BUSY. Your code is expected to roll back and retry.
Can SQLite handle concurrent writes? Many connections can ask at the same time, but SQLite runs the writes one after another. For short transactions that is often fast enough. The limit is how long each write holds the lock, not how many connections you open.
Cheat sheet
Further reading
- SQLite docs: file locking and concurrency
- SQLite docs: write-ahead logging
- SQLite docs: BEGIN, COMMIT and ROLLBACK
- SQLite docs: sqlite3_busy_timeout() and sqlite3_busy_handler()
- SQLite docs: result and error codes
- SQLite docs: shared-cache mode
- SQLite for high-traffic websites on this site
- SQLite index optimisation on this site
- Understanding PostgreSQL locks on this site
- Postgres as a job queue on this site