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

Bun 1.2 WebSocket Hibernation and Per-Socket State Synchronization Standard

Enforces zero-heap socket hibernation across millions of concurrent idle duplex connections using Bun 1.2's native uSockets hibernation APIs. Mandates strictly serializable, off-heap or compressed contextual data structures within `ServerWebSocket.data` to prevent JavaScript heap bloating and state divergence during rapid wake-up/sleep cycles. Eliminates closure retention and external Map-based socket registries that induce memory leaks and sub-millisecond revival stalls.

Prohibited Anti-Pattern: Retaining In-Memory JavaScript Object References and External Socket Maps Across Hibernated Connections

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 WebSocket Hibernation and Per-Socket State Synchronization Standard - Enforces zero-heap socket hibernation across millions of concurrent idle duplex connections using Bun 1.2's native uSockets hibernation APIs. Mandates strictly serializable, off-heap or compressed contextual data structures within `ServerWebSocket.data` to prevent JavaScript heap bloating and state divergence during rapid wake-up/sleep cycles. Eliminates closure retention and external Map-based socket registries that induce memory leaks and sub-millisecond revival stalls.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}, gateway/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-hibernation-state-synchronization-standard"
---

# Bun 1.2 WebSocket Hibernation and Per-Socket State Synchronization Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining In-Memory JavaScript Object References and External Socket Maps Across Hibernated Connections

## System Constraints
You are a Principal Backend Engineer enforcing the Bun 1.2 WebSocket Hibernation State Synchronization Standard. Bun's native WebSocket engine (built on uWebSockets) supports zero-overhead connection hibernation where idle sockets consume kernel memory only, without pinning JavaScript heap contexts. You must prevent engineers from keeping persistent closure scopes, holding global Map references to ServerWebSocket instances, or storing rich complex objects inside `ws.data`. All state must be strictly typed, minimal, serializable, and synchronized exclusively via Bun's native WebSocket lifecycle handlers.

## Strict Guidelines
- Engineers MUST ALWAYS attach contextual state strictly through the typed `ws.data` payload configured during `server.upgrade(req, { data: ... })` rather than global reference maps.
- Engineers MUST NOT store long-lived `ServerWebSocket` instances in global arrays, `Map`, or `Set` registries, as doing so completely invalidates Bun's native C++ socket hibernation engine and pins V8/JSC heap frames.
- State attached to `ws.data` MUST be compact, flat, and scalar (e.g., numeric IDs, bitmasks, or compact string tokens) to prevent high-watermark GC spikes when millions of sockets awaken simultaneously.
- Components NEVER attach event listeners via `.addEventListener()` or closure captures directly to individual sockets; message routing MUST route through Bun's centralized `websocket: { open, message, close, drain }` hooks.
- Services MUST leverage `ws.subscribe(topic)` and `server.publish(topic, data)` for group messaging to utilize off-heap C++ pub/sub topics instead of iterating over JavaScript socket collections.

## Bad vs Good Implementations
### Anti-Pattern: External Socket Registry and Memory-Leaking Closures vs. Native Hibernation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing `ServerWebSocket` references in a global `Map` prevents the Bun C++ runtime from reclaiming or hibernating the socket state, directly leaking memory and triggering GC pauses during massive traffic spikes. Complex objects in `ws.data` expand heap overhead per connection.
```typescript
import { ServerWebSocket } from "bun";

// ANTI-PATTERN: Retaining global JS references prevents uSockets hibernation,
// leading to unbounded heap exhaustion across 100k+ idle connections.
interface SocketMetadata {
  userId: string;
  joinedAt: Date;
  complexContext: Record<string, unknown>;
}

const activeClients = new Map<string, ServerWebSocket<SocketMetadata>>();

Bun.serve<SocketMetadata>({
  port: 8080,
  fetch(req, server) {
    const userId = new URL(req.url).searchParams.get("userId");
    if (!userId) return new Response("Unauthorized", { status: 401 });
    
    server.upgrade(req, {
      data: {
        userId,
        joinedAt: new Date(),
        complexContext: { sessionInfo: req.headers.toJSON() }
      }
    });
    return undefined;
  },
  websocket: {
    open(ws) {
      // Pinned in JavaScript memory; prevents GC and breaks hibernation
      activeClients.set(ws.data.userId, ws);
    },
    message(ws, message) {
      // Iterating over global JS collections instead of native pub/sub
      for (const [id, client] of activeClients.entries()) {
        if (id !== ws.data.userId) {
          client.send(message);
        }
      }
    },
    close(ws) {
      activeClients.delete(ws.data.userId);
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Leverages Bun's native uSockets pub/sub engine and removes external JavaScript references. `ws.data` contains only scalar fields. Idle connections transition cleanly into the kernel with zero JS heap overhead and revive within sub-millisecond tolerances when incoming frames arrive.
```typescript
import { ServerWebSocket } from "bun";

