PREP WITH PROOF
Menu
DATABASES & TROUBLESHOOTING / PRACTICAL GUIDE

SQLite Database Is Locked: Busy Timeouts, Transactions and WAL

Diagnose SQLite lock errors, distinguish writer contention from stale WAL snapshots, and choose a safe recovery. Includes a complete two-connection Python lab.

THE QUICK ANSWER

A busy timeout can wait for another SQLite connection to release a lock, but it cannot make an obsolete WAL read snapshot writable. Capture the extended error code, identify the transaction boundary and shorten lock ownership. Restart a stale read-to-write transaction from a fresh read rather than repeatedly retrying its final UPDATE.

The failing UPDATE may be the end of a much older transaction

A background job writes one small row and receives database is locked. The query looks cheap, so the first reaction is to increase its timeout. Yet the lock owner might be a request that opened a transaction before a slow API call, an administration tool left mid-edit, or another worker writing continuously. Query size alone does not establish how long the database is occupied.

The useful investigation begins with the connection and transaction that failed, not a global search-and-replace of timeout values. Record the error code, journal mode, operation phase and transaction duration. A failure at BEGIN, during a read-to-write upgrade, or at COMMIT can require different recovery decisions.

This guide includes a complete local lab tested with Python 3.12.14 and its SQLite 3.53.1 library. It uses two independent connections with deliberately ordered operations in one process. It creates temporary databases only; no existing database, production lock or filesystem setting is changed.

Read the result code behind the message

SQLITE_BUSY generally means a conflict with a different connection. SQLITE_LOCKED generally concerns the same connection or connections sharing a cache. The extended SQLITE_BUSY_SNAPSHOT code identifies a WAL read transaction that cannot become a writer because another connection committed after that snapshot was established.

In Python, SQLite-originated exceptions expose sqlite_errorcode and sqlite_errorname. Capture these alongside the operation phase, without logging sensitive SQL values. Matching only the substring locked loses the distinction between a writer that may finish soon and a snapshot that must be abandoned.

OperationalError is a broad exception class, not a retry policy. Permission problems, full storage and unrelated operational failures should not silently enter the same retry loop. If your framework hides the native code, inspect its underlying exception and transaction API before changing behavior.

EvidenceInterpretationRecovery question
SQLITE_BUSY at BEGIN IMMEDIATEAnother writer may hold the databaseCan it finish within this operation’s budget?
SQLITE_BUSY_SNAPSHOT on UPDATEThe WAL read snapshot is obsoleteCan the entire transaction be restarted safely?
SQLITE_LOCKEDConnection/shared-cache conflictWhich active statement or connection ownership overlaps?

Source: SQLite: result and extended error codes ↗

WAL improves overlap; it does not add concurrent writers

Separate connections can read concurrently, but writes to one SQLite database are serialized. Opening more pooled connections does not create more independent write slots. It can instead create a longer queue of waiting work when every request tries to write.

WAL allows readers and a writer to overlap while readers retain their snapshots. There is still one writer at a time. Switching journal modes therefore cannot repair an application that holds a write transaction throughout slow external work or expects unlimited simultaneous writers.

Use transaction-duration evidence to decide whether contention is an ownership problem, a workload burst, or a sustained architecture mismatch. A single writer queue with bounded admission may be sufficient for a modest application. Sustained concurrent write demand may justify a server database, but first establish what the existing workload actually needs.

Source: SQLite: isolation and serialized writes ↗

Treat the busy timeout as a waiting allowance

A busy timeout installs connection-level waiting behavior for lock contention. When waiting is exhausted, the operation can still return SQLITE_BUSY. A busy handler is not guaranteed to run for every conflict, so do not promise that every failure will wait the full configured duration.

Python’s connect(timeout=...) uses seconds. PRAGMA busy_timeout uses milliseconds and applies to that connection. Initialize every connection deliberately; do not assume that configuring one pooled connection configures all future connections. Setting a new busy handler or timeout can replace earlier handler behavior.

Choose the wait within the caller’s total deadline, together with connection acquisition, SQL work and any application retries. A larger timeout can reduce immediate errors while increasing blocked requests and tail latency. It does not shorten the owner’s transaction or create more write capacity.

-- Run on the specific connection whose policy you are inspecting.
PRAGMA journal_mode;
PRAGMA busy_timeout;
-- Example connection-level allowance, not a recommended universal value:
PRAGMA busy_timeout = 250;

Source: SQLite: busy timeout API ↗

Make transaction start and end explicit

BEGIN DEFERRED does not reserve the writer immediately. A transaction that first reads may later need to upgrade when it writes. BEGIN IMMEDIATE attempts to start a write transaction at the beginning, so writer contention can be discovered before application work depends on a read snapshot.

