This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-cluster-websocket-zero-copy-handoff-production-standard

Bun 1.2 Native Cluster WebSocket Zero-Copy Socket Handoff & Backpressure Architecture

Enforces deterministic, memory-safe WebSocket socket handoff and worker load distribution across multi-core Bun cluster architectures. Prevents intermediate heap buffer cloning, frame desynchronization, and silent frame drops during cross-worker migration under saturation by mandating zero-copy transfer lists and native backpressure drain lifecycle hooks.

Prohibited Anti-Pattern: Heap-Cloned WebSocket IPC Handoff Without Backpressure Drain Synchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Cluster WebSocket Zero-Copy Socket Handoff & Backpressure Architecture - Enforces deterministic, memory-safe WebSocket socket handoff and worker load distribution across multi-core Bun cluster architectures. Prevents intermediate heap buffer cloning, frame desynchronization, and silent frame drops during cross-worker migration under saturation by mandating zero-copy transfer lists and native backpressure drain lifecycle hooks.
globs: src/**/*.ts, server/**/*.ts, workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-cluster-websocket-zero-copy-handoff-production-standard"
---

# Bun 1.2 Native Cluster WebSocket Zero-Copy Socket Handoff & Backpressure Architecture

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Heap-Cloned WebSocket IPC Handoff Without Backpressure Drain Synchronization

## System Constraints
You are a Principal Software Architect enforcing the Bun 1.2 Native Cluster WebSocket Zero-Copy Handoff Standard. You must reject any architecture that re-buffers WebSocket frames through standard JSON-serialized IPC, fails to inspect TCP backpressure prior to worker handoff, or performs duplicate allocations on payload migrations across worker threads. Ensure strict compliance with Bun's native socket handles, zero-copy ArrayBuffer transferables, and backpressured drain synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS verify backpressure states via `ws.getBufferedAmount()` before triggering worker migration or frame relay to prevent unmonitored memory ballooning.
- Engineers MUST NOT serialize binary WebSocket frames into Node.js Buffers or JSON payloads across IPC boundaries; zero-copy ArrayBuffer transfer lists or native handle transfers must be utilized exclusively.
- Code SHOULD implement native `drain(ws)` handlers in `Bun.serve` to resume throttled pipelines when cross-worker channel saturation drops below the configured low-water mark.
- Services MUST isolate connection state metadata from payload buffers during worker handoff, executing atomic handshakes to avoid duplicate socket ownership across processes.
- Components NEVER drop or close active client sockets during cluster rebalancing; worker nodes must complete socket handoff or cleanly backpressure clients using WebSocket close code 1013 (Try Again Later) under absolute queue saturation.

## Bad vs Good Implementations
### Cross-Worker Socket Handoff and Frame Relay

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Converting binary buffers into JS arrays and serializing over standard IPC creates high garbage collection pressure, causes frame re-buffering, and ignores socket backpressure, resulting in OOM crashes under cluster saturation.
```typescript
import { type ServerWebSocket } from 'bun';

// ANTI-PATTERN: Heap-cloning payloads, JSON IPC re-buffering, and ignoring backpressure
export function relayToWorker(ws: ServerWebSocket<any>, worker: Worker, payload: Uint8Array) {
  // Incurring deep copy into V8/JSC heap via standard object packaging
  const message = {
    clientId: ws.data.id,
    // Serializing array causes massive heap allocations under high throughput
    data: Array.from(payload),
  };
  
  // No check on ws.getBufferedAmount() or worker queue pressure
  worker.postMessage(message);
  
  // Blind transmission ignores client-side socket saturation
  ws.send(payload);
}
```

#### Production Standard (Correct)
> **Standard**: Transfers ArrayBuffer ownership directly across threads using transfer lists, eliminating heap allocations, and strictly enforces backpressure checking via getBufferedAmount() before queuing work.
```typescript
import { type ServerWebSocket } from 'bun';

interface SocketState {
  id: string;
  isMigrating: boolean;
}

const HIGH_WATER_MARK_BYTES = 1024 * 1024; // 1MB

// PRODUCTION PATTERN: Zero-copy transferables, explicit backpressure verification
export function relayToWorkerZeroCopy(
  ws: ServerWebSocket<SocketState>,
  worker: Worker,
  payload: Uint8Array
): boolean {
  // 1. Guard against local TCP socket backpressure
  if (ws.getBufferedAmount() > HIGH_WATER_MARK_BYTES) {
    return false; // Backpressure active: caller must wait for drain
  }

  // 2. Extract underlying ArrayBuffer for zero-copy ownership transfer
  const buffer = payload.buffer.slice(
    payload.byteOffset,
    payload.byteOffset + payload.byteLength
  );

  // 3. Dispatch to worker transferring buffer ownership without heap duplication
  worker.postMessage(
    {
      type: 'SOCKET_FRAME',
      clientId: ws.data.id,
      byteLength: buffer.byteLength,
      payload: buffer
    },
    [buffer] // Zero-copy transfer list: memory is detached from caller thread
  );

  return true;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Native Cluster WebSocket Zero-Copy Socket Handoff & Backpressure Architecture

Bun 1.2 Native Cluster WebSocket Zero-Copy Socket Handoff & Backpressure Architecture defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic, memory-safe WebSocket socket handoff and worker load distribution across multi-core Bun cluster architectures. Prevents intermediate heap buffer cloning, frame desynchronization, and silent frame drops during cross-worker migration under saturation by mandating zero-copy transfer lists and native backpressure drain lifecycle hooks. 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: Heap-Cloned WebSocket IPC Handoff Without Backpressure Drain Synchronization 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 DriftHeap-Cloned WebSocket IPC Handoff Without Backpressure Drain SynchronizationCritical
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 verify backpressure states via `ws.getBufferedAmount()` before triggering worker migration or frame relay to prevent unmonitored memory ballooning.

Engineers MUST ALWAYS verify backpressure states via `ws.getBufferedAmount()` before triggering worker migration or frame relay to prevent unmonitored memory ballooning.

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 serialize binary WebSocket frames into Node.js Buffers or JSON payloads across IPC boundaries

Engineers MUST NOT serialize binary WebSocket frames into Node.js Buffers or JSON payloads across IPC boundaries; zero-copy ArrayBuffer transfer lists or native handle transfers must be utilized exclusively.

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 implement native `drain(ws)` handlers in `Bun.serve` to resume throttled pipelines when cross-worker channel saturation drops below the configured low-water mark.

Code SHOULD implement native `drain(ws)` handlers in `Bun.serve` to resume throttled pipelines when cross-worker channel saturation drops below the configured low-water mark.

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 isolate connection state metadata from payload buffers during worker handoff, executing atomic handshakes to avoid duplicate socket ownership across processes.

Services MUST isolate connection state metadata from payload buffers during worker handoff, executing atomic handshakes to avoid duplicate socket ownership across processes.

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 drop or close active client sockets during cluster rebalancing

Components NEVER drop or close active client sockets during cluster rebalancing; worker nodes must complete socket handoff or cleanly backpressure clients using WebSocket close code 1013 (Try Again Later) under absolute queue saturation.

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 Cluster WebSocket Zero-Copy Socket Handoff & Backpressure Architecture critical for AI coding assistants?

Enforces deterministic, memory-safe WebSocket socket handoff and worker load distribution across multi-core Bun cluster architectures. Prevents intermediate heap buffer cloning, frame desynchronization, and silent frame drops during cross-worker migration under saturation by mandating zero-copy transfer lists and native backpressure drain lifecycle hooks. 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 (Heap-Cloned WebSocket IPC Handoff Without Backpressure Drain Synchronization) 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