This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-explicit-resource-management-db-pool-invariant

Bun 1.2 Explicit Resource Management Disposable Database Pool Invariant

Enforces deterministic reclamation of acquired database connections and transactions using TC39 Explicit Resource Management (`using` and `await using` declarations) in Bun 1.2+. Guarantees that connection handles and transactional locks are disposed of synchronously or asynchronously upon scope exit, completely eliminating socket starvation and connection pool exhaustion caused by unhandled rejections, early returns, or uncaught exceptions.

Prohibited Anti-Pattern: Manual Connection Release via Ad-Hoc Try/Finally Leading to Leaked Sockets on Premature Rejection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Explicit Resource Management Disposable Database Pool Invariant - Enforces deterministic reclamation of acquired database connections and transactions using TC39 Explicit Resource Management (`using` and `await using` declarations) in Bun 1.2+. Guarantees that connection handles and transactional locks are disposed of synchronously or asynchronously upon scope exit, completely eliminating socket starvation and connection pool exhaustion caused by unhandled rejections, early returns, or uncaught exceptions.
globs: src/**/*.ts, server/**/*.ts, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-explicit-resource-management-db-pool-invariant"
---

# Bun 1.2 Explicit Resource Management Disposable Database Pool Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Manual Connection Release via Ad-Hoc Try/Finally Leading to Leaked Sockets on Premature Rejection

## System Constraints
You are a Principal Backend Architect enforcing strict connection lifecycle management in Bun 1.2+ runtimes. You must enforce TC39 Explicit Resource Management (`Symbol.dispose` and `Symbol.asyncDispose`) for all database client checkouts, transactions, and statement lifecycles. Forbid manual client release calls (`client.release()`, `conn.close()`) trapped in fallible try/finally blocks where early bailouts, cancellations, or unhandled promise race rejections leave orphaned connections in the pool.

## Strict Guidelines
- Engineers MUST ALWAYS wrap acquired pool clients in an `await using` or `using` declaration implementing `[Symbol.asyncDispose]` or `[Symbol.dispose]`.
- Engineers MUST NOT manually call `.release()`, `.close()`, or `.destroy()` within standard application execution flows.
- Code SHOULD polyfill `Symbol.asyncDispose` / `Symbol.dispose` via `@types/node` or TypeScript 5.2+ compiler flags (`lib: ["esnext", "dom"]`) to ensure runtime symbol availability in Bun 1.2.
- Services MUST implement transactional boundaries using disposable transaction scopes that automatically trigger a `ROLLBACK` on unhandled errors before returning the client to the pool.
- Components NEVER store disposable client references in outer lexical scopes or singleton caches beyond the synchronous or asynchronous lexical block of acquisition.

## Bad vs Good Implementations
### Database Client Checkout and Automatic Disposal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Manual try/finally blocks are prone to connection leaks when nested exceptions occur before entering the try block, during client initialization, or when developers forget the finally block altogether under refactoring.
```typescript
import { Pool } from 'pg';

const pool = new Pool();

export async function fetchUserOrders(userId: string) {
  const client = await pool.connect();
  try {
    // If transformData throws or a cancellation aborts here,
    // client release can be bypassed if unhandled errors occur before try block
    const res = await client.query('SELECT * FROM orders WHERE user_id = $1', [userId]);
    return res.rows;
  } finally {
    client.release();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Using `await using client = await acquireDisposableClient()` leverages Bun 1.2 native TC39 Explicit Resource Management to guarantee immediate client release back to the pool as soon as the block exits, even on unhandled promise rejections or runtime panics.
```typescript
import { Pool, type PoolClient } from 'pg';

const pool = new Pool();

interface AsyncDisposableClient extends PoolClient, AsyncDisposable {}

export async function acquireDisposableClient(): Promise<AsyncDisposableClient> {
  const client = await pool.connect();
  return Object.assign(client, {
    async [Symbol.asyncDispose]() {
      client.release();
    }
  });
}

export async function fetchUserOrders(userId: string) {
  // Deterministically returned to pool when scope exits (return or throw)
  await using client = await acquireDisposableClient();
  const res = await client.query('SELECT * FROM orders WHERE user_id = $1', [userId]);
  return res.rows;
}
```

### Atomic Disposable Transaction with Rollback-on-Throw Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Manual transaction control locks the database file/table indefinitely if unhandled process signals, unwound stacks, or unexpected synchronous panics intercept the flow before explicit ROLLBACK.
```typescript
import { Database } from 'bun:sqlite';

