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

Bun 1.2 Native WebSocket Server Hibernation State Retention Standard

Bun 1.2 native WebSocket server hibernation achieves extreme connection density by garbage collecting idle JavaScriptCore connection wrappers and persisting socket descriptors at the native C++/kernel level. Storing active ServerWebSocket references in JavaScript heaps (such as Maps or Sets) defeats hibernation, leading to rapid memory bloat and process termination under high concurrency. All connection lifecycle state must be bound to the native upgrade context and mutated solely via ws.data, while fan-out messaging must leverage native C++ topic pub/sub.

Prohibited Anti-Pattern: Retaining JavaScript ServerWebSocket references in module-scoped collections and manually iterating sockets for broadcasting instead of native hibernation and topic pub/sub.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Server Hibernation State Retention Standard - Bun 1.2 native WebSocket server hibernation achieves extreme connection density by garbage collecting idle JavaScriptCore connection wrappers and persisting socket descriptors at the native C++/kernel level. Storing active ServerWebSocket references in JavaScript heaps (such as Maps or Sets) defeats hibernation, leading to rapid memory bloat and process termination under high concurrency. All connection lifecycle state must be bound to the native upgrade context and mutated solely via ws.data, while fan-out messaging must leverage native C++ topic pub/sub.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-hibernation-state-retention-standard"
---

# Bun 1.2 Native WebSocket Server Hibernation State Retention Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining JavaScript ServerWebSocket references in module-scoped collections and manually iterating sockets for broadcasting instead of native hibernation and topic pub/sub.

## System Constraints
You are a Principal Systems Architect enforcing the Bun 1.2 Native WebSocket Server Hibernation Standard. Mandate that all WebSocket implementations exploit Bun's native C++ hibernation architecture. Strictly forbid storing ServerWebSocket instances in application-level collections (e.g., Set, Map, Array, or closure state). Enforce connection state encapsulation strictly within the `ws.data` context passed during `server.upgrade()`, and require native topic pub/sub (`ws.subscribe()`, `server.publish()`) for high-density broadcast messaging.

## Strict Guidelines
- Engineers MUST ALWAYS initialize socket state via the `data` option of `server.upgrade(request, { data })` during HTTP upgrade handling.
- Engineers MUST NOT store `ServerWebSocket` instances in module-level `Map`, `Set`, `Array`, or object properties, as retaining JS references prevents V8/JSC garbage collection of idle sockets.
- Engineers MUST ALWAYS execute broadcasts using Bun's native topic pub/sub primitives (`server.publish(topic, message)` and `ws.subscribe(topic)`) rather than looping over socket handles.
- Code SHOULD define a strictly typed, memory-compact interface for `ws.data` containing only essential primitives, avoiding deep object graphs or uncollected buffer references.
- Services MUST enable `backpressure: true` or inspect `ws.getBufferedAmount()` before sending high-throughput bursts to hibernating connections.
- Components NEVER attach custom event listeners to dynamic socket instances; all hooks MUST reside globally in the `Bun.serve({ websocket: { open, message, close, drain } })` declaration.

## Bad vs Good Implementations
### Module-Level Socket Registry vs. Native Hibernation Topic Pub/Sub

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing ServerWebSocket objects inside `socketRegistry` keeps strong JavaScript references alive. Bun cannot hibernate idle sockets out of the JavaScriptCore heap into native kernel space. Under millions of connections, this results in massive heap allocation, severe GC pauses, and heap exhaustion.
```typescript
import { ServerWebSocket } from "bun";

interface ClientState {
  userId: string;
  room: string;
}

// ANTI-PATTERN: Retaining JS references prevents JSC from deallocating idle wrappers,
// completely disabling Bun's native hibernation engine and causing OOM at scale.
const socketRegistry = new Map<string, ServerWebSocket<ClientState>>();

Bun.serve<ClientState>({
  port: 3000,
  fetch(req, server) {
    const userId = new URL(req.url).searchParams.get("userId") ?? crypto.randomUUID();
    const room = "global-chat";
    
    const success = server.upgrade(req, {
      data: { userId, room },
    });
    return success ? undefined : new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      socketRegistry.set(ws.data.userId, ws);
    },
    message(ws, message) {
      // ANTI-PATTERN: Manual O(N) iteration in JS heap defeats C++ native broadcast
      for (const [id, socket] of socketRegistry.entries()) {
        if (socket.data.room === ws.data.room && id !== ws.data.userId) {
          socket.send(message);
        }
      }
    },
    close(ws) {
      socketRegistry.delete(ws.data.userId);
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```typescript
import { ServerWebSocket } from "bun";

