This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-native-connection-pool-thread-safety-guardrail

Bun 1.2 Native Database Driver & Thread-Local Connection Pool Isolation

Enforces thread-isolated connection pooling and prevents file descriptor corruption in Bun 1.2 runtimes. Native SQLite (bun:sqlite) and Postgres (bun:sql) instances allocate underlying C/Zig memory pointers and OS descriptors that are not safe for cross-worker sharing or concurrent cross-thread mutations. AI agents must enforce strict thread-local connection instantiation or serialize-by-value worker RPC architectures.

Prohibited Anti-Pattern: Sharing Native Database Instances Across Bun Worker Threads Causing FD Corruption and Segfaults

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Database Driver & Thread-Local Connection Pool Isolation - Enforces thread-isolated connection pooling and prevents file descriptor corruption in Bun 1.2 runtimes. Native SQLite (bun:sqlite) and Postgres (bun:sql) instances allocate underlying C/Zig memory pointers and OS descriptors that are not safe for cross-worker sharing or concurrent cross-thread mutations. AI agents must enforce strict thread-local connection instantiation or serialize-by-value worker RPC architectures.
globs: src/**/*.{ts,tsx}, workers/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-connection-pool-thread-safety-guardrail"
---

# Bun 1.2 Native Database Driver & Thread-Local Connection Pool Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Sharing Native Database Instances Across Bun Worker Threads Causing FD Corruption and Segfaults

## System Constraints
You are a Principal Backend Architect enforcing Bun 1.2 native driver safety standards. Mandate strict isolation of native SQLite (`bun:sqlite`) and Postgres (`bun:sql`) handles within Bun preemptive worker threads. Never allow native database handles or stateful transactions to be passed via IPC or shared across thread boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate native database drivers (`bun:sqlite` Database and `bun:sql` SQLClient) strictly within the executing worker thread's local scope.
- Engineers MUST NOT attempt to transfer native database handles, prepared statements, or transaction handles through `worker.postMessage()` across thread boundaries.
- Code SHOULD utilize serialize-by-value message passing (Worker RPC pattern) when a dedicated actor worker manages database operations.
- Services MUST configure SQLite in Write-Ahead Logging mode (`PRAGMA journal_mode = WAL;`) and set a busy timeout whenever multiple Bun worker threads instantiate separate connections to the same database file.
- Components NEVER share global singleton database instances across preemptive worker execution contexts.

## Bad vs Good Implementations
### Bun SQLite Worker Concurrency & Handle Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Native C/Zig pointers backing bun:sqlite cannot survive structured cloning across threads. Sharing database file descriptors without thread isolation and WAL configuration leads to database locks, corrupted file headers, or process crashes.
```typescript
import { Database } from "bun:sqlite";

// Anti-pattern: Main thread initializes DB handle and attempts to pass it
// or worker threads concurrently write without WAL/busy timeout configuration
const sharedDb = new Database("production.db");

const worker = new Worker("./db-worker.ts");
// CRITICAL: Passing native DB handles via postMessage causes DataCloneError
// or pointer corruption if deserialization hooks are bypassed
worker.postMessage({ type: "EXECUTE", db: sharedDb, query: "INSERT INTO events VALUES (?)" });
```

#### Production Standard (Correct)
> **Standard**: Each Bun worker maintains its own thread-local native database instance. Concurrency across worker threads is coordinated through SQLite WAL mode and busy timeouts at the storage engine level, using strictly serializable payload IPC.
```typescript
import { Database } from "bun:sqlite";

// db-worker.ts (Isolated Worker Execution Context)
declare var self: Worker;

// Invariant: Thread-local database instantiation with concurrency configuration
const threadLocalDb = new Database("production.db", { create: true });
threadLocalDb.exec("PRAGMA journal_mode = WAL;");
threadLocalDb.exec("PRAGMA busy_timeout = 5000;");

const insertStatement = threadLocalDb.query("INSERT INTO events (payload) VALUES ($payload)");

self.onmessage = (event: MessageEvent<{ type: string; payload: string }>) => {
  if (event.data.type === "EXECUTE") {
    insertStatement.run({ $payload: event.data.payload });
    self.postMessage({ status: "ok" });
  }
};
```