const db = new Database('app.db');

export function executeTransfer(fromId: number, toId: number, amount: number) {
  db.run('BEGIN TRANSACTION');
  try {
    db.run('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, fromId]);
    if (amount <= 0) throw new Error('Invalid transfer amount');
    db.run('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, toId]);
    db.run('COMMIT');
  } catch (err) {
    db.run('ROLLBACK');
    throw err;
  }
}
```

#### Production Standard (Correct)
> **Standard**: The Disposable pattern encapsulates the transaction boundary. Unless explicitly committed, exiting lexical scope triggers `[Symbol.dispose]()` which executes a safe rollback, ensuring zero connection or table lock leakage.
```typescript
import { Database } from 'bun:sqlite';

const db = new Database('app.db');

class DisposableTransaction implements Disposable {
  private committed = false;

  constructor(private readonly connection: Database) {
    this.connection.run('BEGIN IMMEDIATE');
  }

  commit(): void {
    this.connection.run('COMMIT');
    this.committed = true;
  }

  [Symbol.dispose](): void {
    if (!this.committed) {
      this.connection.run('ROLLBACK');
    }
  }
}

export function executeTransfer(fromId: number, toId: number, amount: number) {
  using tx = new DisposableTransaction(db);
  
  db.run('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, fromId]);
  if (amount <= 0) throw new Error('Invalid transfer amount');
  db.run('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, toId]);
  
  tx.commit();
  // If tx.commit() was not reached due to any throw, Symbol.dispose executes ROLLBACK automatically
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Explicit Resource Management Disposable Database Pool Invariant

Bun 1.2 Explicit Resource Management Disposable Database Pool Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic reclamation of acquired database connections and transactions using TC39 Explicit Resource Management (`using` and `await using` declarations) in Bun 1.2+. Guarantees that connection handles and transactional locks are disposed of synchronously or asynchronously upon scope exit, completely eliminating socket starvation and connection pool exhaustion caused by unhandled rejections, early returns, or uncaught exceptions. 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: Manual Connection Release via Ad-Hoc Try/Finally Leading to Leaked Sockets on Premature Rejection 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 DriftManual Connection Release via Ad-Hoc Try/Finally Leading to Leaked Sockets on Premature RejectionCritical
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 wrap acquired pool clients in an `await using` or `using` declaration implementing `[Symbol.asyncDispose]` or `[Symbol.dispose]`.

Engineers MUST ALWAYS wrap acquired pool clients in an `await using` or `using` declaration implementing `[Symbol.asyncDispose]` or `[Symbol.dispose]`.

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 manually call `.release()`, `.close()`, or `.destroy()` within standard application execution flows.

Engineers MUST NOT manually call `.release()`, `.close()`, or `.destroy()` within standard application execution flows.

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 polyfill `Symbol.asyncDispose` / `Symbol.dispose` via `@types/node` or TypeScript 5.2+ compiler flags (`lib

Code SHOULD polyfill `Symbol.asyncDispose` / `Symbol.dispose` via `@types/node` or TypeScript 5.2+ compiler flags (`lib: ["esnext", "dom"]`) to ensure runtime symbol availability in Bun 1.2.

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 implement transactional boundaries using disposable transaction scopes that automatically trigger a `ROLLBACK` on unhandled errors before returning the client to the pool.

Services MUST implement transactional boundaries using disposable transaction scopes that automatically trigger a `ROLLBACK` on unhandled errors before returning the client to the pool.

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 store disposable client references in outer lexical scopes or singleton caches beyond the synchronous or asynchronous lexical block of acquisition.

Components NEVER store disposable client references in outer lexical scopes or singleton caches beyond the synchronous or asynchronous lexical block of acquisition.

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 Explicit Resource Management Disposable Database Pool Invariant critical for AI coding assistants?

Enforces deterministic reclamation of acquired database connections and transactions using TC39 Explicit Resource Management (`using` and `await using` declarations) in Bun 1.2+. Guarantees that connection handles and transactional locks are disposed of synchronously or asynchronously upon scope exit, completely eliminating socket starvation and connection pool exhaustion caused by unhandled rejections, early returns, or uncaught exceptions. 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 (Manual Connection Release via Ad-Hoc Try/Finally Leading to Leaked Sockets on Premature Rejection) 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