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

Bun 1.2 Native SQLite WAL Isolation and Multi-Threaded Concurrency Guardrail

Mandates write-ahead logging (WAL), synchronous normal modes, tuned busy timeouts, and immediate transaction locking for Bun 1.2 native bun:sqlite multiplexing across clustered workers. Eliminates SQLITE_BUSY contention deadlocks, connection exhaustion, and dirty reads during concurrent read/write transactions across OS threads.

Prohibited Anti-Pattern: Ad-Hoc Unsynchronized bun:sqlite Handles with Deferred Transactions across Bun Workers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native SQLite WAL Isolation and Multi-Threaded Concurrency Guardrail - Mandates write-ahead logging (WAL), synchronous normal modes, tuned busy timeouts, and immediate transaction locking for Bun 1.2 native bun:sqlite multiplexing across clustered workers. Eliminates SQLITE_BUSY contention deadlocks, connection exhaustion, and dirty reads during concurrent read/write transactions across OS threads.
globs: src/**/*.{ts,js}, workers/**/*.{ts,js}, lib/db/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-concurrency-isolation-production-standard"
---

# Bun 1.2 Native SQLite WAL Isolation and Multi-Threaded Concurrency Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ad-Hoc Unsynchronized bun:sqlite Handles with Deferred Transactions across Bun Workers

## System Constraints
You are a Principal Software Architect enforcing production safety for Bun 1.2 native SQLite (bun:sqlite). You must enforce strict Write-Ahead Logging (WAL) configuration, appropriate busy timeouts, and immediate transaction semantics across multi-threaded and worker environments. Reject ad-hoc unpooled connection instances, deferred write transactions that risk lock-upgrade deadlocks, and unindexed concurrent queries.

## Strict Guidelines
- Engineers MUST ALWAYS configure `PRAGMA journal_mode = WAL;` and `PRAGMA synchronous = NORMAL;` immediately upon opening any bun:sqlite database handle intended for multi-threaded access.
- Engineers MUST ALWAYS set `PRAGMA busy_timeout = 5000;` (or higher depending on SLA) to allow Bun clustered workers to wait for locked WAL frames rather than instantly throwing SQLITE_BUSY.
- Engineers MUST ALWAYS use `BEGIN IMMEDIATE` or Bun's `.transaction()` with explicit immediate write isolation when performing mutations to avoid deadlock during write-lock escalation.
- Engineers MUST NOT instantiate new `new Database(path)` instances per HTTP request; database handles MUST be managed as persistent singletons per worker thread.
- Services MUST execute `PRAGMA wal_autocheckpoint` management on designated coordinator processes to avoid checkpoint starvation during sustained write bursts.
- Workers NEVER execute destructive operations like `VACUUM` or explicit DDL alterations concurrently while active reader workers hold open transaction snapshots.

## Bad vs Good Implementations
### Configuring bun:sqlite for Thread-Safe WAL Concurrency vs Ad-Hoc Deferred Locking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Opening database handles per request bypasses Bun's native connection caching and creates race conditions across OS threads. Default DELETE journal mode blocks concurrent readers during writes, and deferred transaction start causes upgrade deadlocks under high-frequency writes.
```typescript
import { Database } from 'bun:sqlite';

// ANTI-PATTERN: Connection opened per request without WAL or busy_timeout configuration
export async function handleWriteRequest(payload: { id: string; data: string }) {
  const db = new Database('app.db'); // Opens database handle with default DELETE journal mode and 0ms busy timeout
  
  // Deferred transaction: SQLite starts in read mode and tries to upgrade to write lock
  // This throws 'SQLITE_BUSY: database is locked' under concurrent Bun worker load
  db.run('BEGIN TRANSACTION');
  try {
    db.query('INSERT INTO audit_events (id, data) VALUES (?1, ?2)').run(payload.id, payload.data);
    db.run('COMMIT');
  } catch (err) {
    db.run('ROLLBACK');
    throw err;
  } finally {
    db.close();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Initializes SQLite in WAL mode with synchronous=NORMAL and a 5000ms busy timeout. Uses an application-scoped singleton handle with prepared statements and Bun's native immediate transaction wrapper, guaranteeing starvation-free shared memory isolation across clustered workers.
```typescript
import { Database } from 'bun:sqlite';

