Skip to main content
Back to Community & Earn Hub
Q&A Questiondatabases +150 pt Bounty

SQLite WAL Contention in Local AI Agent Memory: How to fix 'database is locked' under concurrent asyncio sub-agent writes?

@vikram_joshi4 days ago 1468 views

For local-first desktop AI agents, embedded SQLite is way cleaner than forcing users to install Postgres.

We enabled WAL mode at startup:

python
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA synchronous=NORMAL;")

Why It Still Crashes

When an orchestrator fans out 4 parallel sub-agents via asyncio.gather() and each sub-agent logs tool outcomes concurrently using aiosqlite:

text
sqlite3.OperationalError: database is locked

Even with timeout=5.0 on aiosqlite.connect(), two concurrent BEGIN transactions fail instantly in <1ms without even waiting for the 5-second busy timeout!

Why does SQLite ignore busy_timeout during concurrent DEFERRED transactions, and what is the rock-solid Python pattern for multi-agent SQLite writes?

1 Answers

Community Answers

@sneha_patel Accepted Answer4 days ago

You hit SQLite's famous deferred lock-upgrade deadlock:

In Python sqlite3 / aiosqlite, transactions default to BEGIN DEFERRED. When two connections both start a DEFERRED transaction as readers and then both attempt to upgrade to a write lock, SQLite cannot wait on busy_timeout—because neither connection can release its read snapshot without rolling back! So SQLite immediately aborts one connection in <1ms with database is locked.

Here are the two fixes you need together in production:


1. Always Use BEGIN IMMEDIATE + Set PRAGMA busy_timeout Per Connection

BEGIN IMMEDIATE acquires the write lock upfront at transaction start, allowing SQLite's busy_timeout to sleep and retry cleanly instead of deadlocking:

python
import aiosqlite

async def get_db_connection(db_path: str) -> aiosqlite.Connection:
    # isolation_level=None gives explicit manual transaction control
    conn = await aiosqlite.connect(db_path, isolation_level=None)
    await conn.execute("PRAGMA journal_mode=WAL;")
    await conn.execute("PRAGMA synchronous=NORMAL;")
    await conn.execute("PRAGMA busy_timeout=5000;")  # Wait up to 5s cleanly
    return conn

async def safe_write(conn: aiosqlite.Connection, sql: str, params: tuple):
    await conn.execute("BEGIN IMMEDIATE;")
    try:
        await conn.execute(sql, params)
        await conn.execute("COMMIT;")
    except Exception:
        await conn.execute("ROLLBACK;")
        raise

2. Best Practice for High-Concurrency Sub-Agents: Single-Writer asyncio.Queue

Since SQLite only allows one writer at a time anyway, funnel all writes from your 4 parallel sub-agents through one lightweight background writer coroutine while letting all 4 sub-agents read concurrently in WAL mode:

python
import asyncio

class SqliteWriteActor:
    def __init__(self, db_path: str):
        self.db_path = db_path
        self.queue: asyncio.Queue = asyncio.Queue()

    async def start(self):
        self.conn = await get_db_connection(self.db_path)
        self._task = asyncio.create_task(self._writer_loop())

    async def _writer_loop(self):
        while True:
            sql, params, future = await self.queue.get()
            try:
                await safe_write(self.conn, sql, params)
                future.set_result(True)
            except Exception as exc:
                future.set_exception(exc)
            finally:
                self.queue.task_done()

    async def execute_write(self, sql: str, params: tuple = ()):
        fut = asyncio.get_running_loop().create_future()
        await self.queue.put((sql, params, fut))
        return await fut

With BEGIN IMMEDIATE + SqliteWriteActor, 10+ concurrent sub-agents can hammer writes simultaneously with zero database is locked exceptions.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.