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

Bun 1.2 Native WebSocket Backpressure and High-Watermark Drain Management

Enforces strict per-socket buffered amount verification and cooperative backpressure in Bun 1.2 native WebSockets. Mandates drain lifecycle handler implementation and high-watermark boundaries to eliminate unbounded heap growth and process-level OOM crashes during high-throughput message fanouts.

Prohibited Anti-Pattern: Unchecked ws.send() Loop Fanout Leading to Silent Buffer Bloat and Fatal OOM Disruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure and High-Watermark Drain Management - Enforces strict per-socket buffered amount verification and cooperative backpressure in Bun 1.2 native WebSockets. Mandates drain lifecycle handler implementation and high-watermark boundaries to eliminate unbounded heap growth and process-level OOM crashes during high-throughput message fanouts.
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-backpressure-highwatermark"
---

# Bun 1.2 Native WebSocket Backpressure and High-Watermark Drain Management

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked ws.send() Loop Fanout Leading to Silent Buffer Bloat and Fatal OOM Disruption

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Native WebSocket Backpressure & High-Watermark Allocations. Mandate invariants regarding ws.getBufferedAmount(), Bun.serve websocket.drain lifecycle handling, explicit high-watermark socket disconnection or throttling policies, and elimination of unthrottled broadcast iterations over connected clients.

## Strict Guidelines
- Engineers MUST ALWAYS check ws.getBufferedAmount() before sending messages in high-volume paths or observe backpressure return values from ws.send().
- Engineers MUST NOT execute blind fanout loops over client collections without validating per-socket queued buffer levels against a defined high-watermark threshold.
- Services MUST define a websocket.drain handler in Bun.serve to resume suspended publishers or flush pending ring-buffered frames when kernel/socket buffers clear.
- Code SHOULD immediately terminate slow consumers with status code 1008 (Policy Violation) or 1011 (Internal Error) if their individual bufferedAmount exceeds the max safety allocation ceiling (e.g., 1MB - 4MB).
- Components NEVER store unbounded arrays of outgoing payloads in client socket metadata or process memory without strict capacity rejection.

## Bad vs Good Implementations
### Unbounded Fanout Broadcast vs. Backpressure-Aware Bounded High-Watermark Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating over all connected sockets and calling client.send() without inspecting client.getBufferedAmount() or configuring a drain callback causes memory to bloat when clients have limited network throughput. Bun buffers unsent frames on the heap, eventually terminating the process due to unbounded allocation.
```typescript
import { ServerWebSocket } from "bun";

interface ClientData {
  id: string;
}

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

Bun.serve<ClientData>({
  port: 8080,
  websocket: {
    open(ws) {
      clients.add(ws);
    },
    message(ws, message) {
      // CRITICAL VIOLATION: Unchecked broadcast fanout.
      // Slow consumer sockets buffer infinitely in user/kernel space,
      // consuming massive memory and triggering Bun process OOM crash.
      for (const client of clients) {
        client.send(message);
      }
    },
    close(ws) {
      clients.delete(ws);
    },
  },
  fetch(req, server) {
    server.upgrade(req, { data: { id: crypto.randomUUID() } });
    return undefined;
  },
});
```

