This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-postgres-direct-socket-pipelining-production-standard

Bun 1.2 Native PostgreSQL Direct-Socket Pipelining Standard

Enforces non-blocking transactional query pipelining over unbuffered native TCP stream abstractions in Bun 1.2. Eliminates connection pool starvation during high-concurrency microservice fan-outs by replacing sequential pool checkouts with native binary-level socket multiplexing.

Prohibited Anti-Pattern: Exhausting Connection Pools via Sequential Client Checkouts in High-Concurrency Fan-Outs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native PostgreSQL Direct-Socket Pipelining Standard - Enforces non-blocking transactional query pipelining over unbuffered native TCP stream abstractions in Bun 1.2. Eliminates connection pool starvation during high-concurrency microservice fan-outs by replacing sequential pool checkouts with native binary-level socket multiplexing.
globs: src/**/*.ts, services/**/*.ts, lib/db/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-postgres-direct-socket-pipelining-production-standard"
---

# Bun 1.2 Native PostgreSQL Direct-Socket Pipelining Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Exhausting Connection Pools via Sequential Client Checkouts in High-Concurrency Fan-Outs

## System Constraints
You are a Principal Software Architect enforcing the Bun 1.2 Native PostgreSQL Direct-Socket Pipelining Standard. Mandate native unbuffered TCP socket multiplexing using Bun's built-in SQL interface instead of traditional Node-style pooled connection checkouts. Reject sequential round-trips in fan-out scenarios and ensure strict transaction boundaries via scoped socket reservation.

## Strict Guidelines
- Engineers MUST ALWAYS use Bun 1.2's native PostgreSQL driver (`import { SQL } from 'bun'`) rather than external Node-based drivers (`pg`, `postgres.js`) in Bun runtimes.
- Engineers MUST NOT acquire individual client checkout connections sequentially within microservice fan-out loops, as this triggers connection starvation under concurrent load.
- Queries executing in fan-out workloads MUST be dispatched concurrently through Bun's native socket pipelining engine via `Promise.all` without manual connection reservation.
- Services MUST reserve dedicated direct-socket instances via `await sql.reserve()` strictly when atomicity requires multi-statement transaction state (`BEGIN` ... `COMMIT`), and MUST release them inside an unconditional `finally` block.
- Components NEVER execute raw string interpolations; queries MUST be constructed using Bun's native tagged template literals (`sql`...``) to guarantee binary parameter serialization.

## Bad vs Good Implementations
### Mitigating Fan-out Connection Starvation via Native Socket Pipelining

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterative connection checkout against a fixed pool exhausts file descriptors and socket pools during fan-out spikes, introducing head-of-line blocking and millisecond-level tail latency inflation.
```typescript
import { Pool } from 'pg';

const pool = new Pool({ max: 20 });

export async function handleFanoutBad(entityIds: string[]): Promise<Record<string, unknown>[]> {
  // Anti-Pattern: Consumes pooled connections sequentially per loop iteration.
  // Under microservice fan-out, pool exhaustion blocks event loop turns.
  const results: Record<string, unknown>[] = [];
  for (const id of entityIds) {
    const client = await pool.connect();
    try {
      const res = await client.query('SELECT * FROM entities WHERE id = $1', [id]);
      results.push(res.rows[0]);
    } finally {
      client.release();
    }
  }
  return results;
}
```

#### Production Standard (Correct)
> **Standard**: Bun's native SQL client pushes concurrent query packets directly to PostgreSQL's native socket buffer using wire-level pipelining, bypassing pool checkout bottlenecks and reducing latency to a single amortized network round trip.
```typescript
import { SQL } from 'bun';

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

export async function handleFanoutGood(entityIds: string[]): Promise<unknown[]> {
  // Production Invariant: Direct-socket pipelining sends queries back-to-back
  // over the unbuffered TCP connection without waiting for individual round-trips.
  return await Promise.all(
    entityIds.map((id) => sql`SELECT * FROM entities WHERE id = ${id}`)
  );
}
```

