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

Bun 1.2 WebSocket Hibernation & Zero-Heap Connection Pinning

Enforces zero-heap WebSocket lifecycle patterns in Bun 1.2+ by offloading idle socket state to native kernel structures (epoll/kqueue) through native pub/sub topics and transient descriptors. Eliminates multi-gigabyte JavaScriptCore heap degradation across high-fanout deployments by prohibiting persistent JavaScript socket references and unbounded closure captures.

Prohibited Anti-Pattern: Retaining ServerWebSocket references in heap collections or closures, defeating native kernel hibernation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 WebSocket Hibernation & Zero-Heap Connection Pinning - Enforces zero-heap WebSocket lifecycle patterns in Bun 1.2+ by offloading idle socket state to native kernel structures (epoll/kqueue) through native pub/sub topics and transient descriptors. Eliminates multi-gigabyte JavaScriptCore heap degradation across high-fanout deployments by prohibiting persistent JavaScript socket references and unbounded closure captures.
globs: src/**/*.ts, server/**/*.ts, apps/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-hibernation-native-memory-pinning"
---

# Bun 1.2 WebSocket Hibernation & Zero-Heap Connection Pinning

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining ServerWebSocket references in heap collections or closures, defeating native kernel hibernation

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 WebSocket Hibernation & Native Memory Pinning. You must ensure all WebSocket server implementations leverage native C++ topic-based pub/sub, transient socket wrappers, and corked I/O batching, completely preventing idle connection retention in the JavaScriptCore heap.

## Strict Guidelines
- Engineers MUST ALWAYS rely on native topic-based pub/sub (`ws.subscribe()`, `server.publish()`) rather than maintaining user-space socket registries (`Set<ServerWebSocket>`, `Map<string, ServerWebSocket>`).
- Engineers MUST NOT capture `ServerWebSocket` instances in persistent closures, long-lived promises, module-level variables, or asynchronous intervals.
- Engineers MUST batch multi-message transmissions using `ws.cork()` to minimize TCP system calls and avoid intermediate user-space buffer allocations.
- Services MUST implement the `drain` and `backpressure` lifecycle hooks to enforce strict kernel buffer ceilings using `ws.getBufferedAmount()` before sending additional payloads.
- Components NEVER store mutable business state directly on the `ServerWebSocket` instance outside of the statically-typed `ws.data` context initialized during the HTTP upgrade handshake.

## Bad vs Good Implementations
### Topic-based Native Hibernation vs. Userland Collection Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing `ServerWebSocket` instances in a JavaScript `Map` prevents the JavaScriptCore runtime from garbage-collecting the JS wrapper, forcing Bun to keep wrapper objects alive on the JS heap instead of hibernating idle descriptors into native kernel epoll/kqueue structures.
```typescript
import { serve, type ServerWebSocket } from "bun";

interface SocketData { userId: string; roomId: string; }

// ANTI-PATTERN: Heap-pinned collection defeats native socket hibernation.
// Every connected client retains a full JavaScriptCore object in memory.
const activeSockets = new Map<string, ServerWebSocket<SocketData>>();

const server = serve<SocketData>({
  port: 3000,
  fetch(req, server) {
    const url = new URL(req.url);
    server.upgrade(req, {
      data: { userId: crypto.randomUUID(), roomId: url.searchParams.get("room") ?? "default" },
    });
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      activeSockets.set(ws.data.userId, ws); // Memory leak under high connection fanout
    },
    message(ws, message) {
      // Iterating over user-space sockets keeps all sockets hot in JSC heap
      for (const [_, client] of activeSockets) {
        if (client.data.roomId === ws.data.roomId) {
          client.send(message); // Unbatched write causing syscall overhead
        }
      }
    },
    close(ws) {
      activeSockets.delete(ws.data.userId);
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Utilizes Bun's native C++ topic subscription engine. Idle WebSockets drop their JS wrapper entirely, hibernating at zero JS heap overhead down to the native descriptor level. Corking batches writes into a single kernel payload, maximizing throughput.
```typescript
import { serve, type ServerWebSocket } from "bun";

interface SocketData { userId: string; roomId: string; }

