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

Bun 1.2 SQLite WAL2 Checkpoint Starvation Boundary & Disk Growth Guardrail

Prevents unbounded WAL growth and container ENOSPC failures in high-throughput Bun 1.2 microservices using SQLite WAL/WAL2 mode. Enforces strict boundary isolation between synchronous read/write transactions and asynchronous event-loop operations, eliminating reader snapshot holding that blocks WAL log recycling.

Prohibited Anti-Pattern: Suspending SQLite Transactions Across Asynchronous Event Loop Ticks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 SQLite WAL2 Checkpoint Starvation Boundary & Disk Growth Guardrail - Prevents unbounded WAL growth and container ENOSPC failures in high-throughput Bun 1.2 microservices using SQLite WAL/WAL2 mode. Enforces strict boundary isolation between synchronous read/write transactions and asynchronous event-loop operations, eliminating reader snapshot holding that blocks WAL log recycling.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal2-checkpoint-starvation-boundary"
---

# Bun 1.2 SQLite WAL2 Checkpoint Starvation Boundary & Disk Growth Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Suspending SQLite Transactions Across Asynchronous Event Loop Ticks

## System Constraints
You are a Principal Database Infrastructure Architect specializing in Bun 1.2 runtime internals and SQLite VFS behavior. You enforce zero-downtime database lifecycles by strictly segregating synchronous bun:sqlite queries from asynchronous runtime promises. Never allow transactions to remain open across async boundaries, mandate explicit busy timeouts, ensure journal_mode=WAL2 checkpoints are aggressively scheduled, and protect container disk allocations from log starvation.

## Strict Guidelines
- Engineers MUST NEVER execute asynchronous promises (e.g., `await fetch()`, timer delays, message bus dispatches) inside a `bun:sqlite` transaction context.
- Engineers MUST ALWAYS isolate SQLite read transactions to synchronous, discrete code paths that finalize iterators or read arrays prior to yielding to the Bun event loop.
- Code MUST set `PRAGMA busy_timeout = 5000;` and explicitly configure `PRAGMA synchronous = NORMAL;` alongside `PRAGMA journal_mode = WAL2;` upon database connection initialization.
- Services MUST implement a background checkpoint supervisor that periodically executes `PRAGMA wal_checkpoint(PASSIVE)` and escalates to `RESTART` or `TRUNCATE` when WAL size exceeds bounded thresholds (e.g., 64MB).
- Components NEVER execute unbounded cursor streaming (`query.iterate()`) concurrently with long network streams without chunking records into discrete synchronous snapshot batches.

## Bad vs Good Implementations
### Asynchronous Operations Inside SQLite Transaction Starving WAL Checkpoints

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding a database transaction open across `await fetch()` suspends the transaction on the Bun event loop. The active read snapshot prevents the SQLite engine from advancing WAL2 log frames and executing checkpoints. Under sustained ingestion, WAL files grow uncontrollably until the container runs out of disk space (ENOSPC).
```typescript
import { Database } from "bun:sqlite";

const db = new Database("analytics.db");
db.run("PRAGMA journal_mode = WAL2;");

export async function processAuditEvents(eventType: string) {
  // ANTI-PATTERN: Transaction open across async network calls blocks SQLite WAL recycling indefinitely
  const tx = db.transaction(async () => {
    const stmt = db.query("SELECT id, payload FROM events WHERE type = ? AND dispatched = 0");
    const rows = stmt.all(eventType) as Array<{ id: string; payload: string }>;

    for (const row of rows) {
      // Async suspension holds reader lock on WAL frame header
      await fetch("https://ingest.internal/events", {
        method: "POST",
        body: row.payload,
      });
      db.query("UPDATE events SET dispatched = 1 WHERE id = ?").run(row.id);
    }
  });

  await tx();
}
```

