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

Bun 1.2 Embedded SQLite WAL Concurrency and Native S3 Streaming Invariants

Enforces production-grade concurrency invariants for Bun 1.2 embedded bun:sqlite with Write-Ahead Logging (WAL) and native zero-copy S3 streaming storage. Prevents database lock starvation (SQLITE_BUSY), unbounded heap consumption during object storage transfers, and unescaped SQL execution.

Prohibited Anti-Pattern: Unconfigured SQLite Rollback Journals with In-Memory S3 File Buffering

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Embedded SQLite WAL Concurrency and Native S3 Streaming Invariants - Enforces production-grade concurrency invariants for Bun 1.2 embedded bun:sqlite with Write-Ahead Logging (WAL) and native zero-copy S3 streaming storage. Prevents database lock starvation (SQLITE_BUSY), unbounded heap consumption during object storage transfers, and unescaped SQL execution.
globs: src/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-s3-native-streaming"
---

# Bun 1.2 Embedded SQLite WAL Concurrency and Native S3 Streaming Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unconfigured SQLite Rollback Journals with In-Memory S3 File Buffering

## System Constraints
You are a Principal Backend Systems Architect enforcing Bun 1.2 embedded database and cloud storage patterns. You must reject any bun:sqlite implementation that fails to initialize WAL mode and busy timeouts, and reject any S3 uploads that buffer payloads into heap memory instead of using Bun's native streaming APIs.

## Strict Guidelines
- Engineers MUST ALWAYS configure 'PRAGMA journal_mode = WAL;' and 'PRAGMA busy_timeout = 5000;' immediately upon opening a `bun:sqlite` Database connection.
- Engineers MUST set 'PRAGMA synchronous = NORMAL;' in WAL mode to maintain crash safety while maximizing NVMe write throughput.
- Engineers MUST NEVER buffer large S3 uploads into heap memory via `arrayBuffer()`, `Buffer.concat()`, or in-memory blobs; native `Bun.s3.write()` or streaming pipes MUST be used.
- Engineers MUST ALWAYS prepare SQL statements outside of high-frequency execution loops and use parameterized bindings ($param, :param, or ?) to enable query plan reuse and prevent SQL injection.
- Engineers MUST NEVER import heavyweight legacy AWS SDK clients when Bun 1.2 native S3 APIs ('bun' or native S3Client) provide zero-copy, C++ backed network streaming.
- Services MUST gracefully checkpoint WAL files via 'PRAGMA wal_checkpoint(TRUNCATE);' during application teardown or scheduled maintenance.

## Bad vs Good Implementations
### SQLite WAL Concurrency and Parameterized Zero-Copy Queries

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to set WAL mode causes readers and writers to block each other. Omitting busy_timeout crashes operations immediately upon contention. String interpolation introduces critical SQL injection vulnerabilities and prevents query plan caching.
```typescript
import { Database } from 'bun:sqlite';

// ANTI-PATTERN: Default rollback journal locks readers during writes.
// Missing busy_timeout throws immediate SQLITE_BUSY errors under concurrency.
// Unescaped template literal leads to critical SQL injection vulnerability.
export class OrderRepository {
  private db = new Database('orders.db');

  getOrder(id: string) {
    return this.db.query(`SELECT * FROM orders WHERE id = '${id}'`).get();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Sets WAL mode to permit non-blocking concurrent reads during writes, specifies a 5000ms busy timeout to prevent transient contention crashes, caches prepared statements, and guarantees parameter safety.
```typescript
import { Database } from 'bun:sqlite';

interface OrderRecord {
  id: string;
  userId: string;
  amount: number;
  createdAt: string;
}

export class OrderRepository {
  private db: Database;
  private getOrderStmt;

  constructor(dbPath: string = 'orders.db') {
    this.db = new Database(dbPath, { create: true, strict: true });
    
    // Mandatory concurrency & durability pragmas for Bun embedded SQLite
    this.db.exec('PRAGMA journal_mode = WAL;');
    this.db.exec('PRAGMA synchronous = NORMAL;');
    this.db.exec('PRAGMA busy_timeout = 5000;');

    // Prepared statement instantiated once, leveraging zero-copy deserialization
    this.getOrderStmt = this.db.query<OrderRecord, { $id: string }>(
      'SELECT id, userId, amount, createdAt FROM orders WHERE id = $id;'
    );
  }

  getOrder(id: string): OrderRecord | null {
    return this.getOrderStmt.get({ $id: id });
  }

