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.

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.
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:
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 mode | Writer blocks readers | Readers block writer | Concurrency |
|---|---|---|---|
DELETE (default) | yes, during write | yes | one operation at a time |
WAL | no | no, readers see a snapshot | one writer with many readers |
TRUNCATE or PERSIST | yes | yes | marginally faster than DELETE |
MEMORY | yes | yes | unsafe across crashes |
OFF | corrupts on crash | — | never use |
Key Comparison Table
| Cause | Symptom | Fix |
|---|---|---|
| Uncommitted write transaction | error only under concurrent writes | commit or roll back promptly |
| Shared connection across threads | sporadic, often under load | one connection per thread |
| Default journal mode | readers block the writer | PRAGMA journal_mode=WAL |
| 5-second default timeout | errors on slow queries | raise timeout and busy_timeout |
| Network filesystem | locking unreliable, hangs | keep the database on local disk |
| Long transaction around network calls | writes pile up | move I/O outside the transaction |
Python API choices that change behaviour:
| Setting | Default | Effect | Recommended |
|---|---|---|---|
timeout | 5.0 seconds | busy wait before SQLITE_BUSY | 10 to 30 for write paths |
isolation_level | "" (implicit BEGIN) | transaction opens on first DML | explicit BEGIN IMMEDIATE for writes |
check_same_thread | True | rejects cross-thread use | keep True, one connection per thread |
autocommit | not set (3.12+) | PEP 249-style control | True plus explicit transactions |
detect_types | 0 | no type conversion | unrelated to locking |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Find the transaction that is holding the lock
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:
with sqlite3.connect("app.db") as conn:
conn.execute("UPDATE jobs SET state = 'done' WHERE id = ?", (job_id,))
# committed here; an exception rolls backNote 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
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 connWAL 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
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.connOne 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.
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()
raiseWith 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
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 documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython Typer Rich Integration and Progress Bars
python typer rich integration and progress bars: Learn to integrate Rich progress bars into Typer CLI applications, covering track, Progress, dynamic.
asyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Python Watchdog Created, Modified, and Deleted Events
Handle created, modified, and deleted file events with Python's watchdog library. Covers handler methods, event objects, duplicate modification events.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.