This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-clustered-worker-native-sql-isolation-standard

Bun 1.2 Clustered Worker Native SQL Connection Pool Isolation Standard

Enforces strict per-worker thread-pinned lifecycle management for native SQL clients (`bun:sqlite`, native Postgres/MySQL clients) when operating under Bun clustered worker topologies. Prevents cross-worker socket desynchronization, file descriptor leaks, and IPC contention by prohibiting shared connection handles across process or thread boundaries.

Prohibited Anti-Pattern: Sharing or Hoisting Native Database Clients Across Bun Worker Thread Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Clustered Worker Native SQL Connection Pool Isolation Standard - Enforces strict per-worker thread-pinned lifecycle management for native SQL clients (`bun:sqlite`, native Postgres/MySQL clients) when operating under Bun clustered worker topologies. Prevents cross-worker socket desynchronization, file descriptor leaks, and IPC contention by prohibiting shared connection handles across process or thread boundaries.
globs: src/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-clustered-worker-native-sql-isolation-standard"
---

# Bun 1.2 Clustered Worker Native SQL Connection Pool Isolation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Sharing or Hoisting Native Database Clients Across Bun Worker Thread Boundaries

## System Constraints
You are a Principal Backend Systems Architect enforcing the Bun 1.2 Clustered Worker Native SQL Connection Pool Isolation Standard. Mandate that all native SQL clients (PostgreSQL, MySQL, SQLite) instantiate connection pools strictly within the isolated scope of individual Bun workers. Prohibit serialization or IPC transmission of active socket handles, and enforce deterministic socket lifecycle cleanup on worker termination.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate native SQL connection pools within the local context of each individual Bun Worker (`self` / worker scope) rather than inheriting or passing active socket references from the primary thread.
- Engineers MUST NOT attempt to pass native SQL database handles, active connection instances, or raw socket descriptors through `postMessage()` or shared memory structures across workers.
- Services MUST enforce strict per-worker pool size limits calculated by dividing the target database server connection capacity by the total active worker count (`max_connections / worker_count`).
- Services MUST register lifecycle disposal listeners on `self.addEventListener('close', ...)` and `process.on('SIGTERM', ...)` to drain and close the native pool explicitly before the worker process halts.
- Components NEVER execute cross-thread database queries over IPC; workers must execute queries against their own pinned local pool and return serialized plain data DTOs to orchestrators.

## Bad vs Good Implementations
### Cross-Worker Shared SQL Client Anti-Pattern vs Isolated Thread-Pinned Pool Standard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attempting to pass active database socket connections across worker boundaries via workerData or postMessage violates socket ownership invariants. Bun's native SQL client cannot be cloned across isolate boundaries, resulting in serialization failures, socket descriptor contention, and deadlocks.
```typescript
import { SQL } from 'bun';

// Anti-pattern: Instantiating client in main thread and leaking/attempting to share via worker data
const sharedSql = new SQL(process.env.DATABASE_URL!);

const worker = new Worker(new URL('./worker.ts', import.meta.url), {
  workerData: { dbHandle: sharedSql } // Fails: Sockets cannot be cloned via Structured Clone Algorithm or causes cross-thread race conditions
});

worker.postMessage({ action: 'QUERY', client: sharedSql });
```

#### Production Standard (Correct)
> **Standard**: The native SQL client is strictly initialized within the worker's own isolate. The connection pool size is apportioned proportionally across worker threads, sockets remain pinned to the executing thread, and deterministic resource disposal occurs via the worker lifecycle hook.
```typescript
// worker.ts - Thread-pinned worker initialization
import { SQL } from 'bun';

interface WorkerConfig {
  workerId: number;
  maxPoolSize: number;
}

// Initialize isolated native SQL instance strictly inside the worker
const poolSize = Math.max(1, Math.floor(100 / (navigator.hardwareConcurrency || 4)));
const sql = new SQL({
  url: process.env.DATABASE_URL!,
  max: poolSize,
  idleTimeout: 30,
  connectionTimeout: 5,
});

self.onmessage = async (event: MessageEvent<{ id: string; query: string; params: unknown[] }>) => {
  const { id, query, params } = event.data;
  try {
    const result = await sql(query, params);
    self.postMessage({ id, success: true, data: result });
  } catch (error) {
    self.postMessage({
      id,
      success: false,
      error: error instanceof Error ? error.message : 'Unknown database error',
    });
  }
};

self.addEventListener('close', async () => {
  await sql.close();
});
```

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 Clustered Worker Native SQL Connection Pool Isolation Standard

Bun 1.2 Clustered Worker Native SQL Connection Pool Isolation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict per-worker thread-pinned lifecycle management for native SQL clients (`bun:sqlite`, native Postgres/MySQL clients) when operating under Bun clustered worker topologies. Prevents cross-worker socket desynchronization, file descriptor leaks, and IPC contention by prohibiting shared connection handles across process or thread boundaries. 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 or Hoisting Native Database Clients Across Bun Worker Thread Boundaries 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 or Hoisting Native Database Clients Across Bun Worker Thread BoundariesCritical
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 SQL connection pools within the local context of each individual Bun Worker (`self` / worker scope) rather than inheriting or passing active socket references from the primary thread.

Engineers MUST ALWAYS instantiate native SQL connection pools within the local context of each individual Bun Worker (`self` / worker scope) rather than inheriting or passing active socket references from the primary thread.

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 pass native SQL database handles, active connection instances, or raw socket descriptors through `postMessage()` or shared memory structures across workers.

Engineers MUST NOT attempt to pass native SQL database handles, active connection instances, or raw socket descriptors through `postMessage()` or shared memory structures across workers.

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

Services MUST enforce strict per-worker pool size limits calculated by dividing the target database server connection capacity by the total active worker count (`max_connections / worker_count`).

Services MUST enforce strict per-worker pool size limits calculated by dividing the target database server connection capacity by the total active worker count (`max_connections / worker_count`).

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 register lifecycle disposal listeners on `self.addEventListener('close', ...)` and `process.on('SIGTERM', ...)` to drain and close the native pool explicitly before the worker process halts.

Services MUST register lifecycle disposal listeners on `self.addEventListener('close', ...)` and `process.on('SIGTERM', ...)` to drain and close the native pool explicitly before the worker process halts.

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 cross-thread database queries over IPC

Components NEVER execute cross-thread database queries over IPC; workers must execute queries against their own pinned local pool and return serialized plain data DTOs to orchestrators.

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 Clustered Worker Native SQL Connection Pool Isolation Standard critical for AI coding assistants?

Enforces strict per-worker thread-pinned lifecycle management for native SQL clients (`bun:sqlite`, native Postgres/MySQL clients) when operating under Bun clustered worker topologies. Prevents cross-worker socket desynchronization, file descriptor leaks, and IPC contention by prohibiting shared connection handles across process or thread boundaries. 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 or Hoisting Native Database Clients Across Bun Worker Thread Boundaries) 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