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

Bun 1.2 WebSocket Engine Server-Side Hibernation & Memory Eviction Guardrail

Enforces Bun 1.2 native uWebSockets-backed server-side hibernation semantics for ultra-dense real-time connection pooling. Prevents JavaScript V8/JSC heap exhaustion by eliminating long-lived JavaScript closure references, external maps, and non-pruned buffers, allowing idle sockets to drop their JS wrappers and sleep in kernel memory without V8 heap allocation.

Prohibited Anti-Pattern: Retaining JavaScript Object References and External Map Registries for Dormant WebSockets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 WebSocket Engine Server-Side Hibernation & Memory Eviction Guardrail - Enforces Bun 1.2 native uWebSockets-backed server-side hibernation semantics for ultra-dense real-time connection pooling. Prevents JavaScript V8/JSC heap exhaustion by eliminating long-lived JavaScript closure references, external maps, and non-pruned buffers, allowing idle sockets to drop their JS wrappers and sleep in kernel memory without V8 heap allocation.
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-eviction-boundary"
---

# Bun 1.2 WebSocket Engine Server-Side Hibernation & Memory Eviction Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining JavaScript Object References and External Map Registries for Dormant WebSockets

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 WebSocket Engine Server-Side Hibernation Memory Eviction Boundary. Mandate invariants that allow dormant sockets to enter zero-footprint kernel sleep states without retaining references in the JavaScript runtime heap.

## Strict Guidelines
- Engineers MUST ALWAYS leverage Bun.serve({ websocket: { ... } }) native hibernation hooks (open, message, close, drain) without binding socket instances to outer closure scopes.
- Engineers MUST NOT store `ServerWebSocket` instances in global `Map`, `Set`, or array registries, as holding a reference prevents Bun from deallocating the JS wrapper object during hibernation.
- Code MUST store connection-specific metadata strictly inside the `ws.data` contextual payload initialized during the HTTP upgrade step via `server.upgrade(req, { data: ... })`.
- Services MUST delegate all fan-out multicasting to native topic subscriptions via `ws.subscribe(topic)` and `server.publish(topic, data)` rather than iterating over collections of socket instances in JavaScript.
- Components NEVER attach custom event listeners or instantiate long-lived closures over `ws` references inside lifecycle callbacks.

## Bad vs Good Implementations
### WebSocket Connection Tracking: External Heap Map vs. Native Hibernation Subscriptions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing ServerWebSocket instances in a Map pins the JavaScript wrapper in the heap. Bun cannot evict the JS object when the socket is idle, causing the process to allocate hundreds of bytes per idle socket, leading to GC thrashing and preventing true kernel-level hibernation at scale.
```typescript
import { type ServerWebSocket } from 'bun';

interface ClientData {
  userId: string;
  rooms: string[];
}

// ANTI-PATTERN: Retaining raw ws references in a global collection prevents Bun's
// C++ core from evicting the JavaScript wrapper. Sockets cannot enter hibernation.
const activeClients = new Map<string, ServerWebSocket<ClientData>>();

Bun.serve<ClientData>({
  port: 8080,
  fetch(req, server) {
    const userId = new URL(req.url).searchParams.get('userId') ?? 'anonymous';
    server.upgrade(req, { data: { userId, rooms: ['global'] } });
    return new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    open(ws) {
      activeClients.set(ws.data.userId, ws);
    },
    message(ws, message) {
      // Iterating in JS heap forces wrappers to persist across GC cycles
      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**: By avoiding any long-lived JS references to `ws` and using `ws.subscribe` and `ws.publish`, Bun frees the JavaScript wrapper object as soon as the event callback returns. The connection drops down to a zero-memory hibernation state in the kernel until the next network packet arrives.
```typescript
import { type ServerWebSocket } from 'bun';

interface ClientData {
  userId: string;
  channels: string[];
}

// PRODUCTION INVARIANT: Zero external JS-retained socket maps.
// Bun manages connection lifecycle in C++/kernel space, freeing the JS wrapper when idle.
Bun.serve<ClientData>({
  port: 8080,
  fetch(req, server) {
    const url = new URL(req.url);
    const userId = url.searchParams.get('userId') ?? 'anonymous';
    const upgraded = server.upgrade(req, {
      data: {
        userId,
        channels: ['global']
      }
    });
    return upgraded ? undefined : new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    // Native pub/sub registers C++ socket descriptors directly to topics
    open(ws: ServerWebSocket<ClientData>) {
      for (const channel of ws.data.channels) {
        ws.subscribe(channel);
      }
    },
    message(ws: ServerWebSocket<ClientData>, message: string | Buffer) {
      // Dispatches directly through uWebSockets engine; zero JS loop overhead
      ws.publish('global', message);
    },
    close(ws: ServerWebSocket<ClientData>) {
      for (const channel of ws.data.channels) {
        ws.unsubscribe(channel);
      }
    },
    // Enables native backpressure handling without memory buildup
    drain(ws: ServerWebSocket<ClientData>) {
      // Socket drained and eligible for immediate hibernation
    }
  }
});
```

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 Engine Server-Side Hibernation & Memory Eviction Guardrail

Bun 1.2 WebSocket Engine Server-Side Hibernation & Memory Eviction Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces Bun 1.2 native uWebSockets-backed server-side hibernation semantics for ultra-dense real-time connection pooling. Prevents JavaScript V8/JSC heap exhaustion by eliminating long-lived JavaScript closure references, external maps, and non-pruned buffers, allowing idle sockets to drop their JS wrappers and sleep in kernel memory without V8 heap allocation. 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 Object References and External Map Registries for Dormant WebSockets 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 Object References and External Map Registries for Dormant WebSocketsCritical
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.serve({ websocket

Engineers MUST ALWAYS leverage Bun.serve({ websocket: { ... } }) native hibernation hooks (open, message, close, drain) without binding socket instances to outer closure scopes.

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 global `Map`, `Set`, or array registries, as holding a reference prevents Bun from deallocating the JS wrapper object during hibernation.

Engineers MUST NOT store `ServerWebSocket` instances in global `Map`, `Set`, or array registries, as holding a reference prevents Bun from deallocating the JS wrapper object during 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

Code MUST store connection-specific metadata strictly inside the `ws.data` contextual payload initialized during the HTTP upgrade step via `server.upgrade(req, { data

Code MUST store connection-specific metadata strictly inside the `ws.data` contextual payload initialized during the HTTP upgrade step via `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.
4

Services MUST delegate all fan-out multicasting to native topic subscriptions via `ws.subscribe(topic)` and `server.publish(topic, data)` rather than iterating over collections of socket instances in JavaScript.

Services MUST delegate all fan-out multicasting to native topic subscriptions via `ws.subscribe(topic)` and `server.publish(topic, data)` rather than iterating over collections of socket instances in JavaScript.

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 attach custom event listeners or instantiate long-lived closures over `ws` references inside lifecycle callbacks.

Components NEVER attach custom event listeners or instantiate long-lived closures over `ws` references inside lifecycle 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.
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 Engine Server-Side Hibernation & Memory Eviction Guardrail critical for AI coding assistants?

Enforces Bun 1.2 native uWebSockets-backed server-side hibernation semantics for ultra-dense real-time connection pooling. Prevents JavaScript V8/JSC heap exhaustion by eliminating long-lived JavaScript closure references, external maps, and non-pruned buffers, allowing idle sockets to drop their JS wrappers and sleep in kernel memory without V8 heap allocation. 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 Object References and External Map Registries for Dormant WebSockets) 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