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

Bun Embedded SQLite WAL Mode & Transaction Synchronization Standard

Production database standard for bun:sqlite. Mandates enabling Write-Ahead Logging (PRAGMA journal_mode = WAL), busy timeouts, and using db.transaction() for atomic operations without lock starvation.

Prohibited Anti-Pattern: AI opens bun:sqlite with default rollback journals and un-isolated batch inserts, triggering SQLITE_BUSY crashes under concurrent requests.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun Embedded SQLite WAL Mode & Transaction Synchronization Standard - Production database standard for bun:sqlite. Mandates enabling Write-Ahead Logging (PRAGMA journal_mode = WAL), busy timeouts, and using db.transaction() for atomic operations without lock starvation.
globs: **/db/**/*.ts, **/database.ts, **/*sqlite*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-concurrency"
---

# Bun Embedded SQLite WAL Mode & Transaction Synchronization Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI opens bun:sqlite with default rollback journals and un-isolated batch inserts, triggering SQLITE_BUSY crashes under concurrent requests.

## System Constraints
You are a Bun High-Performance Systems Engineer using bun:sqlite. Never run embedded SQLite in default rollback journal mode. Always configure PRAGMA journal_mode = WAL, PRAGMA synchronous = NORMAL, and wrap multi-row mutations inside db.transaction().

## Strict Guidelines
- MUST execute db.run('PRAGMA journal_mode = WAL;') immediately upon creating Database instance.
- MUST set PRAGMA busy_timeout = 5000; to queue concurrent write attempts for up to 5 seconds.
- MUST wrap multi-statement mutations in const tx = db.transaction(() => { ... }) for atomic ACID guarantees.
- MUST close prepared statements (query.finalize()) or reuse cached statement singletons.

## Bad vs Good Implementations
### Configuring Bun SQLite with WAL Mode and Atomic Transactions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default rollback journal locks the entire database file per insert. Multiple concurrent web requests collide immediately with fatal database locked exceptions.
```typescript
// FATAL: Default bun:sqlite crashes on concurrent write requests
import { Database } from 'bun:sqlite';

const db = new Database('app.db');
// Un-isolated concurrent writes cause SQLITE_BUSY database is locked!
for (const item of items) {
  db.run('INSERT INTO records (data) VALUES (?)', [item]);
}
```

#### Production Standard (Correct)
> **Standard**: Enables WAL mode permitting simultaneous reads and writes, while bundling batch operations into a single filesystem commit.
```typescript
import { Database } from 'bun:sqlite';

const db = new Database('app.db', { create: true, strict: true });

// 1. Initialize concurrency pragmas
db.run('PRAGMA journal_mode = WAL;');
db.run('PRAGMA synchronous = NORMAL;');
db.run('PRAGMA busy_timeout = 5000;');

// 2. Prepare single parameterized statement
const insertStmt = db.prepare('INSERT INTO records (data) VALUES (?)');

// 3. Atomically commit batch inside compiled transaction
const insertBatch = db.transaction((records: string[]) => {
  for (const record of records) {
    insertStmt.run(record);
  }
});

insertBatch(items);
```

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 Embedded SQLite WAL Mode & Transaction Synchronization Standard

Bun Embedded SQLite WAL Mode & Transaction Synchronization Standard defines an industrial-grade behavioral standard for backend engineering. Production database standard for bun:sqlite. Mandates enabling Write-Ahead Logging (PRAGMA journal_mode = WAL), busy timeouts, and using db.transaction() for atomic operations without lock starvation. 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: AI opens bun:sqlite with default rollback journals and un-isolated batch inserts, triggering SQLITE_BUSY crashes under concurrent requests. 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 DriftAI opens bun:sqlite with default rollback journals and un-isolated batch inserts, triggering SQLITE_BUSY crashes under concurrent requests.Critical
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

MUST execute db.run('PRAGMA journal_mode = WAL

MUST execute db.run('PRAGMA journal_mode = WAL;') immediately upon creating Database instance.

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

MUST set PRAGMA busy_timeout = 5000

MUST set PRAGMA busy_timeout = 5000; to queue concurrent write attempts for up to 5 seconds.

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

MUST wrap multi-statement mutations in const tx = db.transaction(() => { ... }) for atomic ACID guarantees.

MUST wrap multi-statement mutations in const tx = db.transaction(() => { ... }) for atomic ACID guarantees.

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

MUST close prepared statements (query.finalize()) or reuse cached statement singletons.

MUST close prepared statements (query.finalize()) or reuse cached statement singletons.

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 Embedded SQLite WAL Mode & Transaction Synchronization Standard critical for AI coding assistants?

Production database standard for bun:sqlite. Mandates enabling Write-Ahead Logging (PRAGMA journal_mode = WAL), busy timeouts, and using db.transaction() for atomic operations without lock starvation. 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 (AI opens bun:sqlite with default rollback journals and un-isolated batch inserts, triggering SQLITE_BUSY crashes under concurrent requests.) 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