Skip to content

Lesson 6 of 9 · 23m

Concurrency Without Folklore: Busy Timeouts, Snapshots, and Writer Discipline

How to design application concurrency around one-writer semantics, when SQLITE_BUSY is normal backpressure, and the patterns that prevent lock storms.

The worst SQLite concurrency advice is 'just use WAL.' WAL helps, but production behavior comes from transaction shape: how long writes stay open, whether reads pin snapshots, and whether the application understands SQLITE_BUSY as contention rather than corruption.

busy_timeout is the minimum viable setting

PRAGMA busy_timeout = 5000;

This tells SQLite to wait up to five seconds when a lock is unavailable. It is not a queueing system and it is not a deadlock detector; it converts instant failure into bounded waiting. For embedded applications and moderate web workloads, it prevents most transient lock errors. Verify it on the same connection you use because the setting is connection-local.

Keep write transactions tiny

Bad:

BEGIN IMMEDIATE
read remote HTTP response
transform 100 MB payload
write rows
COMMIT

Good:

fetch remote HTTP response
transform payload outside transaction
BEGIN IMMEDIATE
write rows
COMMIT

Anything inside the write transaction extends the writer-critical section. Network calls, file compression, user prompts, crypto, and sleeps do not belong there. This one rule fixes more lock incidents than any pragma.

Use one writer lane at the application layer

Because SQLite allows one writer at a time, make that architecture explicit: route writes through a single worker, queue, actor, or serialized task lane even if many threads handle reads.

HTTP handlers -- read-only queries --> sqlite connections
HTTP handlers -- write jobs ---------> writer queue -> one writer connection

This does not remove database locking, but it prevents your own process from competing with itself in unpredictable bursts. It also centralizes retry, metrics, and migration execution.

Snapshot reads and long reports

WAL readers pin WAL frames. A five-minute CSV export can prevent checkpoint completion and grow the WAL file. Export in smaller chunks with fresh snapshots, copy the database and export offline, or use a replicated read copy. Do not kill connections blindly unless you can identify the exact process and transaction.

Field notes

  • database is locked during normal operation often means backpressure worked as designed; repeated occurrences are a queueing problem.
  • Connection pools sized for network databases can hurt SQLite: 64 concurrent application writers do not create 64 database writers.
  • Close cursors and transactions deterministically. Python with sqlite3.connect(...) manages transactions, not connection lifetime.
  • Measure p50/p95 lock wait separately from query execution time; users experience the sum, not the SQL alone.

Was this lesson helpful?

Sign in to rate