Acquiring the writer earlier is a tradeoff, not a blanket optimization. Keep validation and network calls that do not require database ownership outside that interval. Once the transaction starts, perform the necessary database work and finish promptly. Do not hold the writer while sleeping between application retry attempts.

Also distinguish a failed statement from a finished transaction. In rollback-journal mode, COMMIT can return SQLITE_BUSY because a reader remains active, leaving the write transaction open. Depending on the driver and operation contract, retrying that same COMMIT within a bound can be appropriate; replaying the UPDATE as well could apply the change twice.

Source: SQLite: transaction control and COMMIT behavior ↗

A complete lab: writer contention versus a stale snapshot

Save this as sqlite_lock_lab.py and run python3 -B sqlite_lock_lab.py with Python 3.12 or newer. The connection factory explicitly uses autocommit=True, then controls transactions using SQL BEGIN, COMMIT and ROLLBACK. This avoids depending on Python’s legacy implicit-transaction defaults.

The first two scenarios hold a writer open in DELETE and WAL modes. The second connection cannot become a writer until the first commits. Its short 0.05-second timeout makes the controlled demonstration finish promptly; it is not a production recommendation or a measured latency guarantee.

The final scenario keeps a WAL reader’s old view, commits a change on another connection, then attempts to write from the old snapshot. The lab checks the extended error code, rolls back, reads again in a fresh transaction and verifies the final value. Every connection closes before temporary-directory cleanup.

# Python 3.12+; creates databases only inside a temporary directory.
from contextlib import closing
from pathlib import Path
import sqlite3
import tempfile


def connect(path):
    # Use explicit SQL BEGIN/COMMIT/ROLLBACK throughout this lab.
    return sqlite3.connect(path, timeout=0.05, autocommit=True)


def prepare(path, mode):
    with closing(connect(path)) as db:
        actual = db.execute(f'PRAGMA journal_mode={mode}').fetchone()[0]
        assert actual.lower() == mode.lower(), actual
        db.execute('CREATE TABLE counter (id INTEGER PRIMARY KEY, value INTEGER)')
        db.execute('INSERT INTO counter VALUES (1, 0)')


def writer_conflict(path, mode):
    prepare(path, mode)
    with closing(connect(path)) as a, closing(connect(path)) as b:
        a.execute('BEGIN IMMEDIATE')
        a.execute('UPDATE counter SET value=value+1 WHERE id=1')
        try:
            b.execute('BEGIN IMMEDIATE')
        except sqlite3.OperationalError as exc:
            assert exc.sqlite_errorcode & 255 == sqlite3.SQLITE_BUSY
            print(mode, 'second writer:', exc.sqlite_errorname)
        else:
            raise AssertionError('A second writer unexpectedly started')
        a.execute('COMMIT')
        b.execute('BEGIN IMMEDIATE')
        b.execute('UPDATE counter SET value=value+1 WHERE id=1')
        b.execute('COMMIT')
        assert b.execute('SELECT value FROM counter').fetchone()[0] == 2
        assert not a.in_transaction and not b.in_transaction


def stale_snapshot(path):
    prepare(path, 'WAL')
    with closing(connect(path)) as a, closing(connect(path)) as b:
        a.execute('BEGIN')
        assert a.execute('SELECT value FROM counter').fetchone()[0] == 0
        b.execute('BEGIN IMMEDIATE')
        b.execute('UPDATE counter SET value=value+1 WHERE id=1')
        b.execute('COMMIT')
        assert a.execute('SELECT value FROM counter').fetchone()[0] == 0
        try:
            a.execute('UPDATE counter SET value=value+1 WHERE id=1')
        except sqlite3.OperationalError as exc:
            assert exc.sqlite_errorcode == sqlite3.SQLITE_BUSY_SNAPSHOT
            print('WAL read upgrade:', exc.sqlite_errorname)
        else:
            raise AssertionError('An obsolete snapshot unexpectedly wrote')
        a.execute('ROLLBACK')
        # Restart the whole logical transaction, including its read.
        a.execute('BEGIN IMMEDIATE')
        assert a.execute('SELECT value FROM counter').fetchone()[0] == 1
        a.execute('UPDATE counter SET value=value+1 WHERE id=1')
        a.execute('COMMIT')
        assert b.execute('SELECT value FROM counter').fetchone()[0] == 2
        assert not a.in_transaction and not b.in_transaction


with tempfile.TemporaryDirectory(prefix='sqlite-lock-lab-') as directory:
    root = Path(directory)
    writer_conflict(root / 'delete.db', 'DELETE')
    writer_conflict(root / 'wal.db', 'WAL')
    stale_snapshot(root / 'snapshot.db')
