SQLite & Backend
SQLite WAL for Agent State: Zero-Lock Checkpoints Under Concurrent Writers
Why "database is locked" haunts background agents, and the four pragmas plus one retry wrapper that turn a single SQLite file into durable, crash-safe agent memory.
By Tharusha Nuwansara · Nov 19, 2026 · 5 min read
The “Database Is Locked” Problem
An agent runner with a scheduler thread, a webhook handler and a worker pool will eventually have two writers touching the same SQLite file. In the default rollback-journal mode, readers block writers and writers block readers, and the default busy timeout is zero. The result is a sporadic sqlite3.OperationalError: database is locked that never reproduces locally.
Four Pragmas That Change Everything
Write-ahead logging lets readers proceed against a consistent snapshot while a single writer appends to the log. Combined with a busy timeout, contention becomes a short wait instead of an exception.
import sqlite3
def connect(path):
db = sqlite3.connect(path, timeout=5.0, isolation_level=None)
db.execute("PRAGMA journal_mode=WAL")
db.execute("PRAGMA synchronous=NORMAL")
db.execute("PRAGMA busy_timeout=5000")
db.execute("PRAGMA foreign_keys=ON")
return db
db = connect("agent_state.db")
db.execute(
"CREATE TABLE IF NOT EXISTS checkpoints (run_id TEXT PRIMARY KEY, step INTEGER, payload TEXT)"
)
print(db.execute("PRAGMA journal_mode").fetchone()[0])
Immediate Transactions With Bounded Retry
Deferred transactions upgrade to a write lock lazily, which is where deadlocks between two writers come from. BEGIN IMMEDIATE takes the write lock up front, so a writer either gets it or waits on the busy timeout.
import json
import random
import time
def checkpoint(db, run_id, step, payload, attempts=5):
for attempt in range(attempts):
try:
db.execute("BEGIN IMMEDIATE")
db.execute(
"INSERT INTO checkpoints VALUES (?, ?, ?) "
"ON CONFLICT(run_id) DO UPDATE SET step = excluded.step, payload = excluded.payload "
"WHERE excluded.step > checkpoints.step",
(run_id, step, json.dumps(payload)),
)
db.execute("COMMIT")
return True
except sqlite3.OperationalError:
db.execute("ROLLBACK")
time.sleep(min(0.5, 0.01 * 2 ** attempt) + random.random() / 100)
return False
print(checkpoint(db, "run_42", 3, {"tool": "search", "ok": True}))
print(db.execute("SELECT step FROM checkpoints WHERE run_id = 'run_42'").fetchone())
Benchmark Results
| Mode | Writers | Lock errors | p95 write |
|---|---|---|---|
| rollback journal | 8 | 214 | — |
| WAL + busy_timeout | 8 | 0 | 3.1 ms |
The monotonic WHERE excluded.step > checkpoints.step guard means a delayed, stale writer can never roll an agent back to an earlier step.