This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-websocket-backpressure-drain-invariant-bun-1-2-high-thr-371

Bun 1.2 WebSocket Backpressure Drain & High-Cardinality Invariant

Enforces deterministic non-blocking socket backpressure handling in Bun 1.2+ native WebSockets during high-cardinality broadcast spikes. Prevents silent internal C++ heap bloat and unmonitored dropped frames by verifying `ws.send()` return codes, maintaining per-socket pending ring buffers, and listening to the `drain(ws)` event hook before resuming socket writes.

Prohibited Anti-Pattern: Blind ws.send() Broadcasting Causing Silent C++ Heap Ballooning and OOM Crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 WebSocket Backpressure Drain & High-Cardinality Invariant - Enforces deterministic non-blocking socket backpressure handling in Bun 1.2+ native WebSockets during high-cardinality broadcast spikes. Prevents silent internal C++ heap bloat and unmonitored dropped frames by verifying `ws.send()` return codes, maintaining per-socket pending ring buffers, and listening to the `drain(ws)` event hook before resuming socket writes.
globs: src/**/*.ts, server/**/*.ts, lib/websocket/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-backpressure-drain-invariant-bun-1-2-high-thr-371"
---

# Bun 1.2 WebSocket Backpressure Drain & High-Cardinality Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Blind ws.send() Broadcasting Causing Silent C++ Heap Ballooning and OOM Crashes

## System Constraints
You are a Principal Systems Architect specializing in Bun runtime internals and high-throughput network programming. Enforce zero-allocation, backpressure-aware WebSocket architectures. You must reject any code where `ws.send()`, `ws.publish()`, or `server.publish()` is invoked without evaluating the returned byte count or handling `drain` lifecycle events under sustained socket pressure. Mandate explicit socket queue ceilings and deterministic drop-or-pause policies.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the numeric return value of `ws.send(data)`: in Bun, a return value of -1 indicates full backpressure, 0 indicates failure/closure, and a positive integer indicates byte count queued or sent.
- Engineers MUST NOT assume `ws.publish()` or `server.publish()` silently handles slow consumers; slow subscribers in high-throughput topics MUST have explicit backpressure bounds or be evicted to protect the event loop.
- Services MUST implement the `drain(ws)` callback in `Bun.serve({ websocket: { ... } })` to flush buffered frames once the OS kernel socket buffer frees capacity.
- Code SHOULD track `ws.getBufferedAmount()` against a hard upper limit (e.g., 1MB per socket) and immediately close (`ws.close(1008, 'Policy Violation: Buffer Exceeded')`) uncooperative slow-draining peers.
- Components NEVER store unbounded arrays of outgoing payloads on client session contexts without backpressure-aware throttling or bounded sliding-window drops.

## Bad vs Good Implementations
### Unbounded Naive Broadcast vs. Backpressure-Aware Drain Queue

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `ws.send()` across a client set without inspecting return values or buffered queue sizes causes Bun's internal C++ WebSocket memory pool to grow without bound when a consumer is slow or network stalls, eventually triggering an unrecoverable SIGKILL from the OS OOM killer.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientData {
  id: string;
}

const clients = new Set<ServerWebSocket<ClientData>>();

export function broadcast(payload: string) {
  // Anti-pattern: Blind iteration without checking backpressure or return code
  for (const ws of clients) {
    ws.send(payload); // Silently piles into Bun internal C++ ring buffer; risks OOM
  }
}

