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

Bun 1.2 Native SQL Connection Pool RAII and Finalizer Standard

Enforces deterministic connection release and explicit lifecycle management on Bun 1.2 native SQL connection pools using the ECMAScript Explicit Resource Management (RAII) protocol. Guarantees that checkout sockets, reserved clients, and multi-statement transactions release pooled file descriptors immediately upon scope exit, preventing kernel socket exhaustion during unhandled rejections or sudden POSIX process termination signals.

Prohibited Anti-Pattern: Unscoped Connection Checkouts and Dangling Leases Inducing File Descriptor Exhaustion Under Event-Loop Interruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native SQL Connection Pool RAII and Finalizer Standard - Enforces deterministic connection release and explicit lifecycle management on Bun 1.2 native SQL connection pools using the ECMAScript Explicit Resource Management (RAII) protocol. Guarantees that checkout sockets, reserved clients, and multi-statement transactions release pooled file descriptors immediately upon scope exit, preventing kernel socket exhaustion during unhandled rejections or sudden POSIX process termination signals.
globs: src/**/*.{ts,js}, apps/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-v12-sql-raii-finalizer-standard"
---

# Bun 1.2 Native SQL Connection Pool RAII and Finalizer Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unscoped Connection Checkouts and Dangling Leases Inducing File Descriptor Exhaustion Under Event-Loop Interruption

## System Constraints
You are a Principal Software Architect enforcing the Bun 1.2 Native SQL Connection Pool RAII Finalizer Standard. In Bun 1.2, database connections provisioned via native `bun:sql` or `SQL` instances utilize low-level OS file descriptors that bypass standard Node.js stream finalizers. You must mandate the ECMAScript Explicit Resource Management pattern (`await using` and `Symbol.asyncDispose`) for all reserved connection checkouts, transactional blocks, and pool lifecycle hooks. Reject any non-deterministic teardowns, ad-hoc `try...finally` connection releases vulnerable to event-loop abandonment, or omitted POSIX signal drains.

## Strict Guidelines
- Engineers MUST ALWAYS use 'await using' (Explicit Resource Management) when reserving dedicated connections or transactions from native SQL pools.
- Engineers MUST implement '[Symbol.asyncDispose]()' on all wrapper classes, unit-of-work abstractions, or repositories retaining native SQL client handles.
- Engineers MUST NOT rely on runtime garbage collection, FinalizationRegistry, or implicit idle timeouts to release reserved database sockets.
- Code MUST bind process-level POSIX signals ('SIGINT', 'SIGTERM') to an idempotent, bounded pool draining routine using 'sql.close()'.
- Services MUST ensure transactional blocks execute rollbacks inside '[Symbol.asyncDispose]()' if not explicitly committed prior to scope termination.
- Components NEVER execute raw 'BEGIN'/'COMMIT' statements across unbound asynchronous boundaries without RAII-guaranteed disposal.

## Bad vs Good Implementations
### Bun 1.2 Native SQL RAII Disposable Reservation vs Manual Checkout

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Manual acquisition without RAII finalizers leaks the underlying TCP socket and file descriptor whenever an error is thrown prior to calling release(), or when an event-loop interruption leaves the promise suspended, depleting the pool under load.
```typescript
import { SQL } from "bun";

export const sql = new SQL(process.env.DATABASE_URL!);

export async function executeTransfer(fromId: string, toId: string, amount: number) {
  // ANTI-PATTERN: Manual lease without RAII semantics.
  // Socket leaks if unhandled rejection occurs or process receives SIGINT before release().
  const client = await sql.reserve();
  await client`BEGIN`;
  
  const [sender] = await client`SELECT balance FROM accounts WHERE id = ${fromId}`;
  if (!sender || sender.balance < amount) {
    await client`ROLLBACK`;
    throw new Error("Insufficient funds"); // Leaks socket if exception handler skips release
  }
  
  await client`UPDATE accounts SET balance = balance - ${amount} WHERE id = ${fromId}`;
  await client`UPDATE accounts SET balance = balance + ${amount} WHERE id = ${toId}`;
  await client`COMMIT`;
  
  // Manual release easily bypassed by early return, thrown error, or cancellation
  await client.release();
}
```

