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

Bun 1.2 Worker Thread SQLite WAL Affinity and Concurrency Guardrail

Enforces strict database connection isolation, WAL (Write-Ahead Logging) configuration, and single-writer thread affinity across concurrent native Bun worker threads. Prevents SQLITE_BUSY lock starvation, database corruption, and shared-memory descriptor desynchronization caused by uncoordinated concurrent write transactions.

Prohibited Anti-Pattern: Uncoordinated Multi-Threaded Read-Write SQLite Connections Without WAL Affinity or Busy Timeouts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker Thread SQLite WAL Affinity and Concurrency Guardrail - Enforces strict database connection isolation, WAL (Write-Ahead Logging) configuration, and single-writer thread affinity across concurrent native Bun worker threads. Prevents SQLITE_BUSY lock starvation, database corruption, and shared-memory descriptor desynchronization caused by uncoordinated concurrent write transactions.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-worker-wal-affinity-standard"
---

# Bun 1.2 Worker Thread SQLite WAL Affinity and Concurrency Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated Multi-Threaded Read-Write SQLite Connections Without WAL Affinity or Busy Timeouts

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Worker Thread SQLite WAL Affinity Standard. Native Bun worker threads execute in separate native OS threads. Sharing open SQLite file handles, opening unconfigured read-write connections across threads, or omitting WAL mode and busy timeouts causes SQLite locking starvation (SQLITE_BUSY) and memory-mapped file descriptor corruption. Mandate dedicated single-writer affinity or isolated read-only worker connections configured with PRAGMA journal_mode = WAL.

## Strict Guidelines
- Engineers MUST ALWAYS enable Write-Ahead Logging (`PRAGMA journal_mode = WAL;`) and configure a non-zero busy timeout (`PRAGMA busy_timeout = 5000;`) on every SQLite connection.
- Engineers MUST NOT initialize read-write `Database` instances in multiple concurrent worker threads; write transactions MUST be isolated to a single dedicated writer thread or orchestrated through message passing.
- Worker threads executing read-only queries MUST initialize the SQLite connection using the `{ readonly: true }` option.
- Services MUST ensure that `PRAGMA synchronous = NORMAL;` is configured in WAL mode to balance durability with non-blocking disk I/O.
- Components NEVER share raw `Database` instances or internal statement pointers across worker boundaries via global state or serialization attempts.

## Bad vs Good Implementations
### Multi-Worker SQLite Read-Write Contention vs WAL Single-Writer Affinity

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default Bun SQLite instances use journal_mode = DELETE without busy_timeout. When spawned in multiple Bun workers, simultaneous write operations attempt to obtain exclusive locks, triggering immediate SQLITE_BUSY errors, lock starvation, and potential shared memory index (.shm) corruption.
```typescript
import { Database } from 'bun:sqlite';

// ANTI-PATTERN: Multiple native workers instantiate default read-write databases
// Default journal_mode (DELETE) locks the entire database file during writes.
// Omitting busy_timeout causes immediate SQLITE_BUSY exceptions under concurrency.
const db = new Database('production.db');

export function recordEvent(userId: string, payload: string): void {
  // Multiple worker threads running this concurrent write will crash or block starvation
  db.run('INSERT INTO events (user_id, payload) VALUES (?, ?)', [userId, payload]);
}
```

#### Production Standard (Correct)
> **Standard**: By explicitly configuring WAL mode, busy timeout, and enforcing read-only constraints on reader workers, SQLite supports concurrent non-blocking readers alongside an isolated single-writer thread, eliminating SQLITE_BUSY lock collisions and file corruption.
```typescript
import { Database } from 'bun:sqlite';

export interface WorkerDbConfig {
  isWriterThread?: boolean;
}

// PRODUCTION FIX: Explicit connection affinity, WAL mode, and busy timeout configuration
export function initializeWorkerDatabase(config: WorkerDbConfig = {}): Database {
  const isWriter = config.isWriterThread ?? false;

  const db = new Database('production.db', {
    readonly: !isWriter,
    create: isWriter
  });

  // Mandate WAL mode for multi-threaded read/write coexistence
  db.run('PRAGMA journal_mode = WAL;');
  // Non-blocking timeout allows SQLite to retry before throwing SQLITE_BUSY
  db.run('PRAGMA busy_timeout = 5000;');
  // Safe durability optimization for WAL mode
  db.run('PRAGMA synchronous = NORMAL;');

  return db;
}

// Usage in Worker thread:
// - Reader workers call: const db = initializeWorkerDatabase({ isWriterThread: false });
// - Dedicated writer worker calls: const db = initializeWorkerDatabase({ isWriterThread: true });
```

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 Worker Thread SQLite WAL Affinity and Concurrency Guardrail

Bun 1.2 Worker Thread SQLite WAL Affinity and Concurrency Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict database connection isolation, WAL (Write-Ahead Logging) configuration, and single-writer thread affinity across concurrent native Bun worker threads. Prevents SQLITE_BUSY lock starvation, database corruption, and shared-memory descriptor desynchronization caused by uncoordinated concurrent write transactions. 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: Uncoordinated Multi-Threaded Read-Write SQLite Connections Without WAL Affinity or Busy Timeouts 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 DriftUncoordinated Multi-Threaded Read-Write SQLite Connections Without WAL Affinity or Busy TimeoutsCritical
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 enable Write-Ahead Logging (`PRAGMA journal_mode = WAL

Engineers MUST ALWAYS enable Write-Ahead Logging (`PRAGMA journal_mode = WAL;`) and configure a non-zero busy timeout (`PRAGMA busy_timeout = 5000;`) on every SQLite connection.

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 initialize read-write `Database` instances in multiple concurrent worker threads

Engineers MUST NOT initialize read-write `Database` instances in multiple concurrent worker threads; write transactions MUST be isolated to a single dedicated writer thread or orchestrated through message passing.

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

Worker threads executing read-only queries MUST initialize the SQLite connection using the `{ readonly

Worker threads executing read-only queries MUST initialize the SQLite connection using the `{ readonly: true }` option.

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

Services MUST ensure that `PRAGMA synchronous = NORMAL

Services MUST ensure that `PRAGMA synchronous = NORMAL;` is configured in WAL mode to balance durability with non-blocking disk I/O.

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

Components NEVER share raw `Database` instances or internal statement pointers across worker boundaries via global state or serialization attempts.

Components NEVER share raw `Database` instances or internal statement pointers across worker boundaries via global state or serialization attempts.

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 Worker Thread SQLite WAL Affinity and Concurrency Guardrail critical for AI coding assistants?

Enforces strict database connection isolation, WAL (Write-Ahead Logging) configuration, and single-writer thread affinity across concurrent native Bun worker threads. Prevents SQLITE_BUSY lock starvation, database corruption, and shared-memory descriptor desynchronization caused by uncoordinated concurrent write transactions. 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 (Uncoordinated Multi-Threaded Read-Write SQLite Connections Without WAL Affinity or Busy Timeouts) 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