This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-sqlite-wal-concurrency-invariant

Bun 1.2 Clustered SQLite WAL Read-Replica Affinity & Truncation Barrier Standard

Enforces strict process-level separation between solitary write-coordinator threads and read-replica worker pools when leveraging bun:sqlite under high concurrency. Prevents SQLite busy timeouts and unconstrained WAL log explosion by mandating explicit query-only PRAGMAs on read threads alongside deterministic checkpoint barriers via the primary engine thread.

Prohibited Anti-Pattern: Unpartitioned Multi-Threaded Read/Write Contention Leading to SQLITE_BUSY Starvation and Unbounded WAL Expansion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Clustered SQLite WAL Read-Replica Affinity & Truncation Barrier Standard - Enforces strict process-level separation between solitary write-coordinator threads and read-replica worker pools when leveraging bun:sqlite under high concurrency. Prevents SQLite busy timeouts and unconstrained WAL log explosion by mandating explicit query-only PRAGMAs on read threads alongside deterministic checkpoint barriers via the primary engine thread.
globs: src/**/*.{ts,tsx}, workers/**/*.{ts,tsx}, lib/db/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-concurrency-invariant"
---

# Bun 1.2 Clustered SQLite WAL Read-Replica Affinity & Truncation Barrier Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unpartitioned Multi-Threaded Read/Write Contention Leading to SQLITE_BUSY Starvation and Unbounded WAL Expansion

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Clustered Worker SQLite WAL Concurrency Invariant. You must guarantee that clustered engine workers maintain strict connection affinity: writes are dispatched exclusively through an isolated primary writer with a dedicated queue, worker threads open read-only database connections with query_only=ON and synchronous=NORMAL, and periodic PRAGMA wal_checkpoint(PASSIVE/RESTART) operations execute under bounded reader pressure to prevent write-lock starvation and unconstrained WAL file growth.

## Strict Guidelines
- Engineers MUST ALWAYS initialize SQLite connections in worker threads with `readonly: true` and execute `PRAGMA query_only = ON;` immediately upon worker boot.
- Engineers MUST NOT allow distributed clustered workers to instantiate read-write handles against shared WAL database files.
- Services MUST route all write and mutation intents to an isolated primary write coordinator via IPC message channels or an in-memory queue.
- The primary writer MUST configure `PRAGMA busy_timeout = 5000;` and execute periodic `PRAGMA wal_checkpoint(TRUNCATE);` or `PRAGMA wal_checkpoint(PASSIVE);` during reader quiescence.
- Workers NEVER execute direct `PRAGMA wal_checkpoint` or DDL statements independently of the write coordinator.

## Bad vs Good Implementations
### Clustered Worker SQLite Connection Initialization and Write Delegation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Opening read-write database connections across multiple clustered Bun workers causes multi-process lock contention on SQLite's single-writer lock. Uncoordinated writes induce frequent SQLITE_BUSY errors and block the WAL from checkpointing properly.
```typescript
import { Database } from 'bun:sqlite';

// ANTI-PATTERN: Direct read-write connection inside a clustered worker thread
export class WorkerDatabase {
  private db: Database;

  constructor(path: string) {
    // Opens read-write by default across multiple workers, causing lock contention
    this.db = new Database(path);
    this.db.exec('PRAGMA journal_mode = WAL;');
  }

  public mutate(userId: string, balance: number) {
    // Concurrent transactions across clustered threads result in SQLITE_BUSY
    const query = this.db.prepare('UPDATE accounts SET balance = ? WHERE id = ?');
    return query.run(balance, userId);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Configures workers with strict read-only connections and explicit query_only PRAGMA, eliminating write-lock acquisition attempts within the worker pool and delegating write requests to a designated coordinator thread.
```typescript
import { Database } from 'bun:sqlite';

// PRODUCTION INVARIANT: Read-replica worker with strict query_only isolation
export class WorkerReplicaDatabase {
  private readonly db: Database;

  constructor(databasePath: string) {
    this.db = new Database(databasePath, { readonly: true });
    // Enforce read-only semantics at the SQLite virtual machine level
    this.db.exec('PRAGMA query_only = ON;');
    this.db.exec('PRAGMA busy_timeout = 3000;');
  }

  public getAccount(userId: string) {
    const stmt = this.db.prepare('SELECT id, balance FROM accounts WHERE id = ?');
    return stmt.get(userId);
  }

  public requestMutation(userId: string, balance: number): Promise<void> {
    // Delegate write operations exclusively to the primary writer process via IPC
    return new Promise((resolve, reject) => {
      const correlationId = crypto.randomUUID();
      process.send?.({ type: 'DB_WRITE', correlationId, payload: { userId, balance } });
      // In production, listen on correlationId channel for completion confirmation
      resolve();
    });
  }
}
```

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 Clustered SQLite WAL Read-Replica Affinity & Truncation Barrier Standard

Bun 1.2 Clustered SQLite WAL Read-Replica Affinity & Truncation Barrier Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict process-level separation between solitary write-coordinator threads and read-replica worker pools when leveraging bun:sqlite under high concurrency. Prevents SQLite busy timeouts and unconstrained WAL log explosion by mandating explicit query-only PRAGMAs on read threads alongside deterministic checkpoint barriers via the primary engine thread. 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: Unpartitioned Multi-Threaded Read/Write Contention Leading to SQLITE_BUSY Starvation and Unbounded WAL Expansion 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 DriftUnpartitioned Multi-Threaded Read/Write Contention Leading to SQLITE_BUSY Starvation and Unbounded WAL ExpansionCritical
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 initialize SQLite connections in worker threads with `readonly

Engineers MUST ALWAYS initialize SQLite connections in worker threads with `readonly: true` and execute `PRAGMA query_only = ON;` immediately upon worker boot.

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 NOT allow distributed clustered workers to instantiate read-write handles against shared WAL database files.

Engineers MUST NOT allow distributed clustered workers to instantiate read-write handles against shared WAL database files.

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

Services MUST route all write and mutation intents to an isolated primary write coordinator via IPC message channels or an in-memory queue.

Services MUST route all write and mutation intents to an isolated primary write coordinator via IPC message channels or an in-memory queue.

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

The primary writer MUST configure `PRAGMA busy_timeout = 5000

The primary writer MUST configure `PRAGMA busy_timeout = 5000;` and execute periodic `PRAGMA wal_checkpoint(TRUNCATE);` or `PRAGMA wal_checkpoint(PASSIVE);` during reader quiescence.

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

Workers NEVER execute direct `PRAGMA wal_checkpoint` or DDL statements independently of the write coordinator.

Workers NEVER execute direct `PRAGMA wal_checkpoint` or DDL statements independently of the write coordinator.

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 Clustered SQLite WAL Read-Replica Affinity & Truncation Barrier Standard critical for AI coding assistants?

Enforces strict process-level separation between solitary write-coordinator threads and read-replica worker pools when leveraging bun:sqlite under high concurrency. Prevents SQLite busy timeouts and unconstrained WAL log explosion by mandating explicit query-only PRAGMAs on read threads alongside deterministic checkpoint barriers via the primary engine thread. 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 (Unpartitioned Multi-Threaded Read/Write Contention Leading to SQLITE_BUSY Starvation and Unbounded WAL Expansion) 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