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

Bun 1.2 Native WebSocket Kernel Hibernation & Zero-Heap Idle Sockets

Enforces Bun 1.2 native WebSocket server configuration patterns utilizing kernel-level epoll hibernation to eliminate V8/JSC heap bloat over massive concurrent connections. Mandates declarative pub/sub topics and context detachment to prevent socket retention leaks in userland memory, allowing idle connections to sleep entirely in the kernel until packet ingress.

Prohibited Anti-Pattern: Retaining JavaScript WebSocket References in Userland Closures and In-Memory Registry Sets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Kernel Hibernation & Zero-Heap Idle Sockets - Enforces Bun 1.2 native WebSocket server configuration patterns utilizing kernel-level epoll hibernation to eliminate V8/JSC heap bloat over massive concurrent connections. Mandates declarative pub/sub topics and context detachment to prevent socket retention leaks in userland memory, allowing idle connections to sleep entirely in the kernel until packet ingress.
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-kernel-hibernation-contract"
---

# Bun 1.2 Native WebSocket Kernel Hibernation & Zero-Heap Idle Sockets

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining JavaScript WebSocket References in Userland Closures and In-Memory Registry Sets

## System Constraints
You are a Principal Backend Systems Architect specializing in high-concurrency runtime internals and Bun networking primitives. Your task is to enforce Bun 1.2 Native WebSocket Kernel Hibernation contracts. You must ensure that idle WebSockets consume zero JavaScript heap overhead by preventing userland reference storage, mandating Bun native pub/sub topics over custom iteration loops, and guaranteeing that WebSocket handlers rely exclusively on native epoll-backed hibernation parameters without attaching stateful closures or custom ping/pong intervals.

## Strict Guidelines
- Engineers MUST configure `websocket: { sendPings: true, idleTimeout: number }` in Bun.serve to offload heartbeat maintenance entirely to the C++ core and kernel, deprecating userland ping/pong timer loops.
- Engineers MUST NOT store `ServerWebSocket` instances in userland collections (`Set`, `Map`, `Array`, or global object properties), as any persistent reference prevents garbage collection and breaks zero-heap kernel hibernation.
- Engineers MUST utilize Bun's native server pub/sub interface (`server.publish(topic, data)` and `ws.subscribe(topic)`) instead of manual iteration over connected socket registries.
- Code SHOULD store transient per-connection data strictly within the typed `ws.data` context passed during the HTTP `upgrade()` handshake, avoiding dynamic allocations inside socket callbacks.
- Services MUST implement backpressure-aware draining using `drain(ws)` rather than buffering payload chunks in userland queues when kernel socket buffers saturate.

## Bad vs Good Implementations
### Migrating from Manual Socket Retention to Bun 1.2 Kernel Hibernation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining socket instances inside an in-memory `Set` and running userland `setInterval` ping loops forces the JavaScript runtime to keep socket wrappers instantiated in heap memory. This prevents idle connections from hibernating at the OS kernel epoll layer, causing significant heap bloat and high CPU overhead on million-connection clusters.
```typescript
import { ServerWebSocket } from "bun";

interface ClientData {
  userId: string;
}

// ANTI-PATTERN: In-memory registry prevents V8/JSC garbage collection
// and subverts kernel epoll hibernation, pinning entire socket wrappers to heap.
const activeSockets = new Set<ServerWebSocket<ClientData>>();

Bun.serve<ClientData>({
  port: 8080,
  fetch(req, server) {
    const userId = new URL(req.url).searchParams.get("userId") ?? "anon";
    if (server.upgrade(req, { data: { userId } })) return;
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      activeSockets.add(ws);
      // ANTI-PATTERN: Manual heartbeat keeps JS runtime event-loop pinned
      (ws as any)._pingTimer = setInterval(() => ws.ping(), 30000);
    },
    message(ws, message) {
      // ANTI-PATTERN: Iterating over JS heap collections to broadcast
      for (const socket of activeSockets) {
        socket.send(`User ${ws.data.userId}: ${message}`);
      }
    },
    close(ws) {
      clearInterval((ws as any)._pingTimer);
      activeSockets.delete(ws);
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: By eliminating userland `Set` references and userland ping intervals, idle sockets drop to zero JavaScript heap footprint, staying hibernated at the Linux epoll / macOS kqueue kernel layer until packet arrival. Bun's native `ws.subscribe` and `ws.publish` offload fan-out routing directly to C++ without allocating JavaScript objects for recipient sockets.
```typescript
import { ServerWebSocket } from "bun";

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