print('PASS: writer release and fresh-transaction recovery; SQLite',
      sqlite3.sqlite_version)

Source: Python sqlite3: connections and transaction control ↗

Retry the unit of work that can become correct

After SQLITE_BUSY_SNAPSHOT, waiting cannot refresh the existing read transaction. End it and restart the logical transaction, including every read used to make the write decision. Retrying only the last UPDATE against previously computed values can retain the very assumption that became invalid.

For ordinary writer contention, a bounded wait or a bounded transaction retry may be sufficient after the owner finishes. Establish a maximum attempt count and overall deadline, release transaction ownership before backing off, and expose exhaustion to the caller. Avoid retrying indefinitely in a worker that accepts unlimited queued jobs.

A database retry must also respect external side effects. Sending an email or charging a payment inside a retried transaction does not become reversible because SQLite rolled back. Keep such effects outside the replayed unit or use an explicitly designed idempotent workflow. The lab has no external effects, so its replay is deliberately simpler.

Close the work that keeps a read transaction alive

Examine long-lived result iteration, open cursors and explicit transactions that survive while a client consumes a response. Fetching a small result and finishing promptly may have very different lock behavior from streaming a large result while holding database resources across slow client reads.

In WAL, long-running readers can prevent checkpoint progress from reaching a point that would let the WAL reset. A growing WAL file is therefore a reason to inspect transaction lifetimes and checkpoint behavior, rather than proof that the next write merely needs a longer timeout.

Python’s connection context manager handles transaction success or failure under its transaction-control rules; it does not close the connection. The lab uses contextlib.closing to make ownership explicit and SQL statements to end transactions. In a framework, use the documented session, cursor and connection lifetime contracts instead of assuming all context managers mean close.

Source: SQLite: WAL concurrency, checkpoints and version guidance ↗

Verify the database, mode and library you actually run

Confirm that competing workers refer to the intended database path. A relative path evaluated from another working directory may inspect a different file and produce reassuring but irrelevant observations. Record the application’s SQLite library version; the sqlite3 command-line tool may use another build.

Changing journal_mode to WAL is persistent for the database, so treat it as a reviewed deployment change and check the returned mode. WAL depends on same-machine shared memory and is unsuitable for ordinary cross-host network-filesystem access. Verify the actual storage arrangement instead of assuming a mounted path behaves like local storage.

The official WAL documentation also describes the 2026 WAL-reset fix. Use a library release or documented vendor backport that includes it; the lab’s SQLite 3.53.1 is newer than the fixed 3.51.3 release. Version review complements contention diagnosis and should not be replaced by repeated retries.

Source: SQLite: WAL concurrency, checkpoints and version guidance ↗

Collect evidence without trying to remove the lock files

Build a timeline of transaction start, first write, commit or rollback, and connection release. Include the job or request identity and concurrency level. Compare the lock error rate with transaction duration and queued writes before and after a fix. Successful recovery means stable completion under the relevant workload, not merely one successful request after a restart.

Do not delete a database journal or WAL file to clear a lock. These files participate in recovery and database state; removing them while the database is in use can cause corruption or data loss. Use a supported backup or recovery procedure when investigating damage, and preserve the evidence before changing files.

Reduce the reproduction to the smallest sequence that preserves the failure. Specify journal mode, transaction order, driver version and error name. The included lab is useful for recognizing two mechanisms, but it is not a cross-process stress test, a benchmark, or validation of your deployment’s storage locking.

Source: SQLite: journal files and corruption hazards ↗

Choose the smallest fix that matches the failure

If a writer owns the database too long, shorten that ownership and bound incoming work. If a stale snapshot cannot upgrade, restart from a fresh transaction and reread the decision inputs. If a same-connection conflict occurs, inspect active statements and connection sharing. These are different repairs even when the visible message looks similar.

After the change, verify both correctness and resource lifetime. Repeat representative success, failure and cancellation paths. Check that transactions end, connections return to their intended owner and retries stop within the caller’s budget. Keep the reproduction and before-and-after evidence with the change.

A timeout is one part of a contention policy. The stronger result is knowing which transaction held what, why the next operation could not proceed, and which bounded recovery preserves the application’s decision.

KEEP THESE THREE THINGS

Your next steps

  1. Capture native error codes and the failing transaction phase before changing timeout values.
  2. Use the temporary lab to distinguish a busy writer from a WAL snapshot that requires a fresh transaction.
  3. Shorten ownership, bound retries and validate cleanup under representative workload; preserve journal and WAL files.

Sources & official resources

Linked resources checked on 2026-10-27. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →