Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: sqlite3.OperationalError: database is locked

One writer at a time is SQLite's rule. Shorten transactions, enable WAL, take BEGIN IMMEDIATE up front and retry busy errors with backoff.

~5 min readPython
#python#sqlite#concurrency#database
Bold white headline reading DATABASE LOCKED with a SQLite file crate sealed by an amber lock while a cyan writer waits.

Introduction & Quick Summary

A small web app starts returning 500s under load:

sqlite3.OperationalError: database is locked

Quick answer: another connection is writing, and this connection waited out its busy timeout. SQLite allows one writer at a time; the fix is to hold write transactions briefly, enable WAL so readers do not block the writer, and give busy waits a sane timeout.

python
import sqlite3 conn = sqlite3.connect("app.db", timeout=10.0) # busy timeout in seconds conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA busy_timeout=10000") # milliseconds, same effect conn.execute("PRAGMA synchronous=NORMAL")

The error is SQLITE_BUSY, surfaced through Python's OperationalError. It is not corruption and not a permissions problem: the file is fine, and the database is telling you that a lock is held. database table is locked names a specific table lock, and database is locked names the whole database; both come from the same contention.

What people miss is the default. sqlite3.connect() uses a 5-second timeout, and Python's legacy transaction mode opens a transaction before the first INSERT, UPDATE or DELETE and keeps it open until you commit. One forgotten commit in a worker keeps every other writer waiting, and five seconds later the error appears somewhere unrelated.

Core Mechanics, Signatures & Reproducible Setup

Reproduce deterministically with two connections:

python
import sqlite3, threading, time setup = sqlite3.connect("lock.db") setup.execute("CREATE TABLE IF NOT EXISTS jobs (id INTEGER PRIMARY KEY, state TEXT)") setup.commit() setup.close() def writer(): c = sqlite3.connect("lock.db") c.execute("BEGIN IMMEDIATE") c.execute("INSERT INTO jobs (state) VALUES ('running')") time.sleep(8) # a long transaction c.commit() c.close() threading.Thread(target=writer, daemon=True).start() time.sleep(1) try: c2 = sqlite3.connect("lock.db", timeout=2) c2.execute("INSERT INTO jobs (state) VALUES ('queued')") c2.commit() except sqlite3.OperationalError as exc: print("expected:", exc) # database is locked after 2 seconds
Journal modeWriter blocks readersReaders block writerConcurrency
DELETE (default)yes, during writeyesone operation at a time
WALnono, readers see a snapshotone writer with many readers
TRUNCATE or PERSISTyesyesmarginally faster than DELETE
MEMORYyesyesunsafe across crashes
OFFcorrupts on crash—never use

Key Comparison Table

CauseSymptomFix
Uncommitted write transactionerror only under concurrent writescommit or roll back promptly
Shared connection across threadssporadic, often under loadone connection per thread
Default journal modereaders block the writerPRAGMA journal_mode=WAL
5-second default timeouterrors on slow queriesraise timeout and busy_timeout
Network filesystemlocking unreliable, hangskeep the database on local disk
Long transaction around network callswrites pile upmove I/O outside the transaction

Python API choices that change behaviour:

SettingDefaultEffectRecommended
timeout5.0 secondsbusy wait before SQLITE_BUSY10 to 30 for write paths
isolation_level"" (implicit BEGIN)transaction opens on first DMLexplicit BEGIN IMMEDIATE for writes
check_same_threadTruerejects cross-thread usekeep True, one connection per thread
autocommitnot set (3.12+)PEP 249-style controlTrue plus explicit transactions
detect_types0no type conversionunrelated to locking

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Find the transaction that is holding the lock

python
conn = sqlite3.connect("app.db") print(conn.in_transaction) # True means an implicit transaction is open conn.execute("PRAGMA busy_timeout") conn.execute("PRAGMA journal_mode").fetchone()

If in_transaction is True after a read path returns, a write happened earlier and was never committed. Context managers commit on success and roll back on exception, so use them:

python
with sqlite3.connect("app.db") as conn: conn.execute("UPDATE jobs SET state = 'done' WHERE id = ?", (job_id,)) # committed here; an exception rolls back

Note that with sqlite3.connect(...) in the legacy mode manages the transaction, not the connection: the connection stays open. Close it explicitly or use contextlib.closing.

2. WAL and busy timeout together

python
def connect(path: str) -> sqlite3.Connection: conn = sqlite3.connect(path, timeout=15.0) conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA busy_timeout=15000") conn.execute("PRAGMA synchronous=NORMAL") return conn

WAL is persistent for the database file: setting it once is enough, but setting it on every connection is harmless and self-documenting. It creates app.db-wal and app.db-shm files, so backups must copy all three or use sqlite3.Connection.backup(). synchronous=NORMAL in WAL mode is safe against application crashes and only risks the last transactions on a power loss, which is the usual trade for a web app.

3. Threads, processes and connection ownership

python
import sqlite3, threading local = threading.local() def get_conn() -> sqlite3.Connection: if not hasattr(local, "conn"): local.conn = sqlite3.connect("app.db", timeout=15.0, check_same_thread=True) return local.conn

One connection per thread removes cross-thread contention inside the process. Across processes, no configuration removes the single-writer rule; a queue that funnels writes through one process is more reliable than tuning timeouts. check_same_thread=False only disables a guard: it lets two threads share a connection and serialize at the C level, which does not prevent database is locked from another writer.

4. BEGIN IMMEDIATE and lock upgrades

A deferred transaction starts as a reader and upgrades on the first write. If another writer got there first, the upgrade fails immediately with SQLITE_BUSY regardless of the busy timeout, because waiting could deadlock.

python
conn = sqlite3.connect("app.db", timeout=15.0, isolation_level=None) # manual control conn.execute("BEGIN IMMEDIATE") # take the write lock up front try: conn.execute("INSERT INTO jobs (state) VALUES ('queued')") conn.commit() except Exception: conn.rollback() raise

With isolation_level=None Python sends no implicit BEGIN, so every transaction is explicit. Take the write lock at the start of any read-modify-write sequence; it converts a late failure into an early, retryable wait. Pattern-matching queries in the SQL formatter helps confirm the statement order when a sequence spans several functions.

5. Network filesystems and containers

SQLite locking relies on fcntl or flock semantics that NFS, SMB and some overlay mounts do not implement consistently. The result is database is locked with no competing writer, or a database that corrupts after a network hiccup. Keep the file on a local volume, and in Docker mount a named volume rather than a bind mount on a network share. Two containers writing the same file on the same host is supported by POSIX locks but fragile; one writer container is a better design.

6. Retry policy and what to log

python
import random, sqlite3, time def with_retry(fn, attempts=5): for i in range(attempts): try: return fn() except sqlite3.OperationalError as exc: if "locked" not in str(exc) or i == attempts - 1: raise time.sleep((2 ** i) * 0.05 + random.random() * 0.05)

Retry only the busy errors, with jitter, and only outside the transaction that failed. A retry inside an open transaction re-runs statements that may already have applied. Log the operation, the wait time and the number of attempts: a rising retry rate is the signal to move writes to a queue long before users notice. Exports of the affected table are easier to inspect with the CSV to JSON converter than through ad-hoc queries.

Common Compilation/Runtime Mistakes & Version Gotchas

Raising the timeout to a minute. It converts a fast failure into a slow one and hides the design problem. Fix transaction length first, then tune.

Catching OperationalError broadly. The same class covers syntax errors, missing tables and disk I/O problems. Match "locked" in the message, or check sqlite3.sqlite_errorcode on 3.11 and later.

Holding a transaction across an HTTP call. The lock lives for the whole network round trip. Read, release, call, then write in a new short transaction.

Setting WAL on a read-only or network volume. PRAGMA journal_mode=WAL returns the mode actually applied; check the returned value instead of assuming it took effect.

Sharing one connection across a thread pool. The guard is there for a reason. Use a per-thread connection or a single writer thread with a queue.

Version notes. Python 3.12 added sqlite3.Connection.autocommit and deprecated the implicit-transaction behaviour of isolation_level; code that relies on the legacy mode should pin behaviour explicitly. Python 3.11 changed sqlite3.threadsafety to report 3 for serialized builds, which does not make concurrent writes safe. SQLite 3.35 added RETURNING, which lets an insert return its row without a second read and shortens write transactions.

Reference material: sqlite3 module and Write-ahead logging.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.