const server = serve<SocketData>({
  port: 3000,
  fetch(req, server) {
    const url = new URL(req.url);
    const upgraded = server.upgrade(req, {
      data: { 
        userId: crypto.randomUUID(), 
        roomId: url.searchParams.get("room") ?? "default" 
      },
    });
    return upgraded ? undefined : new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    // Native socket hibernation configuration
    idleTimeout: 120, // 2 minutes: idle sockets are completely hibernated
    maxPayloadLength: 64 * 1024, // 64KB bounded native payload buffer
    backpressureLimit: 1024 * 1024, // 1MB native buffer limit
    closeOnBackpressureLimit: true,

    open(ws) {
      // Offload connection membership to native C++ topic structure
      ws.subscribe(ws.data.roomId);
    },
    message(ws, message) {
      // Corking groups syscalls and ensures zero JS-heap socket retention
      ws.cork((corkedWs) => {
        server.publish(corkedWs.data.roomId, message);
      });
    },
    drain(ws) {
      // Invoked when kernel transmission buffer drains below high-water mark
      if (ws.getBufferedAmount() === 0) {
        // Resume any pending producer tasks
      }
    },
    close(ws) {
      ws.unsubscribe(ws.data.roomId);
    },
  },
});
```

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 WebSocket Hibernation & Zero-Heap Connection Pinning

Bun 1.2 WebSocket Hibernation & Zero-Heap Connection Pinning defines an industrial-grade behavioral standard for backend engineering. Enforces zero-heap WebSocket lifecycle patterns in Bun 1.2+ by offloading idle socket state to native kernel structures (epoll/kqueue) through native pub/sub topics and transient descriptors. Eliminates multi-gigabyte JavaScriptCore heap degradation across high-fanout deployments by prohibiting persistent JavaScript socket references and unbounded closure captures. 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 ServerWebSocket references in heap collections or closures, defeating native kernel hibernation 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 ServerWebSocket references in heap collections or closures, defeating native kernel hibernationCritical
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 rely on native topic-based pub/sub (`ws.subscribe()`, `server.publish()`) rather than maintaining user-space socket registries (`Set<ServerWebSocket>`, `Map<string, ServerWebSocket>`).

Engineers MUST ALWAYS rely on native topic-based pub/sub (`ws.subscribe()`, `server.publish()`) rather than maintaining user-space socket registries (`Set<ServerWebSocket>`, `Map<string, ServerWebSocket>`).

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 capture `ServerWebSocket` instances in persistent closures, long-lived promises, module-level variables, or asynchronous intervals.

Engineers MUST NOT capture `ServerWebSocket` instances in persistent closures, long-lived promises, module-level variables, or asynchronous intervals.

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 batch multi-message transmissions using `ws.cork()` to minimize TCP system calls and avoid intermediate user-space buffer allocations.

Engineers MUST batch multi-message transmissions using `ws.cork()` to minimize TCP system calls and avoid intermediate user-space buffer allocations.

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 implement the `drain` and `backpressure` lifecycle hooks to enforce strict kernel buffer ceilings using `ws.getBufferedAmount()` before sending additional payloads.

Services MUST implement the `drain` and `backpressure` lifecycle hooks to enforce strict kernel buffer ceilings using `ws.getBufferedAmount()` before sending additional payloads.

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 store mutable business state directly on the `ServerWebSocket` instance outside of the statically-typed `ws.data` context initialized during the HTTP upgrade handshake.

Components NEVER store mutable business state directly on the `ServerWebSocket` instance outside of the statically-typed `ws.data` context initialized during the HTTP upgrade handshake.

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 & Zero-Heap Connection Pinning critical for AI coding assistants?

Enforces zero-heap WebSocket lifecycle patterns in Bun 1.2+ by offloading idle socket state to native kernel structures (epoll/kqueue) through native pub/sub topics and transient descriptors. Eliminates multi-gigabyte JavaScriptCore heap degradation across high-fanout deployments by prohibiting persistent JavaScript socket references and unbounded closure captures. 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 ServerWebSocket references in heap collections or closures, defeating native kernel hibernation) 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