This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-sqlite-wal2-mutex-cluster-isolation

Bun 1.2 SQLite WAL2 Mutex Isolation and Descriptor Allocation in Cluster Workers

Enforces non-blocking concurrent reader execution and prevents file descriptor pool exhaustion in Bun 1.2 cluster worker topologies executing SQLite write-intensive operations. Mandates strict WAL2 pragma configuration alongside centralized cross-worker mutex delegation to eliminate busy-lock timeouts and cascading fd starvation across multithreaded edge runtimes.

Prohibited Anti-Pattern: Direct Multi-Worker Concurrent SQLite Mutations Causing WAL Contention, SQLITE_BUSY Cascades, and FD Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 SQLite WAL2 Mutex Isolation and Descriptor Allocation in Cluster Workers - Enforces non-blocking concurrent reader execution and prevents file descriptor pool exhaustion in Bun 1.2 cluster worker topologies executing SQLite write-intensive operations. Mandates strict WAL2 pragma configuration alongside centralized cross-worker mutex delegation to eliminate busy-lock timeouts and cascading fd starvation across multithreaded edge runtimes.
globs: src/**/*.{ts,js,mjs}, workers/**/*.{ts,js,mjs}, lib/db/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal2-mutex-cluster-isolation"
---

# Bun 1.2 SQLite WAL2 Mutex Isolation and Descriptor Allocation in Cluster Workers

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Direct Multi-Worker Concurrent SQLite Mutations Causing WAL Contention, SQLITE_BUSY Cascades, and FD Leaks

## System Constraints
You are a Principal Systems Architect enforcing Bun 1.2 SQLite WAL2 Mutex Isolation and File Descriptor Safeguards across clustered edge runtimes. You mandate isolated single-writer processes or inter-worker transaction queues, explicit WAL2 journal configurations, explicit checkpoint management, and pooled read-only instances to guarantee lock-free reader throughput without descriptor exhaustion.

## Strict Guidelines
- Engineers MUST ALWAYS isolate SQLite write mutations to a single designated worker or execute writes through a synchronized queue/mutex coordinator to eliminate SQLITE_BUSY contention across cluster forks.
- Engineers MUST ALWAYS initialize Bun Database instances with `readOnly: true` in query-only edge cluster worker threads to bypass write lock acquisition and reduce file lock overhead.
- Engineers MUST configure SQLite pragmas: `PRAGMA journal_mode = WAL2;`, `PRAGMA synchronous = NORMAL;`, and `PRAGMA busy_timeout = 5000;` on boot before executing any transactions.
- Engineers MUST NOT allow multiple Bun cluster worker processes to execute uncoordinated concurrent `BEGIN IMMEDIATE` or `BEGIN EXCLUSIVE` transactions against the same database file.
- Code MUST close prepared statements and database instances explicitly during worker lifecycle teardown to prevent unlinked file descriptor leaks across process reloads.
- Services MUST execute periodic passive checkpoints via `PRAGMA wal_checkpoint(PASSIVE);` exclusively on the primary coordinator node to avoid starving active edge readers during high-write spikes.

## Bad vs Good Implementations
### Uncoordinated Multi-Worker Write Instantiation vs. Mutex-Isolated Single-Writer IPC Coordinator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly writing to the SQLite database from every cluster child process with default rollback journal or standard unconfigured WAL triggers intense lock contention, recurrent SQLITE_BUSY exceptions, and unbounded file descriptor consumption due to concurrent uncheckpointed log growth.
```typescript
import { Database } from 'bun:sqlite';
import cluster from 'node:cluster';

// ANTI-PATTERN: Direct multi-process write instantiation without mutex isolation or WAL2 pragmas
const db = new Database('production.db');

export function recordEvent(data: Record<string, unknown>) {
  // Triggers SQLITE_BUSY under high load and starves worker fd pools
  const stmt = db.prepare('INSERT INTO events (payload, created_at) VALUES (?, ?)');
  stmt.run(JSON.stringify(data), Date.now());
}
```