Bun.serve<ClientData>({
  port: 3000,
  websocket: {
    open(ws) {
      clients.add(ws);
    },
    message(ws, message) {
      broadcast(String(message));
    },
    close(ws) {
      clients.delete(ws);
    }
  },
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response('Upgrade failed', { status: 400 });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic backpressure handling by intercepting Bun's `-1` return status from `ws.send()`, transitioning the socket into a backpressured state, queuing frames inside bounded userland storage, enforcing an absolute ceiling on `ws.getBufferedAmount()`, and draining strictly when Bun fires the native `drain` hook.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientData {
  id: string;
  queue: string[];
  isBackpressured: boolean;
}

const MAX_BUFFERED_BYTES = 1024 * 1024; // 1MB upper boundary
const MAX_QUEUE_DEPTH = 500;

function sendOrBuffer(ws: ServerWebSocket<ClientData>, message: string): void {
  if (ws.data.isBackpressured || ws.data.queue.length > 0) {
    if (ws.data.queue.length >= MAX_QUEUE_DEPTH || ws.getBufferedAmount() > MAX_BUFFERED_BYTES) {
      ws.close(1008, 'Buffer overflow: consumer too slow');
      return;
    }
    ws.data.queue.push(message);
    return;
  }

  const result = ws.send(message);
  if (result === -1) {
    // Backpressure threshold reached
    ws.data.isBackpressured = true;
    ws.data.queue.push(message);
  } else if (result === 0) {
    ws.close(1011, 'Frame dispatch failure');
  }
}

Bun.serve<ClientData>({
  port: 3000,
  websocket: {
    open(ws) {
      ws.data = { id: crypto.randomUUID(), queue: [], isBackpressured: false };
    },
    message(ws, msg) {
      sendOrBuffer(ws, String(msg));
    },
    drain(ws) {
      ws.data.isBackpressured = false;
      while (ws.data.queue.length > 0) {
        const next = ws.data.queue[0];
        const result = ws.send(next);
        if (result === -1) {
          ws.data.isBackpressured = true;
          break;
        }
        ws.data.queue.shift();
      }
    },
    close(ws) {
      ws.data.queue.length = 0;
    }
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: '', queue: [], isBackpressured: false } })) return;
    return 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 WebSocket Backpressure Drain & High-Cardinality Invariant

Bun 1.2 WebSocket Backpressure Drain & High-Cardinality Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic non-blocking socket backpressure handling in Bun 1.2+ native WebSockets during high-cardinality broadcast spikes. Prevents silent internal C++ heap bloat and unmonitored dropped frames by verifying `ws.send()` return codes, maintaining per-socket pending ring buffers, and listening to the `drain(ws)` event hook before resuming socket writes. 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: Blind ws.send() Broadcasting Causing Silent C++ Heap Ballooning and OOM Crashes 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 DriftBlind ws.send() Broadcasting Causing Silent C++ Heap Ballooning and OOM CrashesCritical
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 inspect the numeric return value of `ws.send(data)`

Engineers MUST ALWAYS inspect the numeric return value of `ws.send(data)`: in Bun, a return value of -1 indicates full backpressure, 0 indicates failure/closure, and a positive integer indicates byte count queued or sent.

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 assume `ws.publish()` or `server.publish()` silently handles slow consumers

Engineers MUST NOT assume `ws.publish()` or `server.publish()` silently handles slow consumers; slow subscribers in high-throughput topics MUST have explicit backpressure bounds or be evicted to protect the event loop.

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

Services MUST implement the `drain(ws)` callback in `Bun.serve({ websocket

Services MUST implement the `drain(ws)` callback in `Bun.serve({ websocket: { ... } })` to flush buffered frames once the OS kernel socket buffer frees capacity.

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 track `ws.getBufferedAmount()` against a hard upper limit (e.g., 1MB per socket) and immediately close (`ws.close(1008, 'Policy Violation

Code SHOULD track `ws.getBufferedAmount()` against a hard upper limit (e.g., 1MB per socket) and immediately close (`ws.close(1008, 'Policy Violation: Buffer Exceeded')`) uncooperative slow-draining peers.

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 unbounded arrays of outgoing payloads on client session contexts without backpressure-aware throttling or bounded sliding-window drops.

Components NEVER store unbounded arrays of outgoing payloads on client session contexts without backpressure-aware throttling or bounded sliding-window drops.

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 Backpressure Drain & High-Cardinality Invariant critical for AI coding assistants?

Enforces deterministic non-blocking socket backpressure handling in Bun 1.2+ native WebSockets during high-cardinality broadcast spikes. Prevents silent internal C++ heap bloat and unmonitored dropped frames by verifying `ws.send()` return codes, maintaining per-socket pending ring buffers, and listening to the `drain(ws)` event hook before resuming socket writes. 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 (Blind ws.send() Broadcasting Causing Silent C++ Heap Ballooning and OOM Crashes) 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