  close(): void {
    this.db.exec('PRAGMA wal_checkpoint(TRUNCATE);');
    this.db.close();
  }
}
```

### Zero-Copy S3 Multipart Streaming vs Heap Buffering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reading the entire incoming body into an in-memory Buffer/ArrayBuffer exhausts Node/Bun process memory under multi-gigabyte uploads or concurrent burst traffic.
```typescript
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const client = new S3Client({ region: 'us-east-1' });

// ANTI-PATTERN: Buffering entire stream into memory exhaust heap limits (OOM)
// under large file uploads or concurrent requests.
export async function uploadArtifact(key: string, req: Request): Promise<void> {
  const buffer = Buffer.from(await req.arrayBuffer());
  await client.send(new PutObjectCommand({
    Bucket: 'production-assets',
    Key: key,
    Body: buffer,
  }));
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Bun 1.2 native S3 file streaming to pipe the incoming HTTP request stream directly to S3 with zero intermediary heap allocation, eliminating out-of-memory risks.
```typescript
import { s3 } from 'bun';

// PRODUCTION PATTERN: Bun 1.2 native S3 zero-copy streaming pipeline
export async function uploadArtifact(key: string, req: Request): Promise<void> {
  if (!req.body) {
    throw new Error('Missing payload stream');
  }

  const s3File = s3.file(`production-assets/${key}`, {
    endpoint: process.env.S3_ENDPOINT,
    accessKeyId: process.env.S3_ACCESS_KEY_ID,
    secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION ?? 'us-east-1',
  });

  // Native C++ stream pipe directly to S3 multipart upload with zero JS heap buffering
  await s3File.write(req.body, {
    type: req.headers.get('content-type') ?? 'application/octet-stream',
  });
}
```

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 Embedded SQLite WAL Concurrency and Native S3 Streaming Invariants

Bun 1.2 Embedded SQLite WAL Concurrency and Native S3 Streaming Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces production-grade concurrency invariants for Bun 1.2 embedded bun:sqlite with Write-Ahead Logging (WAL) and native zero-copy S3 streaming storage. Prevents database lock starvation (SQLITE_BUSY), unbounded heap consumption during object storage transfers, and unescaped SQL execution. 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: Unconfigured SQLite Rollback Journals with In-Memory S3 File Buffering 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 DriftUnconfigured SQLite Rollback Journals with In-Memory S3 File BufferingCritical
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 busy_timeout = 5000;' immediately upon opening a `bun:sqlite` Database 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 set 'PRAGMA synchronous = NORMAL

Engineers MUST set 'PRAGMA synchronous = NORMAL;' in WAL mode to maintain crash safety while maximizing NVMe write throughput.

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 NEVER buffer large S3 uploads into heap memory via `arrayBuffer()`, `Buffer.concat()`, or in-memory blobs

Engineers MUST NEVER buffer large S3 uploads into heap memory via `arrayBuffer()`, `Buffer.concat()`, or in-memory blobs; native `Bun.s3.write()` or streaming pipes MUST be used.

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 ALWAYS prepare SQL statements outside of high-frequency execution loops and use parameterized bindings ($param,

Engineers MUST ALWAYS prepare SQL statements outside of high-frequency execution loops and use parameterized bindings ($param, :param, or ?) to enable query plan reuse and prevent SQL injection.

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

Engineers MUST NEVER import heavyweight legacy AWS SDK clients when Bun 1.2 native S3 APIs ('bun' or native S3Client) provide zero-copy, C++ backed network streaming.

Engineers MUST NEVER import heavyweight legacy AWS SDK clients when Bun 1.2 native S3 APIs ('bun' or native S3Client) provide zero-copy, C++ backed network streaming.

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

Services MUST gracefully checkpoint WAL files via 'PRAGMA wal_checkpoint(TRUNCATE)

Services MUST gracefully checkpoint WAL files via 'PRAGMA wal_checkpoint(TRUNCATE);' during application teardown or scheduled maintenance.

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 Embedded SQLite WAL Concurrency and Native S3 Streaming Invariants critical for AI coding assistants?

Enforces production-grade concurrency invariants for Bun 1.2 embedded bun:sqlite with Write-Ahead Logging (WAL) and native zero-copy S3 streaming storage. Prevents database lock starvation (SQLITE_BUSY), unbounded heap consumption during object storage transfers, and unescaped SQL execution. 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 (Unconfigured SQLite Rollback Journals with In-Memory S3 File Buffering) 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