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-storage

Bun 1.2 Embedded SQLite WAL & S3 Native Zero-Copy Streaming Invariants

Enforces deterministic concurrency control and high-throughput zero-copy streaming when combining Bun 1.2's native bun:sqlite engine with Bun.s3 storage. Mandates WAL journal mode with synchronous normal settings, prepared statement reuse, and direct stream piping between SQLite BLOB reads/writes and native S3 multipart operations without intermediate in-memory buffering. Eliminates event loop blocking, file lock deadlocks, and Node.js wrapper overhead.

Prohibited Anti-Pattern: Unbuffered in-memory reads, missing WAL journal configuration, and redundant AWS-SDK wrapping in Bun runtimes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Embedded SQLite WAL & S3 Native Zero-Copy Streaming Invariants - Enforces deterministic concurrency control and high-throughput zero-copy streaming when combining Bun 1.2's native bun:sqlite engine with Bun.s3 storage. Mandates WAL journal mode with synchronous normal settings, prepared statement reuse, and direct stream piping between SQLite BLOB reads/writes and native S3 multipart operations without intermediate in-memory buffering. Eliminates event loop blocking, file lock deadlocks, and Node.js wrapper overhead.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-s3-native-storage"
---

# Bun 1.2 Embedded SQLite WAL & S3 Native Zero-Copy Streaming Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbuffered in-memory reads, missing WAL journal configuration, and redundant AWS-SDK wrapping in Bun runtimes

## System Constraints
You are a Principal Engineer enforcing production invariants for Bun 1.2 native bun:sqlite and Bun.s3 architectures. Mandate strict zero-copy streaming, WAL mode concurrency invariants, and native S3 client usage. Reject Node-specific polyfills (aws-sdk, better-sqlite3) and intermediate ArrayBuffer pooling for high-volume transactions.

## Strict Guidelines
- Engineers MUST ALWAYS execute `PRAGMA journal_mode = WAL;` and `PRAGMA synchronous = NORMAL;` immediately upon opening a `bun:sqlite` Database instance.
- Engineers MUST ALWAYS cache and reuse `Database.prototype.query()` prepared statements instead of calling ad-hoc query execution methods in request hot paths.
- Engineers MUST NEVER use heavy AWS SDK packages (`@aws-sdk/client-s3`) when Bun 1.2's native `Bun.s3` client provides zero-overhead S3 operations.
- Services MUST pipe `Bun.s3.file().stream()` directly to disk or downstream consumers without accumulating entire payloads in memory via `await response.arrayBuffer()`.
- Engineers MUST wrap multi-statement SQLite mutations in explicit `db.transaction()` callbacks to ensure ACID compliance and prevent transaction-lock starvation under high WAL concurrency.
- Code SHOULD configure `PRAGMA busy_timeout = 5000;` to gracefully handle concurrent SQLite write queueing without immediately throwing SQLITE_BUSY errors.
- Components NEVER store unstructured binary payloads larger than 64KB inside SQLite columns; store the S3 object URI in SQLite and pipe the payload directly to Bun S3.

## Bad vs Good Implementations
### Native Bun S3 Streaming & SQLite WAL Storage Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits SQLite WAL mode and busy timeout, uses heavy @aws-sdk/client-s3 instead of Bun.s3, buffers stream contents entirely into memory causing OOM risks, and runs an unparameterized ad-hoc SQL query vulnerable to injection and locking.
```typescript
import { Database } from 'bun:sqlite';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

// ANTI-PATTERN: Default rollback journal, AWS SDK overhead, and in-memory buffer bloat
const db = new Database('app.db');
const s3 = new S3Client({ region: 'us-east-1' });

export async function saveAsset(assetId: string, stream: ReadableStream): Promise<void> {
  // Inefficiently buffers whole stream into RAM
  const chunks: Uint8Array[] = [];
  const reader = stream.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
  }
  const buffer = Buffer.concat(chunks);

  await s3.send(new PutObjectCommand({
    Bucket: 'assets',
    Key: `${assetId}.bin`,
    Body: buffer
  }));

  // Non-prepared, unconfigured transaction susceptible to SQLITE_BUSY
  db.run(`INSERT INTO assets (id, size, path) VALUES ('${assetId}', ${buffer.byteLength}, '${assetId}.bin')`);
}
```