// PRODUCTION INVARIANT: Persistent per-worker singleton configured with WAL and busy timeout
class DatabaseClient {
  private static instance: Database | null = null;

  public static getInstance(): Database {
    if (!DatabaseClient.instance) {
      const db = new Database('app.db', { create: true });
      
      // Enforce WAL mode, normal sync for fast durability, and 5s busy wait retry
      db.exec(`
        PRAGMA journal_mode = WAL;
        PRAGMA synchronous = NORMAL;
        PRAGMA busy_timeout = 5000;
        PRAGMA foreign_keys = ON;
      `);
      
      DatabaseClient.instance = db;
    }
    return DatabaseClient.instance;
  }
}

export async function handleWriteRequest(payload: { id: string; data: string }): Promise<void> {
  const db = DatabaseClient.getInstance();
  const insertStmt = db.prepare('INSERT INTO audit_events (id, data) VALUES (?1, ?2)');

  // db.transaction() in bun:sqlite defaults to BEGIN IMMEDIATE semantics, preventing lock upgrade races
  const insertTransaction = db.transaction((id: string, data: string) => {
    insertStmt.run(id, data);
  });

  insertTransaction(payload.id, payload.data);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Native SQLite WAL Isolation and Multi-Threaded Concurrency Guardrail

Bun 1.2 Native SQLite WAL Isolation and Multi-Threaded Concurrency Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates write-ahead logging (WAL), synchronous normal modes, tuned busy timeouts, and immediate transaction locking for Bun 1.2 native bun:sqlite multiplexing across clustered workers. Eliminates SQLITE_BUSY contention deadlocks, connection exhaustion, and dirty reads during concurrent read/write transactions across OS threads. 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: Ad-Hoc Unsynchronized bun:sqlite Handles with Deferred Transactions across Bun Workers 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 DriftAd-Hoc Unsynchronized bun:sqlite Handles with Deferred Transactions across Bun WorkersCritical
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 configure `PRAGMA journal_mode = WAL

Engineers MUST ALWAYS configure `PRAGMA journal_mode = WAL;` and `PRAGMA synchronous = NORMAL;` immediately upon opening any bun:sqlite database handle intended for multi-threaded access.

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 set `PRAGMA busy_timeout = 5000

Engineers MUST ALWAYS set `PRAGMA busy_timeout = 5000;` (or higher depending on SLA) to allow Bun clustered workers to wait for locked WAL frames rather than instantly throwing SQLITE_BUSY.

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 ALWAYS use `BEGIN IMMEDIATE` or Bun's `.transaction()` with explicit immediate write isolation when performing mutations to avoid deadlock during write-lock escalation.

Engineers MUST ALWAYS use `BEGIN IMMEDIATE` or Bun's `.transaction()` with explicit immediate write isolation when performing mutations to avoid deadlock during write-lock escalation.

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 instantiate new `new Database(path)` instances per HTTP request

Engineers MUST NOT instantiate new `new Database(path)` instances per HTTP request; database handles MUST be managed as persistent singletons per worker thread.

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

Services MUST execute `PRAGMA wal_autocheckpoint` management on designated coordinator processes to avoid checkpoint starvation during sustained write bursts.

Services MUST execute `PRAGMA wal_autocheckpoint` management on designated coordinator processes to avoid checkpoint starvation during sustained write bursts.

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

Workers NEVER execute destructive operations like `VACUUM` or explicit DDL alterations concurrently while active reader workers hold open transaction snapshots.

Workers NEVER execute destructive operations like `VACUUM` or explicit DDL alterations concurrently while active reader workers hold open transaction snapshots.

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 Native SQLite WAL Isolation and Multi-Threaded Concurrency Guardrail critical for AI coding assistants?

Mandates write-ahead logging (WAL), synchronous normal modes, tuned busy timeouts, and immediate transaction locking for Bun 1.2 native bun:sqlite multiplexing across clustered workers. Eliminates SQLITE_BUSY contention deadlocks, connection exhaustion, and dirty reads during concurrent read/write transactions across OS threads. 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 (Ad-Hoc Unsynchronized bun:sqlite Handles with Deferred Transactions across Bun Workers) 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