Most small FastAPI services start on SQLite with PRAGMA journal_mode=WAL, pass local load checks, and stay quiet for months. Then one traffic burst hits a webhook endpoint or a background worker retries twenty jobs at once, and your logs fill up with sqlite3.OperationalError: database is locked.
I ran into this exact surprise while keeping webhook deduplication and small user-state tables inside a single-node FastAPI backend for an open Telegram Mini App (https://github.com/angeldev-tech/ton-alpha-tma). Turning on WAL felt like checking the "safe for concurrency" box. It was not.
The lock upgrade bug that skips busy_timeout
Even with journal_mode=WAL and busy_timeout=5000, SQLite still allows only one writer at a time. That part is well known. The part that catches Python developers off guard is what happens when two transactions start as DEFERRED (the default in sqlite3) and both try to upgrade from a read lock to a write lock.
When connection A reads a row, then connection B reads a row, and then both try to execute an INSERT or UPDATE, SQLite cannot make connection B wait for connection A. Waiting would create a deadlock because connection B holds a shared snapshot that conflicts with A's pending write. Instead, SQLite returns SQLITE_BUSY immediately and completely ignores busy_timeout.
Starting write transactions with BEGIN IMMEDIATE fixes this. Connection B waits cleanly for the RESERVED lock up to busy_timeout instead of failing on the spot.
Reproducing the failure in 45 lines of Python
You can test the difference locally using only the Python standard library. Run this script once with use_immediate=False and once with use_immediate=True against the same temporary database file.
import sqlite3
import tempfile
import threading
from pathlib import Path
def open_conn(db_path: Path) -> sqlite3.Connection:
conn = sqlite3.connect(db_path, timeout=5.0, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")
conn.execute("PRAGMA busy_timeout=5000;")
return conn
def run_burst(use_immediate: bool, workers: int = 8, writes_per_worker: int = 40) -> int:
with tempfile.TemporaryDirectory() as tmp:
db_path = Path(tmp) / "events.db"
setup = open_conn(db_path)
setup.execute("CREATE TABLE events (id INTEGER PRIMARY KEY, worker INTEGER, n INTEGER)")
setup.close()
failures = 0
fail_lock = threading.Lock()
barrier = threading.Barrier(workers)
def worker_fn(wid: int) -> None:
nonlocal failures
conn = open_conn(db_path)
barrier.wait()
for n in range(writes_per_worker):
try:
conn.execute("BEGIN IMMEDIATE" if use_immediate else "BEGIN")
conn.execute("SELECT COUNT(*) FROM events").fetchone()
conn.execute("INSERT INTO events (worker, n) VALUES (?, ?)", (wid, n))
conn.execute("COMMIT")
except sqlite3.OperationalError:
conn.execute("ROLLBACK")
with fail_lock:
failures += 1
conn.close()
threads = [threading.Thread(target=worker_fn, args=(i,)) for i in range(workers)]
for t in threads:
t.start()
for t in threads:
t.join()
return failures
if __name__ == "__main__":
print("DEFERRED failures :", run_burst(use_immediate=False))
print("IMMEDIATE failures:", run_burst(use_immediate=True))
In a local run on my machine, DEFERRED failed on 260 of 320 writes under 8 concurrent threads even with a 5-second timeout. Switching the transaction start to BEGIN IMMEDIATE brought failures down to zero because writers serialized cleanly before reading.
The second wall is WAL checkpoint starvation
Fixing lock upgrades buys you a lot of headroom, yet WAL still has a second operational limit: long-lived read transactions block automatic checkpoints.
If an admin export, a forgotten cursor, or a slow async generator holds a read transaction open for ten minutes while webhooks keep writing, SQLite cannot truncate the -wal file. The file grows until read latency spikes or the disk fills up. Running PRAGMA wal_checkpoint(TRUNCATE) on a schedule helps only after all old readers close.
Honest tradeoffs before moving to PostgreSQL
SQLite WAL stays a strong choice when you run one application host, keep write transactions short (under a few milliseconds), never mix network calls inside an open transaction, and ship predictable backups with sqlite3 .backup or Litestream.
It stops being worth the tuning effort the moment you need two stateless app containers writing to shared state, sustained multi-writer throughput, or analytical reads alongside live writes. At that point PostgreSQL row-level locking and INSERT ... ON CONFLICT remove a whole class of lock bugs that no PRAGMA can solve.
For teams who started a Python API on SQLite WAL in production: what was the actual failure mode that finally made you migrate to Postgres, or what PRAGMA and transaction setup let you stay on SQLite longer than expected?
Top comments (1)
Max, the lock-upgrade detail is the part I had wrong: I assumed busy_timeout covered every wait, and your 260-of-320 number shows where that breaks. My webhook deduplication runs on a single writer, so I have not hit this yet. Your BEGIN IMMEDIATE rule goes into my notes before the next burst, not after. What made you stay on SQLite?