#### Production Standard (Correct)
> **Standard**: Read queries and write transactions are strictly synchronous and immediate. Read locks are dropped before any async I/O occurs, allowing WAL2 checkpoints to rotate frames without starvation and guaranteeing deterministic disk bounds.
```typescript
import { Database } from "bun:sqlite";

const db = new Database("analytics.db");
db.run("PRAGMA journal_mode = WAL2;");
db.run("PRAGMA busy_timeout = 5000;");
db.run("PRAGMA synchronous = NORMAL;");

interface AuditEvent {
  id: string;
  payload: string;
}

// GOOD: Read operation finishes synchronously and releases locks immediately
export function fetchPendingBatch(eventType: string, limit: number): AuditEvent[] {
  const stmt = db.query<AuditEvent, [string, number]>(
    "SELECT id, payload FROM events WHERE type = ? AND dispatched = 0 LIMIT ?"
  );
  return stmt.all(eventType, limit);
}

// GOOD: Updates executed in a tight, synchronous transaction
export function markEventsDispatched(ids: string[]): void {
  if (ids.length === 0) return;
  const updateTx = db.transaction((eventIds: string[]) => {
    const stmt = db.query("UPDATE events SET dispatched = 1 WHERE id = ?");
    for (const id of eventIds) {
      stmt.run(id);
    }
  });
  updateTx(ids);
}

export async function processAuditEventsIsolated(eventType: string): Promise<void> {
  const batch = fetchPendingBatch(eventType, 100);
  if (batch.length === 0) return;

  const successfulIds: string[] = [];
  for (const row of batch) {
    try {
      const res = await fetch("https://ingest.internal/events", {
        method: "POST",
        body: row.payload,
      });
      if (res.ok) successfulIds.push(row.id);
    } catch (err) {
      console.error(`Dispatch failed for event ${row.id}`, err);
    }
  }

  markEventsDispatched(successfulIds);
}
```

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 Checkpoint Starvation Boundary & Disk Growth Guardrail

Bun 1.2 SQLite WAL2 Checkpoint Starvation Boundary & Disk Growth Guardrail defines an industrial-grade behavioral standard for backend engineering. Prevents unbounded WAL growth and container ENOSPC failures in high-throughput Bun 1.2 microservices using SQLite WAL/WAL2 mode. Enforces strict boundary isolation between synchronous read/write transactions and asynchronous event-loop operations, eliminating reader snapshot holding that blocks WAL log recycling. 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: Suspending SQLite Transactions Across Asynchronous Event Loop Ticks 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 DriftSuspending SQLite Transactions Across Asynchronous Event Loop TicksCritical
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 NEVER execute asynchronous promises (e.g., `await fetch()`, timer delays, message bus dispatches) inside a `bun

Engineers MUST NEVER execute asynchronous promises (e.g., `await fetch()`, timer delays, message bus dispatches) inside a `bun:sqlite` transaction context.

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 isolate SQLite read transactions to synchronous, discrete code paths that finalize iterators or read arrays prior to yielding to the Bun event loop.

Engineers MUST ALWAYS isolate SQLite read transactions to synchronous, discrete code paths that finalize iterators or read arrays prior to yielding to the Bun event loop.

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

Code MUST set `PRAGMA busy_timeout = 5000

Code MUST set `PRAGMA busy_timeout = 5000;` and explicitly configure `PRAGMA synchronous = NORMAL;` alongside `PRAGMA journal_mode = WAL2;` upon database connection initialization.

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 implement a background checkpoint supervisor that periodically executes `PRAGMA wal_checkpoint(PASSIVE)` and escalates to `RESTART` or `TRUNCATE` when WAL size exceeds bounded thresholds (e.g., 64MB).

Services MUST implement a background checkpoint supervisor that periodically executes `PRAGMA wal_checkpoint(PASSIVE)` and escalates to `RESTART` or `TRUNCATE` when WAL size exceeds bounded thresholds (e.g., 64MB).

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 execute unbounded cursor streaming (`query.iterate()`) concurrently with long network streams without chunking records into discrete synchronous snapshot batches.

Components NEVER execute unbounded cursor streaming (`query.iterate()`) concurrently with long network streams without chunking records into discrete synchronous snapshot batches.

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 Checkpoint Starvation Boundary & Disk Growth Guardrail critical for AI coding assistants?

Prevents unbounded WAL growth and container ENOSPC failures in high-throughput Bun 1.2 microservices using SQLite WAL/WAL2 mode. Enforces strict boundary isolation between synchronous read/write transactions and asynchronous event-loop operations, eliminating reader snapshot holding that blocks WAL log recycling. 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 (Suspending SQLite Transactions Across Asynchronous Event Loop Ticks) 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