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

Bun 1.2 Clustered Worker WebSocket Hibernation Isolation Standard

Enforces zero-memory-leak WebSocket lifecycle management in Bun 1.2+ multi-worker cluster deployments by mandating the native C++ WebSocket hibernation API over in-memory socket retaining patterns. Ensures that worker threads do not retain JavaScript references to idle sockets, delegate cross-worker fanout to native Bun PubSub or an external broker rather than IPC socket transfer, and isolate worker memory footprints to achieve deterministic resource reclaiming.

Prohibited Anti-Pattern: Retaining JavaScript WebSocket References in Worker Event Loops Breaking Bun Native Hibernation and PubSub Isolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Clustered Worker WebSocket Hibernation Isolation Standard - Enforces zero-memory-leak WebSocket lifecycle management in Bun 1.2+ multi-worker cluster deployments by mandating the native C++ WebSocket hibernation API over in-memory socket retaining patterns. Ensures that worker threads do not retain JavaScript references to idle sockets, delegate cross-worker fanout to native Bun PubSub or an external broker rather than IPC socket transfer, and isolate worker memory footprints to achieve deterministic resource reclaiming.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}, workers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-clustered-worker-websocket-hibernation-isolation-standard"
---

# Bun 1.2 Clustered Worker WebSocket Hibernation Isolation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining JavaScript WebSocket References in Worker Event Loops Breaking Bun Native Hibernation and PubSub Isolation

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Clustered Worker WebSocket Hibernation Isolation Standard. Mandate native socket hibernation via `server.upgrade(req, { data })`, forbid retaining JavaScript references to `ServerWebSocket` instances in worker-local arrays or maps, require use of Bun's native C++ PubSub (`server.publish`) or clustered external channels for fanout, and ensure workers terminate connections cleanly without memory retention or thread stalls.

## Strict Guidelines
- Engineers MUST ALWAYS leverage Bun's native WebSocket hibernation API within `Bun.serve({ websocket: { ... } })`, attaching per-connection state exclusively via the `data` property during `server.upgrade(req, { data })`.
- Engineers MUST NOT store active `ServerWebSocket` instances in JavaScript heap collections (e.g., `Map<string, ServerWebSocket>`, `Set<ServerWebSocket>`, or module-level arrays), as this prevents the C++ engine from deallocating socket memory during idle periods.
- Services MUST utilize Bun's native topic-based pub/sub engine (`ws.subscribe(topic)`, `ws.unsubscribe(topic)`, `server.publish(topic, message)`) for broadcasting across connections within a worker rather than iterating over JavaScript socket lists.
- Engineers MUST NOT attempt to transfer raw `ServerWebSocket` objects or file descriptors across cluster worker boundaries via `worker.postMessage()`; cross-worker synchronization MUST use external message brokers (e.g., Redis Streams, DragonFly) or atomic inter-process publish mechanisms.
- Code SHOULD define strict schema validation for the `WebSocketData` interface passed into `server.upgrade()` and avoid storing large payloads, long-lived promises, or circular references in socket metadata.
- Components NEVER attach custom event listeners to individual `ServerWebSocket` instances dynamically; all lifecycle hooks (`open`, `message`, `close`, `drain`, `ping`, `pong`) MUST remain statically configured on the top-level `websocket` handler passed to `Bun.serve()`.

## Bad vs Good Implementations
### Anti-Pattern: Manual Socket Tracking with JavaScript Map Preventing Native Hibernation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining references to `ServerWebSocket` instances inside `activeClients` prevents Bun's internal C++ layer from hibernating the connection. During idle periods, the JavaScript engine cannot garbage collect or evict memory, resulting in high RSS under tens of thousands of concurrent connections and causing cross-worker synchronization failures.
```typescript
import type { ServerWebSocket } from 'bun';

// ANTI-PATTERN: Heap retention defeats Bun's native hibernation
const activeClients = new Map<string, ServerWebSocket>();

Bun.serve({
  port: 8080,
  fetch(req, server) {
    const clientId = new URL(req.url).searchParams.get('id') ?? crypto.randomUUID();
    const upgraded = server.upgrade(req, { data: { clientId } });
    return upgraded ? undefined : new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    open(ws: ServerWebSocket<{ clientId: string }>) {
      // Storing the socket keeps JS references alive; prevents C++ deallocation
      activeClients.set(ws.data.clientId, ws);
    },
    message(ws, message) {
      // Iterating JS map introduces high GC pressure during fanouts
      for (const [id, client] of activeClients.entries()) {
        if (id !== ws.data.clientId) {
          client.send(message);
        }
      }
    },
    close(ws: ServerWebSocket<{ clientId: string }>) {
      activeClients.delete(ws.data.clientId);
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: The production-ready standard uses Bun's built-in topic subscription model (`ws.subscribe`, `ws.publish`). Zero references to `ws` are maintained in JavaScript memory, allowing Bun to put idle connections into low-footprint C++ hibernation. Memory consumption scales linearly with active socket transmission rather than concurrent idle connections.
```typescript
import type { ServerWebSocket } from 'bun';