#### Production Standard (Correct)
> **Standard**: Configures SQLite with WAL, NORMAL synchronization, and 5000ms busy timeout. Uses native `Bun.s3.file().write()` for zero-copy streaming without RAM buffer spikes, and executes an atomic transaction with a precompiled statement.
```typescript
import { Database } from 'bun:sqlite';
import { s3 } from 'bun';

// PRODUCTION INVARIANT: WAL mode, safe timeout, and prepared statements
const db = new Database('app.db', { create: true });
db.run('PRAGMA journal_mode = WAL;');
db.run('PRAGMA synchronous = NORMAL;');
db.run('PRAGMA busy_timeout = 5000;');

interface AssetRecord {
  id: string;
  size: number;
  path: string;
}

const insertAssetStmt = db.prepare<void, [string, number, string]>(
  'INSERT INTO assets (id, size, path) VALUES (?1, ?2, ?3)'
);

export async function saveAsset(
  assetId: string,
  body: ReadableStream<Uint8Array> | Blob | ArrayBufferView,
  contentLength: number
): Promise<void> {
  const s3Path = `assets/${assetId}.bin`;
  const target = s3.file(s3Path);

  // Native Bun zero-copy multipart stream to S3
  await target.write(body);

  // Atomically record metadata via prepared statement
  db.transaction(() => {
    insertAssetStmt.run(assetId, contentLength, s3Path);
  })();
}
```

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 & S3 Native Zero-Copy Streaming Invariants

Bun 1.2 Embedded SQLite WAL & S3 Native Zero-Copy Streaming Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic concurrency control and high-throughput zero-copy streaming when combining Bun 1.2's native bun:sqlite engine with Bun.s3 storage. Mandates WAL journal mode with synchronous normal settings, prepared statement reuse, and direct stream piping between SQLite BLOB reads/writes and native S3 multipart operations without intermediate in-memory buffering. Eliminates event loop blocking, file lock deadlocks, and Node.js wrapper overhead. 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: Unbuffered in-memory reads, missing WAL journal configuration, and redundant AWS-SDK wrapping in Bun runtimes 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 DriftUnbuffered in-memory reads, missing WAL journal configuration, and redundant AWS-SDK wrapping in Bun runtimesCritical
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 execute `PRAGMA journal_mode = WAL

Engineers MUST ALWAYS execute `PRAGMA journal_mode = WAL;` and `PRAGMA synchronous = NORMAL;` immediately upon opening a `bun:sqlite` 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

Engineers MUST ALWAYS cache and reuse `Database.prototype.query()` prepared statements instead of calling ad-hoc query execution methods in request hot paths.

Engineers MUST ALWAYS cache and reuse `Database.prototype.query()` prepared statements instead of calling ad-hoc query execution methods in request hot paths.

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 use heavy AWS SDK packages (`@aws-sdk/client-s3`) when Bun 1.2's native `Bun.s3` client provides zero-overhead S3 operations.

Engineers MUST NEVER use heavy AWS SDK packages (`@aws-sdk/client-s3`) when Bun 1.2's native `Bun.s3` client provides zero-overhead S3 operations.

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 pipe `Bun.s3.file().stream()` directly to disk or downstream consumers without accumulating entire payloads in memory via `await response.arrayBuffer()`.

Services MUST pipe `Bun.s3.file().stream()` directly to disk or downstream consumers without accumulating entire payloads in memory via `await response.arrayBuffer()`.

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 wrap multi-statement SQLite mutations in explicit `db.transaction()` callbacks to ensure ACID compliance and prevent transaction-lock starvation under high WAL concurrency.

Engineers MUST wrap multi-statement SQLite mutations in explicit `db.transaction()` callbacks to ensure ACID compliance and prevent transaction-lock starvation under high WAL concurrency.

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

Code SHOULD configure `PRAGMA busy_timeout = 5000

Code SHOULD configure `PRAGMA busy_timeout = 5000;` to gracefully handle concurrent SQLite write queueing without immediately throwing SQLITE_BUSY errors.

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.
7

Components NEVER store unstructured binary payloads larger than 64KB inside SQLite columns

Components NEVER store unstructured binary payloads larger than 64KB inside SQLite columns; store the S3 object URI in SQLite and pipe the payload directly to Bun S3.

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 & S3 Native Zero-Copy Streaming Invariants critical for AI coding assistants?

Enforces deterministic concurrency control and high-throughput zero-copy streaming when combining Bun 1.2's native bun:sqlite engine with Bun.s3 storage. Mandates WAL journal mode with synchronous normal settings, prepared statement reuse, and direct stream piping between SQLite BLOB reads/writes and native S3 multipart operations without intermediate in-memory buffering. Eliminates event loop blocking, file lock deadlocks, and Node.js wrapper overhead. 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 (Unbuffered in-memory reads, missing WAL journal configuration, and redundant AWS-SDK wrapping in Bun runtimes) 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