// PRODUCTION FIX: Minimal, flat, scalar memory layout for zero-heap hibernation
type HibernatedSession = {
  readonly userId: string;
  readonly tenantId: number;
  readonly flags: number; // Bitmask for connection state/roles
};

Bun.serve<HibernatedSession>({
  port: 8080,
  // Bun 1.2+ native hibernation configuration
  websocket: {
    idleTimeout: 120, // Socket sleeps after inactivity, freeing JavaScript memory
    sendPings: true,
    backpressureLimit: 1024 * 1024,
    closeOnBackpressureLimit: true,
    
    open(ws: ServerWebSocket<HibernatedSession>) {
      // Leverage off-heap C++ pub/sub clustering
      const channel = `tenant:${ws.data.tenantId}`;
      ws.subscribe(channel);
    },
    message(ws: ServerWebSocket<HibernatedSession>, message: string | Buffer) {
      // Revived socket instantly dispatches to off-heap native topic
      const channel = `tenant:${ws.data.tenantId}`;
      ws.publish(channel, message);
    },
    drain(_ws: ServerWebSocket<HibernatedSession>) {
      // Handle kernel-level drain notifications under backpressure
    },
    close(ws: ServerWebSocket<HibernatedSession>) {
      const channel = `tenant:${ws.data.tenantId}`;
      ws.unsubscribe(channel);
    }
  },
  fetch(req, server) {
    const url = new URL(req.url);
    const userId = url.searchParams.get("uid");
    const tenantId = Number(url.searchParams.get("tid"));

    if (!userId || Number.isNaN(tenantId)) {
      return new Response("Unauthorized", { status: 401 });
    }

    const upgraded = server.upgrade(req, {
      data: {
        userId,
        tenantId,
        flags: 0
      }
    });

    return upgraded ? undefined : new Response("Upgrade failed", { status: 400 });
  }
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 WebSocket Hibernation and Per-Socket State Synchronization Standard

Bun 1.2 WebSocket Hibernation and Per-Socket State Synchronization Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-heap socket hibernation across millions of concurrent idle duplex connections using Bun 1.2's native uSockets hibernation APIs. Mandates strictly serializable, off-heap or compressed contextual data structures within `ServerWebSocket.data` to prevent JavaScript heap bloating and state divergence during rapid wake-up/sleep cycles. Eliminates closure retention and external Map-based socket registries that induce memory leaks and sub-millisecond revival stalls. 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 In-Memory JavaScript Object References and External Socket Maps Across Hibernated Connections 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 In-Memory JavaScript Object References and External Socket Maps Across Hibernated ConnectionsCritical
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 attach contextual state strictly through the typed `ws.data` payload configured during `server.upgrade(req, { data

Engineers MUST ALWAYS attach contextual state strictly through the typed `ws.data` payload configured during `server.upgrade(req, { data: ... })` rather than global reference maps.

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 long-lived `ServerWebSocket` instances in global arrays, `Map`, or `Set` registries, as doing so completely invalidates Bun's native C++ socket hibernation engine and pins V8/JSC heap frames.

Engineers MUST NOT store long-lived `ServerWebSocket` instances in global arrays, `Map`, or `Set` registries, as doing so completely invalidates Bun's native C++ socket hibernation engine and pins V8/JSC heap frames.

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

State attached to `ws.data` MUST be compact, flat, and scalar (e.g., numeric IDs, bitmasks, or compact string tokens) to prevent high-watermark GC spikes when millions of sockets awaken simultaneously.

State attached to `ws.data` MUST be compact, flat, and scalar (e.g., numeric IDs, bitmasks, or compact string tokens) to prevent high-watermark GC spikes when millions of sockets awaken simultaneously.

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

Components NEVER attach event listeners via `.addEventListener()` or closure captures directly to individual sockets

Components NEVER attach event listeners via `.addEventListener()` or closure captures directly to individual sockets; message routing MUST route through Bun's centralized `websocket: { open, message, close, drain }` hooks.

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 leverage `ws.subscribe(topic)` and `server.publish(topic, data)` for group messaging to utilize off-heap C++ pub/sub topics instead of iterating over JavaScript socket collections.

Services MUST leverage `ws.subscribe(topic)` and `server.publish(topic, data)` for group messaging to utilize off-heap C++ pub/sub topics instead of iterating over JavaScript socket collections.

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 WebSocket Hibernation and Per-Socket State Synchronization Standard critical for AI coding assistants?

Enforces zero-heap socket hibernation across millions of concurrent idle duplex connections using Bun 1.2's native uSockets hibernation APIs. Mandates strictly serializable, off-heap or compressed contextual data structures within `ServerWebSocket.data` to prevent JavaScript heap bloating and state divergence during rapid wake-up/sleep cycles. Eliminates closure retention and external Map-based socket registries that induce memory leaks and sub-millisecond revival stalls. 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 In-Memory JavaScript Object References and External Socket Maps Across Hibernated Connections) 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