interface WebSocketData {
  readonly userId: string;
  readonly room: string;
  readonly connectedAt: number;
}

const server = Bun.serve<WebSocketData>({
  port: 3000,
  fetch(req, server) {
    const url = new URL(req.url);
    const userId = url.searchParams.get("userId") ?? crypto.randomUUID();
    const room = url.searchParams.get("room") ?? "global-chat";

    // Pass immutable, flat connection metadata into native C++ socket descriptor
    const upgraded = server.upgrade(req, {
      data: {
        userId,
        room,
        connectedAt: Date.now(),
      },
    });

    return upgraded ? undefined : new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws: ServerWebSocket<WebSocketData>) {
      // Native subscription delegates tracking to Bun's C++ uSockets engine
      ws.subscribe(ws.data.room);
    },
    message(ws: ServerWebSocket<WebSocketData>, message: string | Buffer) {
      // Native zero-copy publish to topic without touching JS heap for idle subscribers
      server.publish(ws.data.room, message);
    },
    close(ws: ServerWebSocket<WebSocketData>) {
      ws.unsubscribe(ws.data.room);
    },
    drain(ws: ServerWebSocket<WebSocketData>) {
      // Resume backpressured streams when native kernel buffer drains
    },
  },
});
```

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 WebSocket Server Hibernation State Retention Standard

Bun 1.2 Native WebSocket Server Hibernation State Retention Standard defines an industrial-grade behavioral standard for backend engineering. Bun 1.2 native WebSocket server hibernation achieves extreme connection density by garbage collecting idle JavaScriptCore connection wrappers and persisting socket descriptors at the native C++/kernel level. Storing active ServerWebSocket references in JavaScript heaps (such as Maps or Sets) defeats hibernation, leading to rapid memory bloat and process termination under high concurrency. All connection lifecycle state must be bound to the native upgrade context and mutated solely via ws.data, while fan-out messaging must leverage native C++ topic pub/sub. 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 ServerWebSocket references in module-scoped collections and manually iterating sockets for broadcasting instead of native hibernation and topic pub/sub. 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 ServerWebSocket references in module-scoped collections and manually iterating sockets for broadcasting instead of native hibernation and topic pub/sub.Critical
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 initialize socket state via the `data` option of `server.upgrade(request, { data })` during HTTP upgrade handling.

Engineers MUST ALWAYS initialize socket state via the `data` option of `server.upgrade(request, { data })` during HTTP upgrade handling.

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 `ServerWebSocket` instances in module-level `Map`, `Set`, `Array`, or object properties, as retaining JS references prevents V8/JSC garbage collection of idle sockets.

Engineers MUST NOT store `ServerWebSocket` instances in module-level `Map`, `Set`, `Array`, or object properties, as retaining JS references prevents V8/JSC garbage collection of idle 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.
3

Engineers MUST ALWAYS execute broadcasts using Bun's native topic pub/sub primitives (`server.publish(topic, message)` and `ws.subscribe(topic)`) rather than looping over socket handles.

Engineers MUST ALWAYS execute broadcasts using Bun's native topic pub/sub primitives (`server.publish(topic, message)` and `ws.subscribe(topic)`) rather than looping over socket 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.
4

Code SHOULD define a strictly typed, memory-compact interface for `ws.data` containing only essential primitives, avoiding deep object graphs or uncollected buffer references.

Code SHOULD define a strictly typed, memory-compact interface for `ws.data` containing only essential primitives, avoiding deep object graphs or uncollected buffer references.

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 enable `backpressure

Services MUST enable `backpressure: true` or inspect `ws.getBufferedAmount()` before sending high-throughput bursts to hibernating connections.

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 dynamic socket instances

Components NEVER attach custom event listeners to dynamic socket instances; all hooks MUST reside globally in the `Bun.serve({ websocket: { open, message, close, drain } })` declaration.

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

Bun 1.2 native WebSocket server hibernation achieves extreme connection density by garbage collecting idle JavaScriptCore connection wrappers and persisting socket descriptors at the native C++/kernel level. Storing active ServerWebSocket references in JavaScript heaps (such as Maps or Sets) defeats hibernation, leading to rapid memory bloat and process termination under high concurrency. All connection lifecycle state must be bound to the native upgrade context and mutated solely via ws.data, while fan-out messaging must leverage native C++ topic pub/sub. 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 ServerWebSocket references in module-scoped collections and manually iterating sockets for broadcasting instead of native hibernation and topic pub/sub.) 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