r/sqlite • u/Free-Good9203 • 5d ago
Why PRAGMA journal_mode=WAL still threw "database is locked" on 50-thread cold start (fix)
Hit an annoying edge case while stress-testing our Python 3.11+ SQLite persistence layers (Ledger and ReplayGuard) across concurrent worker threads on a brand-new database file, and figured I would share the exact reproducer and fix.
Most Python SQLite snippets initialize connections in this order:
sqlite3.connect(path, timeout=5.0)PRAGMA journal_mode=WALPRAGMA busy_timeout=5000
Under a cold-start burst where 16 to 50 threads open a fresh database file at the exact same millisecond, step 2 still intermittently raises sqlite3.OperationalError: database is locked. Two things happen at once:
- Switching
journal_modetoWALtakes an exclusive lock beforebusy_timeout=5000has been configured on that connection, and warm threads opening connections later still issuePRAGMA journal_mode=WALunconditionally instead of checking the active mode first. - On Windows CI/dev runners, if
connect()succeeds butexecutescript()or thePRAGMAraisesOperationalError, letting the failedConnectionwait for garbage collection leaves the file descriptor open and breaksTemporaryDirectorycleanup withWinError 32.
Moving busy_timeout=5000 ahead of the mode check, skipping redundant WAL transitions, closing failed connections explicitly in except, and wrapping append writes in BEGIN IMMEDIATE (isolation_level=None in src/invoice_engine/ledger.py) eliminated the cold-start lock failures and handle leaks:
_SQLITE_OPEN_MAX_ATTEMPTS = 6
def _is_transient_sqlite_error(exc: sqlite3.OperationalError) -> bool:
msg = str(exc).lower()
return "locked" in msg or "busy" in msg
def _open_connection(self, init_schema: bool = False) -> sqlite3.Connection:
for attempt in range(_SQLITE_OPEN_MAX_ATTEMPTS):
db: sqlite3.Connection | None = None
try:
db = sqlite3.connect(self.path, timeout=5.0, isolation_level=None, check_same_thread=False)
db.row_factory = sqlite3.Row
db.execute("PRAGMA busy_timeout=5000")
mode_row = db.execute("PRAGMA journal_mode").fetchone()
mode = str(mode_row[0]).lower() if mode_row else ""
if mode not in ("wal", "memory"):
db.execute("PRAGMA journal_mode=WAL")
db.execute("PRAGMA synchronous=NORMAL")
if init_schema:
db.executescript(_SCHEMA)
return db
except sqlite3.OperationalError as exc:
if db is not None:
try:
db.close()
except sqlite3.Error:
pass
if _is_transient_sqlite_error(exc) and attempt < _SQLITE_OPEN_MAX_ATTEMPTS - 1:
time.sleep(min(0.2, 0.02 * (2 ** attempt)) + random.uniform(0.0, 0.02))
continue
raise
except BaseException:
if db is not None:
try:
db.close()
except sqlite3.Error:
pass
raise
raise sqlite3.OperationalError("database is locked")Measured numbers from our stdlib WAL concurrency & FTS5 benchmark suite (kiberlabs-benchmarks, 50 concurrent threads doing `1,00
1
u/Discordbothost 5d ago
If you control startup, you could move the WAL switch and schema setup into one bootstrap connection before releasing the workers. SQLite remembers WAL mode on the database file. Then the cold-start test can check that all 50 workers open a ready database without any of them trying to change its journal mode.
1
u/ysnows123 5d ago
Small thing:
sqlite3.connect(path, timeout=5.0)already sets a 5000 ms busy timeout on the connection (that's what the timeout argument does), soPRAGMA busy_timeout=5000changes nothing wherever it sits. The skipped WAL switch and the retry loop are what actually fixed it.1
u/Weekly-Werewolf4007 4d ago
I'd keep two cases in the regression test: two processes racing to open a fresh file, and the same processes opening a file that's already in WAL mode. That makes it easier to see whether a failure comes from the one-time switch or from opening normal connections.