### Bun 1.2 Native Postgres (bun:sql) Worker Pool Allocation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bun 1.2 native SQL creates underlying connection pools bound to thread event loops. Sharing connection pool descriptors across preemptive worker threads leads to multiplexed socket corruption and out-of-order response stream decoding.
```typescript
import { SQL } from "bun";

// Anti-pattern: Exporting a global pool singleton imported by multiple preemptive workers
export const sql = new SQL({
  url: process.env.DATABASE_URL,
  max: 20
});

// In worker.ts: Directly sharing the client causes socket FD race conditions across threads
// import { sql } from "./db";
// await sql`SELECT 1`;
```

#### Production Standard (Correct)
> **Standard**: Connection pools are explicitly scoped per worker thread, with connection counts sized dynamically to stay within upstream database server limits without sharing socket descriptors across thread loops.
```typescript
import { SQL } from "bun";

// worker-pool.ts: Factory ensuring thread-local pool allocation with scaled capacity
export function createThreadLocalSqlClient(workerCount: number): SQL {
  const baseMaxConnections = 20;
  // Invariant: Pool size scaled to avoid exhausting PostgreSQL max_connections across workers
  const connectionsPerWorker = Math.max(2, Math.floor(baseMaxConnections / workerCount));

  return new SQL({
    url: process.env.DATABASE_URL,
    max: connectionsPerWorker,
    idleTimeout: 30
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Native Database Driver & Thread-Local Connection Pool Isolation

Bun 1.2 Native Database Driver & Thread-Local Connection Pool Isolation defines an industrial-grade behavioral standard for backend engineering. Enforces thread-isolated connection pooling and prevents file descriptor corruption in Bun 1.2 runtimes. Native SQLite (bun:sqlite) and Postgres (bun:sql) instances allocate underlying C/Zig memory pointers and OS descriptors that are not safe for cross-worker sharing or concurrent cross-thread mutations. AI agents must enforce strict thread-local connection instantiation or serialize-by-value worker RPC architectures. 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: Sharing Native Database Instances Across Bun Worker Threads Causing FD Corruption and Segfaults 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 DriftSharing Native Database Instances Across Bun Worker Threads Causing FD Corruption and SegfaultsCritical
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 instantiate native database drivers (`bun

Engineers MUST ALWAYS instantiate native database drivers (`bun:sqlite` Database and `bun:sql` SQLClient) strictly within the executing worker thread's local scope.

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 NOT attempt to transfer native database handles, prepared statements, or transaction handles through `worker.postMessage()` across thread boundaries.

Engineers MUST NOT attempt to transfer native database handles, prepared statements, or transaction handles through `worker.postMessage()` across thread boundaries.

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 SHOULD utilize serialize-by-value message passing (Worker RPC pattern) when a dedicated actor worker manages database operations.

Code SHOULD utilize serialize-by-value message passing (Worker RPC pattern) when a dedicated actor worker manages database 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 configure SQLite in Write-Ahead Logging mode (`PRAGMA journal_mode = WAL

Services MUST configure SQLite in Write-Ahead Logging mode (`PRAGMA journal_mode = WAL;`) and set a busy timeout whenever multiple Bun worker threads instantiate separate connections to the same database file.

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 share global singleton database instances across preemptive worker execution contexts.

Components NEVER share global singleton database instances across preemptive worker execution contexts.

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 Native Database Driver & Thread-Local Connection Pool Isolation critical for AI coding assistants?

Enforces thread-isolated connection pooling and prevents file descriptor corruption in Bun 1.2 runtimes. Native SQLite (bun:sqlite) and Postgres (bun:sql) instances allocate underlying C/Zig memory pointers and OS descriptors that are not safe for cross-worker sharing or concurrent cross-thread mutations. AI agents must enforce strict thread-local connection instantiation or serialize-by-value worker RPC architectures. 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 (Sharing Native Database Instances Across Bun Worker Threads Causing FD Corruption and Segfaults) 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