### Scoped Transaction Isolation with Guaranteed Native Socket Release

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Multiplexed streams cannot guarantee transaction isolation when statements are sent across shared connections without reserving the underlying socket, leading to race conditions and corrupt transactions.
```typescript
import { SQL } from 'bun';
const sql = new SQL(process.env.DATABASE_URL!);

export async function transferBad(senderId: string, receiverId: string, amount: number) {
  // Anti-Pattern: Issuing BEGIN directly over multiplexed pool without reservation
  // interleaves statements from other concurrent requests on the same physical socket.
  await sql`BEGIN`;
  await sql`UPDATE accounts SET balance = balance - ${amount} WHERE id = ${senderId}`;
  await sql`UPDATE accounts SET balance = balance + ${amount} WHERE id = ${receiverId}`;
  await sql`COMMIT`;
}
```

#### Production Standard (Correct)
> **Standard**: Socket reservation temporarily binds a discrete TCP connection to the transactional context, preventing multiplexed pollution and guaranteeing transactional integrity.
```typescript
import { SQL } from 'bun';
const sql = new SQL(process.env.DATABASE_URL!);

export async function transferGood(senderId: string, receiverId: string, amount: number): Promise<void> {
  // Production Invariant: Scoped reservation dedicates the socket for stateful isolation
  // and returns it to the multiplexer immediately via try/finally.
  const reserved = await sql.reserve();
  try {
    await reserved`BEGIN`;
    await reserved`UPDATE accounts SET balance = balance - ${amount} WHERE id = ${senderId}`;
    await reserved`UPDATE accounts SET balance = balance + ${amount} WHERE id = ${receiverId}`;
    await reserved`COMMIT`;
  } catch (error) {
    await reserved`ROLLBACK`;
    throw error;
  } finally {
    reserved.release();
  }
}
```

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 PostgreSQL Direct-Socket Pipelining Standard

Bun 1.2 Native PostgreSQL Direct-Socket Pipelining Standard defines an industrial-grade behavioral standard for backend engineering. Enforces non-blocking transactional query pipelining over unbuffered native TCP stream abstractions in Bun 1.2. Eliminates connection pool starvation during high-concurrency microservice fan-outs by replacing sequential pool checkouts with native binary-level socket multiplexing. 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: Exhausting Connection Pools via Sequential Client Checkouts in High-Concurrency Fan-Outs 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 DriftExhausting Connection Pools via Sequential Client Checkouts in High-Concurrency Fan-OutsCritical
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 Bun 1.2's native PostgreSQL driver (`import { SQL } from 'bun'`) rather than external Node-based drivers (`pg`, `postgres.js`) in Bun runtimes.

Engineers MUST ALWAYS use Bun 1.2's native PostgreSQL driver (`import { SQL } from 'bun'`) rather than external Node-based drivers (`pg`, `postgres.js`) in Bun runtimes.

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 acquire individual client checkout connections sequentially within microservice fan-out loops, as this triggers connection starvation under concurrent load.

Engineers MUST NOT acquire individual client checkout connections sequentially within microservice fan-out loops, as this triggers connection starvation under concurrent load.

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

Queries executing in fan-out workloads MUST be dispatched concurrently through Bun's native socket pipelining engine via `Promise.all` without manual connection reservation.

Queries executing in fan-out workloads MUST be dispatched concurrently through Bun's native socket pipelining engine via `Promise.all` without manual connection reservation.

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 reserve dedicated direct-socket instances via `await sql.reserve()` strictly when atomicity requires multi-statement transaction state (`BEGIN` ... `COMMIT`), and MUST release them inside an unconditional `finally` block.

Services MUST reserve dedicated direct-socket instances via `await sql.reserve()` strictly when atomicity requires multi-statement transaction state (`BEGIN` ... `COMMIT`), and MUST release them inside an unconditional `finally` block.

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 raw string interpolations

Components NEVER execute raw string interpolations; queries MUST be constructed using Bun's native tagged template literals (`sql`...``) to guarantee binary parameter serialization.

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 PostgreSQL Direct-Socket Pipelining Standard critical for AI coding assistants?

Enforces non-blocking transactional query pipelining over unbuffered native TCP stream abstractions in Bun 1.2. Eliminates connection pool starvation during high-concurrency microservice fan-outs by replacing sequential pool checkouts with native binary-level socket multiplexing. 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 (Exhausting Connection Pools via Sequential Client Checkouts in High-Concurrency Fan-Outs) 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