Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:0xK3vin MegaMemory SQLite Concurrency Hardening

From Leeroopedia
Knowledge Sources
Domains Database, Concurrency, Optimization
Last Updated 2026-10-27 14:00 GMT

Overview

Multi-layered concurrency hardening for SQLite/libsql: WAL mode, `BEGIN IMMEDIATE`, `busy_timeout=5000`, and exponential-backoff retry to safely support multiple agent processes writing to the same knowledge graph.

Description

MegaMemory is designed for multiple coding agents (or multiple MCP server instances) to write to the same `.megamemory/knowledge.db` file concurrently. SQLite has a single-writer lock model, so concurrent writes can cause `SQLITE_BUSY` errors. The codebase uses four layers of defense:

  1. WAL mode (`journal_mode = WAL`) — allows concurrent readers while one writer holds the lock
  2. `BEGIN IMMEDIATE` — acquires the write lock at transaction start rather than at first write, preventing "upgrade deadlock" where a read transaction can't upgrade to write
  3. `busy_timeout = 5000` — SQLite waits up to 5 seconds for a lock before throwing `SQLITE_BUSY`
  4. `runWithRetry` — application-level retry with exponential backoff (50ms, 100ms, 200ms) for up to 3 attempts using `Atomics.wait` for synchronous sleeping

Additionally, `runInTransaction` supports re-entrant nesting via a `_txDepth` counter, so nested transaction calls don't issue duplicate `BEGIN`/`COMMIT`.

Usage

Apply this heuristic when:

  • Multiple processes write to the same SQLite database file
  • You see `SQLITE_BUSY` or `database is locked` errors under concurrent load
  • Migrating a single-process SQLite app to multi-process use

This is always active in MegaMemory — every `KnowledgeDB` instance configures these PRAGMAs at construction time.

The Insight (Rule of Thumb)

  • Action: Configure four concurrency defenses at DB construction and transaction boundaries.
  • Values:
    • `journal_mode = WAL` — concurrent readers + single writer
    • `foreign_keys = ON` — referential integrity
    • `busy_timeout = 5000` — 5s lock wait at SQLite level
    • `synchronous = NORMAL` — safe with WAL, faster than FULL
    • `BEGIN IMMEDIATE` — acquire write lock early
    • Retry: 3 attempts, backoff = `50 * 2^attempt` ms, sync sleep via `Atomics.wait`
  • Trade-off: `BEGIN IMMEDIATE` serializes writers immediately (some wasted waits if transaction ends up being read-only), but prevents deadlocks. `synchronous = NORMAL` risks losing the last few transactions on power failure (acceptable for a knowledge graph that can be re-derived).
  • Re-entrancy: `runInTransaction` tracks `_txDepth` — nested calls reuse the outer transaction.

Reasoning

SQLite's default `journal_mode = DELETE` allows only one connection at a time (read or write). WAL mode allows unlimited concurrent readers alongside a single writer — essential when multiple MCP server instances serve different agents.

`BEGIN DEFERRED` (the default) starts a read transaction and tries to upgrade to write on the first write statement. If two connections both do this, neither can upgrade → deadlock. `BEGIN IMMEDIATE` acquires the write lock upfront, serializing writers and preventing this scenario.

Even with `busy_timeout`, a long-running transaction can exceed the 5-second window. The application-level `runWithRetry` catches remaining `SQLITE_BUSY` errors and retries with exponential backoff. Using `Atomics.wait` on a `SharedArrayBuffer` provides a true synchronous sleep without blocking the event loop on other threads.

The migration guard re-checks `user_version` after acquiring the `BEGIN IMMEDIATE` lock, in case another process already completed the migration while this process waited.

Code Evidence

PRAGMA configuration at construction from `src/db.ts:19-24`:

this.db = new Database(dbPath);
this.db.pragma("journal_mode = WAL");
this.db.pragma("foreign_keys = ON");
this.db.pragma("busy_timeout = 5000");
this.db.pragma("synchronous = NORMAL");
this.migrate();

Re-entrant transaction with `BEGIN IMMEDIATE` from `src/db.ts:180-207`:

runInTransaction<T>(fn: () => T): T {
  if (this._txDepth > 0) {
    // Already inside a transaction — just run the function
    this._txDepth++;
    try { return fn(); } finally { this._txDepth--; }
  }
  this._txDepth++;
  try {
    return this.runWithRetry(() => {
      this.db.exec("BEGIN IMMEDIATE");
      try {
        const result = fn();
        this.db.exec("COMMIT");
        return result;
      } catch (err) {
        this.db.exec("ROLLBACK");
        throw err;
      }
    });
  } finally { this._txDepth--; }
}

Exponential backoff retry from `src/db.ts:209-225`:

runWithRetry<T>(fn: () => T, maxRetries = 3): T {
  for (let attempt = 0; ; attempt++) {
    try {
      return fn();
    } catch (err: unknown) {
      const isBusy =
        err instanceof Error &&
        (err.message.includes("SQLITE_BUSY") ||
          err.message.includes("database is locked"));
      if (!isBusy || attempt >= maxRetries) throw err;
      const delayMs = 50 * Math.pow(2, attempt);
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs);
    }
  }
}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment