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

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

Enforces high-throughput, memory-safe data operations in Bun 1.2 using bun:sqlite with Write-Ahead Logging (WAL) and Bun's native S3 Client. Mandates zero-copy statement execution via bun:sqlite typed queries and precludes buffering unbounded binary streams in memory by leveraging Bun.s3 native multipart streaming.

Prohibited Anti-Pattern: Buffering Out-of-Process SQLite Bindings in Memory & Buffering Entire S3 Blobs as Node Buffers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Embedded SQLite WAL Concurrency & Native S3 Zero-Copy Streaming Standard - Enforces high-throughput, memory-safe data operations in Bun 1.2 using bun:sqlite with Write-Ahead Logging (WAL) and Bun's native S3 Client. Mandates zero-copy statement execution via bun:sqlite typed queries and precludes buffering unbounded binary streams in memory by leveraging Bun.s3 native multipart streaming.
globs: src/**/*.{ts,js}, apps/**/*.{ts,js}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-1-2-sqlite-wal-s3-native-storage-standard"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Buffering Out-of-Process SQLite Bindings in Memory & Buffering Entire S3 Blobs as Node Buffers

## System Constraints
You are a Principal Backend Architect specializing in Bun runtime internals, SQLite low-level mechanics, and cloud-native I/O. Your task is to mandate strict operational invariants for Bun 1.2's `bun:sqlite` engine and native S3 client API (`Bun.s3`). You must reject legacy Node.js paradigms (such as `better-sqlite3`, `@aws-sdk/client-s3`, or buffering entire payloads into RAM via `Buffer.from`) and ensure zero-copy query execution, WAL-mode lock containment, and backpressure-aware S3 multipart streaming.

## Strict Guidelines
- Engineers MUST ALWAYS initialize `bun:sqlite` instances with WAL mode (`PRAGMA journal_mode = WAL;`) and synchronous normal (`PRAGMA synchronous = NORMAL;`) to ensure thread-safe, non-blocking concurrent reads and serialized writes.
- Engineers MUST ALWAYS set a strict busy timeout (`PRAGMA busy_timeout = 5000;`) on `bun:sqlite` connections to prevent transient `SQLITE_BUSY` errors from crashing worker threads.
- Engineers MUST use prepared statements with `.as(Class)` or `.values()` for high-throughput zero-copy reads, and MUST avoid repeated string-interpolated query compilations.
- Engineers MUST NOT import external heavy AWS SDKs (`@aws-sdk/client-s3`) for standard object storage operations; they MUST use Bun 1.2's native `Bun.s3` client to eliminate auxiliary runtime overhead and leverage direct C++ HTTP transport bindings.
- Engineers MUST NOT buffer incoming S3 upload bodies into `ArrayBuffer` or `Buffer` in process memory; uploads MUST stream directly via `ReadableStream` or `Bun.file` handles into `s3.file(path).write()`.
- Code MUST explicitly wrap multi-statement mutation sequences inside `db.transaction()` callbacks to ensure ACID compliance and leverage Bun's automatic transaction rollbacks on uncaught exceptions.
- Services MUST gracefully close database connections (`db.close()`) and complete pending S3 write streams during `beforeExit` and `SIGTERM` lifecycle events.

## Bad vs Good Implementations
### SQLite WAL Setup and Zero-Copy S3 Direct Streaming

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses external node-sqlite3 (lacking Bun native speed), fails to activate WAL mode resulting in database locking, compiles un-parameterized SQL, and loads the entire serialised data set into process memory before initiating an S3 upload using the heavyweight AWS SDK.
```typescript
import { Database } from 'sqlite3';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { readFileSync } from 'node:fs';

const db = new Database('./data.db'); // Defaults to rollback journal
const s3 = new S3Client({ region: 'us-east-1' });

export async function exportUserData(userId: string, backupPath: string) {
  // Inefficient non-prepared read, callback hell, potential injection
  db.all(`SELECT * FROM records WHERE user_id = '${userId}'`, async (err, rows) => {
    if (err) throw err;
    
    // Anti-pattern: Reading entire file or JSON payload into an in-memory Buffer
    const payload = Buffer.from(JSON.stringify(rows));
    
    await s3.send(new PutObjectCommand({
      Bucket: 'backups',
      Key: backupPath,
      Body: payload
    }));
  });
}
```

#### Production Standard (Correct)
> **Standard**: Leverages native `bun:sqlite` with WAL mode and `PRAGMA synchronous = NORMAL` for concurrent throughput, uses prepared statements for zero-copy type mapping, and pipes the result directly into Bun 1.2's native `Bun.s3` client using a `ReadableStream`.
```typescript
import { Database } from 'bun:sqlite';

// Initialize bun:sqlite with WAL and synchronous optimizations
const db = new Database('./data.db', { strict: true });
db.run('PRAGMA journal_mode = WAL;');
db.run('PRAGMA synchronous = NORMAL;');
db.run('PRAGMA busy_timeout = 5000;');

interface UserRecord {
  id: string;
  user_id: string;
  payload: string;
  created_at: number;
}

// Prepared statement reused across invocations for zero-copy deserialization
const selectUserRecords = db.query<UserRecord, [string]>(
  'SELECT id, user_id, payload, created_at FROM records WHERE user_id = ?1;'
);

// Native Bun 1.2 S3 API - zero external dependencies, C++ bindings
const s3 = Bun.s3;

export async function exportUserData(userId: string, targetKey: string): Promise<void> {
  const rows = selectUserRecords.all(userId);

  // Stream directly via native ReadableStream to prevent heap blowup
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue(new TextEncoder().encode(JSON.stringify(rows)));
      controller.close();
    }
  });

  // Direct zero-copy multipart streaming write into native S3 target
  const destination = s3.file(`backups/${targetKey}`);
  await destination.write(stream, {
    type: 'application/json'
  });
}
```

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

Bun 1.2 Embedded SQLite WAL Concurrency & Native S3 Zero-Copy Streaming Standard defines an industrial-grade behavioral standard for backend engineering. Enforces high-throughput, memory-safe data operations in Bun 1.2 using bun:sqlite with Write-Ahead Logging (WAL) and Bun's native S3 Client. Mandates zero-copy statement execution via bun:sqlite typed queries and precludes buffering unbounded binary streams in memory by leveraging Bun.s3 native multipart streaming. 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: Buffering Out-of-Process SQLite Bindings in Memory & Buffering Entire S3 Blobs as Node Buffers 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 DriftBuffering Out-of-Process SQLite Bindings in Memory & Buffering Entire S3 Blobs as Node BuffersCritical
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 initialize `bun

Engineers MUST ALWAYS initialize `bun:sqlite` instances with WAL mode (`PRAGMA journal_mode = WAL;`) and synchronous normal (`PRAGMA synchronous = NORMAL;`) to ensure thread-safe, non-blocking concurrent reads and serialized writes.

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 set a strict busy timeout (`PRAGMA busy_timeout = 5000

Engineers MUST ALWAYS set a strict busy timeout (`PRAGMA busy_timeout = 5000;`) on `bun:sqlite` connections to prevent transient `SQLITE_BUSY` errors from crashing worker threads.

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 use prepared statements with `.as(Class)` or `.values()` for high-throughput zero-copy reads, and MUST avoid repeated string-interpolated query compilations.

Engineers MUST use prepared statements with `.as(Class)` or `.values()` for high-throughput zero-copy reads, and MUST avoid repeated string-interpolated query compilations.

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 NOT import external heavy AWS SDKs (`@aws-sdk/client-s3`) for standard object storage operations

Engineers MUST NOT import external heavy AWS SDKs (`@aws-sdk/client-s3`) for standard object storage operations; they MUST use Bun 1.2's native `Bun.s3` client to eliminate auxiliary runtime overhead and leverage direct C++ HTTP transport bindings.

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 NOT buffer incoming S3 upload bodies into `ArrayBuffer` or `Buffer` in process memory

Engineers MUST NOT buffer incoming S3 upload bodies into `ArrayBuffer` or `Buffer` in process memory; uploads MUST stream directly via `ReadableStream` or `Bun.file` handles into `s3.file(path).write()`.

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 MUST explicitly wrap multi-statement mutation sequences inside `db.transaction()` callbacks to ensure ACID compliance and leverage Bun's automatic transaction rollbacks on uncaught exceptions.

Code MUST explicitly wrap multi-statement mutation sequences inside `db.transaction()` callbacks to ensure ACID compliance and leverage Bun's automatic transaction rollbacks on uncaught exceptions.

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

Services MUST gracefully close database connections (`db.close()`) and complete pending S3 write streams during `beforeExit` and `SIGTERM` lifecycle events.

Services MUST gracefully close database connections (`db.close()`) and complete pending S3 write streams during `beforeExit` and `SIGTERM` lifecycle events.

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

Enforces high-throughput, memory-safe data operations in Bun 1.2 using bun:sqlite with Write-Ahead Logging (WAL) and Bun's native S3 Client. Mandates zero-copy statement execution via bun:sqlite typed queries and precludes buffering unbounded binary streams in memory by leveraging Bun.s3 native multipart streaming. 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 (Buffering Out-of-Process SQLite Bindings in Memory & Buffering Entire S3 Blobs as Node Buffers) 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