interface SocketData {
  readonly clientId: string;
  readonly channels: readonly string[];
}

const BROADCAST_ROOM = 'global-events';

Bun.serve<SocketData>({
  port: 8080,
  fetch(req, server) {
    const url = new URL(req.url);
    const clientId = url.searchParams.get('id') ?? crypto.randomUUID();
    const success = server.upgrade(req, {
      data: {
        clientId,
        channels: [BROADCAST_ROOM]
      }
    });
    return success ? undefined : new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    // Native hibernation enabled: zero JS references retained outside the event loop
    open(ws: ServerWebSocket<SocketData>) {
      for (const channel of ws.data.channels) {
        ws.subscribe(channel);
      }
    },
    message(ws: ServerWebSocket<SocketData>, message: string | Buffer) {
      // Zero-copy C++ native fanout without iterating JS collections
      ws.publish(BROADCAST_ROOM, message);
    },
    drain(ws: ServerWebSocket<SocketData>) {
      // Handle backpressure without storing pending queue in JS heap
      ws.cork(() => {
        // Resume writing after socket buffer clears
      });
    },
    close(ws: ServerWebSocket<SocketData>) {
      for (const channel of ws.data.channels) {
        ws.unsubscribe(channel);
      }
    }
  }
});
```

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 WebSocket Hibernation Isolation Standard

Bun 1.2 Clustered Worker WebSocket Hibernation Isolation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-memory-leak WebSocket lifecycle management in Bun 1.2+ multi-worker cluster deployments by mandating the native C++ WebSocket hibernation API over in-memory socket retaining patterns. Ensures that worker threads do not retain JavaScript references to idle sockets, delegate cross-worker fanout to native Bun PubSub or an external broker rather than IPC socket transfer, and isolate worker memory footprints to achieve deterministic resource reclaiming. 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: Retaining JavaScript WebSocket References in Worker Event Loops Breaking Bun Native Hibernation and PubSub Isolation 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 DriftRetaining JavaScript WebSocket References in Worker Event Loops Breaking Bun Native Hibernation and PubSub IsolationCritical
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 leverage Bun's native WebSocket hibernation API within `Bun.serve({ websocket

Engineers MUST ALWAYS leverage Bun's native WebSocket hibernation API within `Bun.serve({ websocket: { ... } })`, attaching per-connection state exclusively via the `data` property during `server.upgrade(req, { data })`.

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 store active `ServerWebSocket` instances in JavaScript heap collections (e.g., `Map<string, ServerWebSocket>`, `Set<ServerWebSocket>`, or module-level arrays), as this prevents the C++ engine from deallocating socket memory during idle periods.

Engineers MUST NOT store active `ServerWebSocket` instances in JavaScript heap collections (e.g., `Map<string, ServerWebSocket>`, `Set<ServerWebSocket>`, or module-level arrays), as this prevents the C++ engine from deallocating socket memory during idle periods.

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 utilize Bun's native topic-based pub/sub engine (`ws.subscribe(topic)`, `ws.unsubscribe(topic)`, `server.publish(topic, message)`) for broadcasting across connections within a worker rather than iterating over JavaScript socket lists.

Services MUST utilize Bun's native topic-based pub/sub engine (`ws.subscribe(topic)`, `ws.unsubscribe(topic)`, `server.publish(topic, message)`) for broadcasting across connections within a worker rather than iterating over JavaScript socket lists.

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

Engineers MUST NOT attempt to transfer raw `ServerWebSocket` objects or file descriptors across cluster worker boundaries via `worker.postMessage()`

Engineers MUST NOT attempt to transfer raw `ServerWebSocket` objects or file descriptors across cluster worker boundaries via `worker.postMessage()`; cross-worker synchronization MUST use external message brokers (e.g., Redis Streams, DragonFly) or atomic inter-process publish mechanisms.

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

Code SHOULD define strict schema validation for the `WebSocketData` interface passed into `server.upgrade()` and avoid storing large payloads, long-lived promises, or circular references in socket metadata.

Code SHOULD define strict schema validation for the `WebSocketData` interface passed into `server.upgrade()` and avoid storing large payloads, long-lived promises, or circular references in socket metadata.

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 attach custom event listeners to individual `ServerWebSocket` instances dynamically

Components NEVER attach custom event listeners to individual `ServerWebSocket` instances dynamically; all lifecycle hooks (`open`, `message`, `close`, `drain`, `ping`, `pong`) MUST remain statically configured on the top-level `websocket` handler passed to `Bun.serve()`.

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 WebSocket Hibernation Isolation Standard critical for AI coding assistants?

Enforces zero-memory-leak WebSocket lifecycle management in Bun 1.2+ multi-worker cluster deployments by mandating the native C++ WebSocket hibernation API over in-memory socket retaining patterns. Ensures that worker threads do not retain JavaScript references to idle sockets, delegate cross-worker fanout to native Bun PubSub or an external broker rather than IPC socket transfer, and isolate worker memory footprints to achieve deterministic resource reclaiming. 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 (Retaining JavaScript WebSocket References in Worker Event Loops Breaking Bun Native Hibernation and PubSub Isolation) 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