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

Bun 1.2 Native WebSocket Hibernation Backpressure Threshold and Shedding

Enforces proactive backpressure management and aggressive connection shedding for Bun 1.2 native hibernated WebSockets. Prevents edge process heap exhaustion and unmanaged native memory bloat by mandating buffered amount checks and drain listeners before sockets return to dormant states.

Prohibited Anti-Pattern: Unbounded WebSocket Broadcasting and Ignored Native Buffer Backpressure in Hibernated Sockets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Hibernation Backpressure Threshold and Shedding - Enforces proactive backpressure management and aggressive connection shedding for Bun 1.2 native hibernated WebSockets. Prevents edge process heap exhaustion and unmanaged native memory bloat by mandating buffered amount checks and drain listeners before sockets return to dormant states.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-hibernation-backpressure-shedding"
---

# Bun 1.2 Native WebSocket Hibernation Backpressure Threshold and Shedding

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded WebSocket Broadcasting and Ignored Native Buffer Backpressure in Hibernated Sockets

## System Constraints
You are a Principal Software Architect enforcing production reliability in Bun 1.2 edge microservices. Hibernated WebSockets delegate connection state to native uWebSockets bindings, meaning write buffer growth does not trigger standard JavaScript engine garbage collection. You must strictly mandate proactive backpressure checks via `ws.getBufferedAmount()`, configured backpressure limits, responsive `drain` hooks, and defensive connection shedding to guarantee worker survivability under slow-consumer attacks.

## Strict Guidelines
- Engineers MUST ALWAYS configure explicit backpressure boundaries (`backpressureLimit` and `closeOnBackpressureLimit`) in `Bun.serve({ websocket: { ... } })` to protect native memory.
- Engineers MUST ALWAYS verify `ws.getBufferedAmount()` before sending high-frequency payloads or large chunks to an individual socket.
- Engineers MUST NOT allow hibernating sockets to queue outbound frames without implementing an explicit `drain(ws)` lifecycle handler.
- Services MUST proactively terminate or drop slow-consumer connections with WebSocket close code 1008 (Policy Violation) or 1013 (Try Again Later) when buffer ceilings are breached.
- Components NEVER assume `ws.publish()` or `ws.send()` completes synchronously without accumulating queued bytes in unmanaged native memory buffers.

## Bad vs Good Implementations
### Naive Broadcast Ignoring Hibernation Backpressure vs. Proactive Threshold Shedding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to set `backpressureLimit` or inspect `ws.getBufferedAmount()` allows slow or stalled consumers to cause unbounded growth in native uWebSockets buffers. Because these buffers exist outside the V8/JSC heap, JavaScript GC cannot reclaim them, precipitating silent OOM process kills on edge nodes.
```typescript
import { serve } from 'bun';

interface ClientData {
  userId: string;
}

serve<ClientData>({
  port: 3000,
  websocket: {
    // ANTI-PATTERN: No backpressure boundaries or drain handlers defined.
    // Slow clients cause unbounded native write-buffer accumulation.
    message(ws, message) {
      // Broadcast blindly to all subscribed clients
      ws.publish('market-feed', message);
    },
    open(ws) {
      ws.subscribe('market-feed');
    }
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { userId: 'anonymous' } })) {
      return;
    }
    return new Response('Upgrade failed', { status: 400 });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Configures strict native backpressure limits with `backpressureLimit` and `closeOnBackpressureLimit`. Validates `ws.getBufferedAmount()` within message flows, sheds misbehaving clients using standard close codes before heap exhaustion occurs, and utilizes the `drain` callback to resume dormant socket streams safely.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface ClientData {
  userId: string;
  isPaused: boolean;
}

const MAX_SOCKET_BACKPRESSURE_BYTES = 256 * 1024; // 256 KiB threshold

serve<ClientData>({
  port: 3000,
  websocket: {
    // Mandate native engine backpressure constraints
    backpressureLimit: MAX_SOCKET_BACKPRESSURE_BYTES,
    closeOnBackpressureLimit: true,

    open(ws: ServerWebSocket<ClientData>) {
      ws.subscribe('market-feed');
    },

    message(ws: ServerWebSocket<ClientData>, message: string | Buffer) {
      const buffered = ws.getBufferedAmount();
      
      // Proactively shed stalled or malicious consumers before buffer saturates
      if (buffered > MAX_SOCKET_BACKPRESSURE_BYTES) {
        ws.close(1008, 'Max backpressure threshold exceeded; connection terminated');
        return;
      }

      // Safe publish to topic subscribers
      ws.publish('market-feed', message);
    },

    drain(ws: ServerWebSocket<ClientData>) {
      // Socket has successfully flushed its write buffer; resume normal operations
      if (ws.data.isPaused) {
        ws.data.isPaused = false;
        ws.subscribe('market-feed');
      }
    },

    close(ws: ServerWebSocket<ClientData>, code: number, reason: string) {
      ws.unsubscribe('market-feed');
    }
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { userId: 'anonymous', isPaused: false } })) {
      return;
    }
    return new Response('WebSocket upgrade rejected', { 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 Hibernation Backpressure Threshold and Shedding

Bun 1.2 Native WebSocket Hibernation Backpressure Threshold and Shedding defines an industrial-grade behavioral standard for backend engineering. Enforces proactive backpressure management and aggressive connection shedding for Bun 1.2 native hibernated WebSockets. Prevents edge process heap exhaustion and unmanaged native memory bloat by mandating buffered amount checks and drain listeners before sockets return to dormant states. 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: Unbounded WebSocket Broadcasting and Ignored Native Buffer Backpressure in Hibernated Sockets 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 DriftUnbounded WebSocket Broadcasting and Ignored Native Buffer Backpressure in Hibernated SocketsCritical
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 configure explicit backpressure boundaries (`backpressureLimit` and `closeOnBackpressureLimit`) in `Bun.serve({ websocket

Engineers MUST ALWAYS configure explicit backpressure boundaries (`backpressureLimit` and `closeOnBackpressureLimit`) in `Bun.serve({ websocket: { ... } })` to protect native memory.

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 ALWAYS verify `ws.getBufferedAmount()` before sending high-frequency payloads or large chunks to an individual socket.

Engineers MUST ALWAYS verify `ws.getBufferedAmount()` before sending high-frequency payloads or large chunks to an individual socket.

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 NOT allow hibernating sockets to queue outbound frames without implementing an explicit `drain(ws)` lifecycle handler.

Engineers MUST NOT allow hibernating sockets to queue outbound frames without implementing an explicit `drain(ws)` lifecycle handler.

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 proactively terminate or drop slow-consumer connections with WebSocket close code 1008 (Policy Violation) or 1013 (Try Again Later) when buffer ceilings are breached.

Services MUST proactively terminate or drop slow-consumer connections with WebSocket close code 1008 (Policy Violation) or 1013 (Try Again Later) when buffer ceilings are breached.

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 assume `ws.publish()` or `ws.send()` completes synchronously without accumulating queued bytes in unmanaged native memory buffers.

Components NEVER assume `ws.publish()` or `ws.send()` completes synchronously without accumulating queued bytes in unmanaged native memory buffers.

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 Hibernation Backpressure Threshold and Shedding critical for AI coding assistants?

Enforces proactive backpressure management and aggressive connection shedding for Bun 1.2 native hibernated WebSockets. Prevents edge process heap exhaustion and unmanaged native memory bloat by mandating buffered amount checks and drain listeners before sockets return to dormant states. 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 (Unbounded WebSocket Broadcasting and Ignored Native Buffer Backpressure in Hibernated Sockets) 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