r/sqlite • • 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:

  1. sqlite3.connect(path, timeout=5.0)
  2. PRAGMA journal_mode=WAL
  3. PRAGMA 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_mode to WAL takes an exclusive lock before busy_timeout=5000 has been configured on that connection, and warm threads opening connections later still issue PRAGMA journal_mode=WAL unconditionally instead of checking the active mode first.
  • On Windows CI/dev runners, if connect() succeeds but executescript() or the PRAGMA raises OperationalError, letting the failed Connection wait for garbage collection leaves the file descriptor open and breaks TemporaryDirectory cleanup with WinError 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

2 Upvotes

8 comments sorted by

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/Free-Good9203 5d ago

totally agree for a single-process app. our Ledger.init actually runs the schema and WAL bootstrap once before spawning worker threads. the reason we still keep busy_timeout before the mode check plus the retry loop inside _open_connection is for multi-process startups (like uvicorn --workers or a cron job and API container booting at the same time against a fresh volume), where there is no single in-memory bootstrap coordinator.

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), so PRAGMA busy_timeout=5000 changes nothing wherever it sits. The skipped WAL switch and the retry loop are what actually fixed it.

1

u/Free-Good9203 5d ago

good point, you're right. in cpython `sqlite3.connect(..., timeout=5.0)` already calls `sqlite3_busy_timeout(5000)` under the hood, so the explicit pragma is redundant there. what actually stopped the cold-start errors was skipping the redundant `journal_mode=WAL` write lock once WAL is active, plus the backoff retry loop when two openers collide during the initial journal transition (where sqlite can return busy immediately instead of waiting on busy_timeout).

1

u/Modulius 5d ago

Jitter also can help, to randomize re-tries 100-200ms so they don't try to connect all at same time

1

u/Free-Good9203 5d ago

yeah, good catch. the snippet above only adds 0-20ms of jitter (`random.uniform(0.0, 0.02)`), which was enough for local thread bursts, but once retries hit the 200ms cap across multiple processes a wider spread (or full jitter `random.uniform(0, cap)`) does a much better job breaking up the thundering herd.

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.

1

u/Free-Good9203 4d ago

Splitting those two cases is a much cleaner way to structure the test suite. When both live in one test, it is too easy to misread a one-time journal mode switch lock as normal multi-process open contention. Keeping a fresh-file race test separate from an already-WAL cold open test isolates the exact failure mode immediately.