#### Production Standard (Correct)
> **Standard**: Isolates write operations to the cluster primary process, eliminating multi-process lock contention and SQLITE_BUSY crashes. Clustered workers connect using read-only handles with WAL2 enabled, preventing descriptor starvation and ensuring continuous read throughput even during massive write spikes.
```typescript
import { Database } from 'bun:sqlite';
import cluster from 'node:cluster';

const DB_PATH = 'production.db';

if (cluster.isPrimary) {
  const primaryDb = new Database(DB_PATH, { create: true });
  // WAL2 enables non-blocking checkpointing across two alternate log files
  primaryDb.exec(`
    PRAGMA journal_mode = WAL2;
    PRAGMA synchronous = NORMAL;
    PRAGMA busy_timeout = 5000;
    PRAGMA cache_size = -64000;
  `);

  // Primary orchestrates writes sequentially via IPC to prevent contention
  const insertStmt = primaryDb.prepare('INSERT INTO events (payload, created_at) VALUES (?, ?)');
  
  cluster.on('message', (worker, message) => {
    if (message?.type === 'WRITE_EVENT') {
      try {
        primaryDb.transaction(() => {
          insertStmt.run(JSON.stringify(message.data), Date.now());
        })();
        worker.send({ id: message.id, success: true });
      } catch (err: unknown) {
        const error = err instanceof Error ? err.message : String(err);
        worker.send({ id: message.id, success: false, error });
      }
    }
  });
} else {
  // Worker threads instantiate read-only handles to prevent descriptor starvation & locks
  const readDb = new Database(DB_PATH, { readonly: true });
  readDb.exec('PRAGMA busy_timeout = 5000;');

  export function readEvents(limit: number): unknown[] {
    const query = readDb.prepare('SELECT * FROM events ORDER BY id DESC LIMIT ?');
    return query.all(limit);
  }

  export function dispatchWrite(data: Record<string, unknown>): Promise<void> {
    return new Promise((resolve, reject) => {
      const id = crypto.randomUUID();
      const listener = (msg: { id: string; success: boolean; error?: string }) => {
        if (msg?.id === id) {
          process.removeListener('message', listener);
          msg.success ? resolve() : reject(new Error(msg.error));
        }
      };
      process.on('message', listener);
      process.send!({ type: 'WRITE_EVENT', id, data });
    });
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 SQLite WAL2 Mutex Isolation and Descriptor Allocation in Cluster Workers

Bun 1.2 SQLite WAL2 Mutex Isolation and Descriptor Allocation in Cluster Workers defines an industrial-grade behavioral standard for backend engineering. Enforces non-blocking concurrent reader execution and prevents file descriptor pool exhaustion in Bun 1.2 cluster worker topologies executing SQLite write-intensive operations. Mandates strict WAL2 pragma configuration alongside centralized cross-worker mutex delegation to eliminate busy-lock timeouts and cascading fd starvation across multithreaded edge runtimes. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Direct Multi-Worker Concurrent SQLite Mutations Causing WAL Contention, SQLITE_BUSY Cascades, and FD Leaks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDirect Multi-Worker Concurrent SQLite Mutations Causing WAL Contention, SQLITE_BUSY Cascades, and FD LeaksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS isolate SQLite write mutations to a single designated worker or execute writes through a synchronized queue/mutex coordinator to eliminate SQLITE_BUSY contention across cluster forks.

Engineers MUST ALWAYS isolate SQLite write mutations to a single designated worker or execute writes through a synchronized queue/mutex coordinator to eliminate SQLITE_BUSY contention across cluster forks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS initialize Bun Database instances with `readOnly

Engineers MUST ALWAYS initialize Bun Database instances with `readOnly: true` in query-only edge cluster worker threads to bypass write lock acquisition and reduce file lock overhead.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST configure SQLite pragmas

Engineers MUST configure SQLite pragmas: `PRAGMA journal_mode = WAL2;`, `PRAGMA synchronous = NORMAL;`, and `PRAGMA busy_timeout = 5000;` on boot before executing any transactions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST NOT allow multiple Bun cluster worker processes to execute uncoordinated concurrent `BEGIN IMMEDIATE` or `BEGIN EXCLUSIVE` transactions against the same database file.

Engineers MUST NOT allow multiple Bun cluster worker processes to execute uncoordinated concurrent `BEGIN IMMEDIATE` or `BEGIN EXCLUSIVE` transactions against the same database file.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Code MUST close prepared statements and database instances explicitly during worker lifecycle teardown to prevent unlinked file descriptor leaks across process reloads.

Code MUST close prepared statements and database instances explicitly during worker lifecycle teardown to prevent unlinked file descriptor leaks across process reloads.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Services MUST execute periodic passive checkpoints via `PRAGMA wal_checkpoint(PASSIVE)

Services MUST execute periodic passive checkpoints via `PRAGMA wal_checkpoint(PASSIVE);` exclusively on the primary coordinator node to avoid starving active edge readers during high-write spikes.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Bun 1.2 SQLite WAL2 Mutex Isolation and Descriptor Allocation in Cluster Workers critical for AI coding assistants?

Enforces non-blocking concurrent reader execution and prevents file descriptor pool exhaustion in Bun 1.2 cluster worker topologies executing SQLite write-intensive operations. Mandates strict WAL2 pragma configuration alongside centralized cross-worker mutex delegation to eliminate busy-lock timeouts and cascading fd starvation across multithreaded edge runtimes. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Direct Multi-Worker Concurrent SQLite Mutations Causing WAL Contention, SQLITE_BUSY Cascades, and FD Leaks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Bun