brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: PRAGMA busy_timeout makes SQLite wait for a lock instead of failing at once

Sqlite
~/tips/tip-database-sqlite-pragma-busy-timeout

sqlite> PRAGMA busy_timeout = 5000;

Sets how long a SQLite connection waits for a locked database before it reports an error.

"database is locked" is the classic SQLite error when two programs touch the same file. Often the lock is only there for a few milliseconds, and the second program gave up too quickly. A busy timeout makes it wait a bit.

sqlite3 app.db
sqlite> PRAGMA busy_timeout = 5000;

The value is in milliseconds, so this lets the connection wait up to five seconds for a lock to clear before it returns the busy error. The docs describe the pragma as an alternative to the C function sqlite3_busy_timeout(), meant for language bindings that cannot call it directly. The maximum is 2147483647 milliseconds, roughly 24.9 days, and the result of a larger value is not defined.

Running PRAGMA busy_timeout; without a value returns the current setting.

There is a catch that the docs state: each connection can have only a single busy handler, and this pragma sets it for the whole process, so it can overwrite a handler that was set before. If your program already installs its own busy handler, do not set both.

It is also a setting of the connection, not of the database file. Setting it in the sqlite3 shell helps the shell and nothing else, so the app that gets the errors has to set it itself. Check how your language or library exposes it.

A longer timeout hides contention. If you need ten seconds to get through, something holds the lock for too long, and the fix is a shorter transaction.

Further reading: SQLite: PRAGMA Statements (busy_timeout)

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state sqlite3 -bail app.db < migrate.sql CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) CREATE INDEX users_active_email ON users(email) WHERE active = 1; All Sqlite tips (27) All topics

Link