#### Production Standard (Correct)
> **Standard**: Implements ECMAScript Explicit Resource Management (`await using` and `[Symbol.asyncDispose]`). Guarantees immediate connection rollback and return to the pool upon scope exit regardless of thrown errors, while process-level signal listeners gracefully drain the native pool.
```typescript
import { SQL } from "bun";

export const sql = new SQL({
  url: process.env.DATABASE_URL!,
  max: 20,
  idleTimeout: 30,
});

// Production RAII Scope for Bun 1.2 Native SQL
export class TransactionScope implements AsyncDisposable {
  private committed = false;
  
  private constructor(public readonly client: Awaited<ReturnType<typeof sql.reserve>>) {}

  static async begin(): Promise<TransactionScope> {
    const client = await sql.reserve();
    await client`BEGIN`;
    return new TransactionScope(client);
  }

  async commit(): Promise<void> {
    await this.client`COMMIT`;
    this.committed = true;
  }

  async [Symbol.asyncDispose](): Promise<void> {
    try {
      if (!this.committed) {
        await this.client`ROLLBACK`;
      }
    } catch {
      // Rollback error suppressed to preserve original throw
    } finally {
      await this.client.release();
    }
  }
}

export async function executeTransfer(fromId: string, toId: string, amount: number): Promise<void> {
  // Deterministic disposal guaranteed on normal exit, throw, or cancellation
  await using tx = await TransactionScope.begin();

  const [sender] = await tx.client`SELECT balance FROM accounts WHERE id = ${fromId}`;
  if (!sender || sender.balance < amount) {
    throw new Error("Insufficient funds");
  }

  await tx.client`UPDATE accounts SET balance = balance - ${amount} WHERE id = ${fromId}`;
  await tx.client`UPDATE accounts SET balance = balance + ${amount} WHERE id = ${toId}`;
  await tx.commit();
}

// Trap sudden interrupts to prevent orphaned socket file descriptors
for (const signal of ["SIGINT", "SIGTERM"] as const) {
  process.once(signal, async () => {
    await sql.close();
    process.exit(0);
  });
}
```

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 Native SQL Connection Pool RAII and Finalizer Standard

Bun 1.2 Native SQL Connection Pool RAII and Finalizer Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic connection release and explicit lifecycle management on Bun 1.2 native SQL connection pools using the ECMAScript Explicit Resource Management (RAII) protocol. Guarantees that checkout sockets, reserved clients, and multi-statement transactions release pooled file descriptors immediately upon scope exit, preventing kernel socket exhaustion during unhandled rejections or sudden POSIX process termination signals. 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: Unscoped Connection Checkouts and Dangling Leases Inducing File Descriptor Exhaustion Under Event-Loop Interruption 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 DriftUnscoped Connection Checkouts and Dangling Leases Inducing File Descriptor Exhaustion Under Event-Loop InterruptionCritical
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 use 'await using' (Explicit Resource Management) when reserving dedicated connections or transactions from native SQL pools.

Engineers MUST ALWAYS use 'await using' (Explicit Resource Management) when reserving dedicated connections or transactions from native SQL pools.

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 implement '[Symbol.asyncDispose]()' on all wrapper classes, unit-of-work abstractions, or repositories retaining native SQL client handles.

Engineers MUST implement '[Symbol.asyncDispose]()' on all wrapper classes, unit-of-work abstractions, or repositories retaining native SQL client handles.

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 NOT rely on runtime garbage collection, FinalizationRegistry, or implicit idle timeouts to release reserved database sockets.

Engineers MUST NOT rely on runtime garbage collection, FinalizationRegistry, or implicit idle timeouts to release reserved database sockets.

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

Code MUST bind process-level POSIX signals ('SIGINT', 'SIGTERM') to an idempotent, bounded pool draining routine using 'sql.close()'.

Code MUST bind process-level POSIX signals ('SIGINT', 'SIGTERM') to an idempotent, bounded pool draining routine using 'sql.close()'.

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

Services MUST ensure transactional blocks execute rollbacks inside '[Symbol.asyncDispose]()' if not explicitly committed prior to scope termination.

Services MUST ensure transactional blocks execute rollbacks inside '[Symbol.asyncDispose]()' if not explicitly committed prior to scope termination.

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

Components NEVER execute raw 'BEGIN'/'COMMIT' statements across unbound asynchronous boundaries without RAII-guaranteed disposal.

Components NEVER execute raw 'BEGIN'/'COMMIT' statements across unbound asynchronous boundaries without RAII-guaranteed disposal.

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 SQL Connection Pool RAII and Finalizer Standard critical for AI coding assistants?

Enforces deterministic connection release and explicit lifecycle management on Bun 1.2 native SQL connection pools using the ECMAScript Explicit Resource Management (RAII) protocol. Guarantees that checkout sockets, reserved clients, and multi-statement transactions release pooled file descriptors immediately upon scope exit, preventing kernel socket exhaustion during unhandled rejections or sudden POSIX process termination signals. 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 (Unscoped Connection Checkouts and Dangling Leases Inducing File Descriptor Exhaustion Under Event-Loop Interruption) 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