// PRODUCTION FIX: Pure kernel-hibernated WebSockets.
// No persistent userland collections. Bun handles ping/pong and epoll hibernation natively.
Bun.serve<SocketData>({
  port: 8080,
  websocket: {
    // Native kernel ping handling: Bun sends unsolicited pings and tears down dead sockets
    sendPings: true,
    idleTimeout: 60, // seconds
    backpressureLimit: 1024 * 1024, // 1MB buffer cap
    
    open(ws: ServerWebSocket<SocketData>) {
      // Subscribe directly to native pub/sub C++ core layer
      ws.subscribe(ws.data.channel);
    },
    
    message(ws: ServerWebSocket<SocketData>, message: string | Buffer) {
      // Broadcast directly through kernel pub/sub without touching JS heap for peer sockets
      ws.publish(ws.data.channel, `User ${ws.data.userId}: ${message}`);
    },
    
    drain(ws: ServerWebSocket<SocketData>) {
      // Backpressure relief hook called when kernel socket write-buffer frees capacity
      console.info(`Socket buffer drained for client: ${ws.data.userId}`);
    },
    
    close(ws: ServerWebSocket<SocketData>) {
      ws.unsubscribe(ws.data.channel);
    }
  },
  
  fetch(req, server) {
    const url = new URL(req.url);
    const userId = url.searchParams.get("userId") ?? "anon";
    const channel = url.searchParams.get("channel") ?? "global";
    
    const upgraded = server.upgrade(req, {
      data: { userId, channel }
    });
    
    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.

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 Kernel Hibernation & Zero-Heap Idle Sockets

Bun 1.2 Native WebSocket Kernel Hibernation & Zero-Heap Idle Sockets defines an industrial-grade behavioral standard for backend engineering. Enforces Bun 1.2 native WebSocket server configuration patterns utilizing kernel-level epoll hibernation to eliminate V8/JSC heap bloat over massive concurrent connections. Mandates declarative pub/sub topics and context detachment to prevent socket retention leaks in userland memory, allowing idle connections to sleep entirely in the kernel until packet ingress. 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 Userland Closures and In-Memory Registry Sets 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 Userland Closures and In-Memory Registry SetsCritical
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 configure `websocket

Engineers MUST configure `websocket: { sendPings: true, idleTimeout: number }` in Bun.serve to offload heartbeat maintenance entirely to the C++ core and kernel, deprecating userland ping/pong timer loops.

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 userland collections (`Set`, `Map`, `Array`, or global object properties), as any persistent reference prevents garbage collection and breaks zero-heap kernel hibernation.

Engineers MUST NOT store `ServerWebSocket` instances in userland collections (`Set`, `Map`, `Array`, or global object properties), as any persistent reference prevents garbage collection and breaks zero-heap kernel hibernation.

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 utilize Bun's native server pub/sub interface (`server.publish(topic, data)` and `ws.subscribe(topic)`) instead of manual iteration over connected socket registries.

Engineers MUST utilize Bun's native server pub/sub interface (`server.publish(topic, data)` and `ws.subscribe(topic)`) instead of manual iteration over connected socket registries.

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 store transient per-connection data strictly within the typed `ws.data` context passed during the HTTP `upgrade()` handshake, avoiding dynamic allocations inside socket callbacks.

Code SHOULD store transient per-connection data strictly within the typed `ws.data` context passed during the HTTP `upgrade()` handshake, avoiding dynamic allocations inside socket callbacks.

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 implement backpressure-aware draining using `drain(ws)` rather than buffering payload chunks in userland queues when kernel socket buffers saturate.

Services MUST implement backpressure-aware draining using `drain(ws)` rather than buffering payload chunks in userland queues when kernel socket buffers saturate.

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 Kernel Hibernation & Zero-Heap Idle Sockets critical for AI coding assistants?

Enforces Bun 1.2 native WebSocket server configuration patterns utilizing kernel-level epoll hibernation to eliminate V8/JSC heap bloat over massive concurrent connections. Mandates declarative pub/sub topics and context detachment to prevent socket retention leaks in userland memory, allowing idle connections to sleep entirely in the kernel until packet ingress. 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 Userland Closures and In-Memory Registry Sets) 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