#### Production Standard (Correct)
> **Standard**: Enforces a per-socket 512KB high-watermark threshold using ws.getBufferedAmount(). Slow consumers that exceed the watermark buffer a bounded number of frames and pause immediate sends. The websocket.drain hook flushes the bounded queue once the OS socket buffer empties. If a slow consumer exceeds the bounded queue capacity, it is terminated with 1008 to protect the runtime.
```typescript
import { ServerWebSocket } from "bun";

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

const HIGH_WATERMARK_BYTES = 1024 * 512; // 512 KB per socket
const MAX_PENDING_QUEUE = 32;
const clients = new Set<ServerWebSocket<ClientData>>();

function dispatchPayload(ws: ServerWebSocket<ClientData>, payload: string): void {
  const currentBuffered = ws.getBufferedAmount();

  // Strict drop or terminate policy for pathological slow consumers
  if (currentBuffered >= HIGH_WATERMARK_BYTES) {
    ws.data.isBackpressured = true;
    if (ws.data.pendingQueue.length >= MAX_PENDING_QUEUE) {
      // Client is falling unrecoverably behind; terminate to protect the shared heap
      ws.close(1008, "Backpressure limit exceeded");
      clients.delete(ws);
      return;
    }
    ws.data.pendingQueue.push(payload);
    return;
  }

  // ws.send returns the number of bytes queued or sent
  const sentOrQueued = ws.send(payload);
  if (sentOrQueued < 0 || ws.getBufferedAmount() >= HIGH_WATERMARK_BYTES) {
    ws.data.isBackpressured = true;
  }
}

Bun.serve<ClientData>({
  port: 8080,
  websocket: {
    open(ws) {
      ws.data.isBackpressured = false;
      ws.data.pendingQueue = [];
      clients.add(ws);
    },
    message(ws, message) {
      const payload = typeof message === "string" ? message : new TextDecoder().decode(message);
      for (const client of clients) {
        dispatchPayload(client, payload);
      }
    },
    drain(ws) {
      // Invariant: drain is called when socket buffer drops below backpressure watermark
      while (ws.data.pendingQueue.length > 0 && ws.getBufferedAmount() < HIGH_WATERMARK_BYTES) {
        const queuedItem = ws.data.pendingQueue.shift()!;
        ws.send(queuedItem);
      }
      if (ws.data.pendingQueue.length === 0 && ws.getBufferedAmount() < HIGH_WATERMARK_BYTES) {
        ws.data.isBackpressured = false;
      }
    },
    close(ws) {
      clients.delete(ws);
    },
  },
  fetch(req, server) {
    server.upgrade(req, {
      data: {
        id: crypto.randomUUID(),
        isBackpressured: false,
        pendingQueue: [],
      },
    });
    return undefined;
  },
});
```

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 Backpressure and High-Watermark Drain Management

Bun 1.2 Native WebSocket Backpressure and High-Watermark Drain Management defines an industrial-grade behavioral standard for backend engineering. Enforces strict per-socket buffered amount verification and cooperative backpressure in Bun 1.2 native WebSockets. Mandates drain lifecycle handler implementation and high-watermark boundaries to eliminate unbounded heap growth and process-level OOM crashes during high-throughput message fanouts. 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: Unchecked ws.send() Loop Fanout Leading to Silent Buffer Bloat and Fatal OOM Disruption 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 DriftUnchecked ws.send() Loop Fanout Leading to Silent Buffer Bloat and Fatal OOM DisruptionCritical
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 check ws.getBufferedAmount() before sending messages in high-volume paths or observe backpressure return values from ws.send().

Engineers MUST ALWAYS check ws.getBufferedAmount() before sending messages in high-volume paths or observe backpressure return values from ws.send().

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 execute blind fanout loops over client collections without validating per-socket queued buffer levels against a defined high-watermark threshold.

Engineers MUST NOT execute blind fanout loops over client collections without validating per-socket queued buffer levels against a defined high-watermark threshold.

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 define a websocket.drain handler in Bun.serve to resume suspended publishers or flush pending ring-buffered frames when kernel/socket buffers clear.

Services MUST define a websocket.drain handler in Bun.serve to resume suspended publishers or flush pending ring-buffered frames when kernel/socket buffers clear.

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 immediately terminate slow consumers with status code 1008 (Policy Violation) or 1011 (Internal Error) if their individual bufferedAmount exceeds the max safety allocation ceiling (e.g., 1MB - 4MB).

Code SHOULD immediately terminate slow consumers with status code 1008 (Policy Violation) or 1011 (Internal Error) if their individual bufferedAmount exceeds the max safety allocation ceiling (e.g., 1MB - 4MB).

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 in client socket metadata or process memory without strict capacity rejection.

Components NEVER store unbounded arrays of outgoing payloads in client socket metadata or process memory without strict capacity rejection.

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 Backpressure and High-Watermark Drain Management critical for AI coding assistants?

Enforces strict per-socket buffered amount verification and cooperative backpressure in Bun 1.2 native WebSockets. Mandates drain lifecycle handler implementation and high-watermark boundaries to eliminate unbounded heap growth and process-level OOM crashes during high-throughput message fanouts. 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 (Unchecked ws.send() Loop Fanout Leading to Silent Buffer Bloat and Fatal OOM Disruption) 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