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

Bun 1.2 Native Clustered WebSocket Memory-Drain Backpressure Invariant

Enforces deterministic high-watermark socket buffering and non-blocking backpressure drain policies for Bun 1.2 clustered native WebSockets. Eliminates silent OOM crashes, buffer starvation, and runaway worker heap allocation under slow-consumer scenarios by requiring explicit return code evaluation from `ws.send()` and coordinated `drain` lifecycle handler implementation.

Prohibited Anti-Pattern: Unchecked Fire-and-Forget `ws.send()` Leading to Silent Out-Of-Memory Panics in Bun Worker Clusters

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Clustered WebSocket Memory-Drain Backpressure Invariant - Enforces deterministic high-watermark socket buffering and non-blocking backpressure drain policies for Bun 1.2 clustered native WebSockets. Eliminates silent OOM crashes, buffer starvation, and runaway worker heap allocation under slow-consumer scenarios by requiring explicit return code evaluation from `ws.send()` and coordinated `drain` lifecycle handler implementation.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}, workers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-v12-clustered-websocket-backpressure-drain-guardrail"
---

# Bun 1.2 Native Clustered WebSocket Memory-Drain Backpressure Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Fire-and-Forget `ws.send()` Leading to Silent Out-Of-Memory Panics in Bun Worker Clusters

## System Constraints
You are a Principal Backend Architect enforcing strict memory safety and non-blocking backpressure invariants across Bun 1.2 native clustered WebSocket topologies. Mandate deterministic buffering thresholds, explicit handling of `ws.send()` return codes, and mandatory integration of the `drain(ws)` socket lifecycle handler. Never allow unthrottled message pumping or unbounded in-memory queues per socket.

## Strict Guidelines
- Engineers MUST ALWAYS evaluate the numeric return value of `ws.send(data)` (where -1 indicates dropped/backpressured, 0 indicates dropped due to closure/error, and > 0 indicates byte count dispatched or queued).
- Engineers MUST pause producer streams or suspend message dispatch loops immediately when `ws.isBackpressured` evaluates to true or when `ws.bufferedAmount` breaches the configured high-watermark threshold.
- Engineers MUST implement the native Bun WebSocket `drain(ws)` callback in the server definition to resume paused producer streams when socket kernel/userland buffers drain.
- Engineers MUST NOT maintain unconstrained in-memory JavaScript arrays or unbounded queues per socket instance to compensate for slow network consumers.
- Services MUST configure explicit `maxPayloadLength` and strict socket timeout invariants in `Bun.serve({ websocket: { ... } })` to protect cluster worker heaps from runaway allocations.
- Engineers MUST terminate recalcitrant or perpetually backpressured sockets using `ws.close(1008, 'Policy Violation: Backpressure Timeout')` after a bounded deadline.

## Bad vs Good Implementations
### Unchecked Socket Broadcast vs. Deterministic High-Watermark Drain Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `ws.send()` without inspecting `ws.bufferedAmount`, checking the send return value, or configuring a `drain` callback causes unbounded userland buffer growth in uSockets/Bun runtime when consumers read slower than the producer writes, inevitably terminating the cluster worker via an uncatchable heap/OOM crash.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientData {
  id: string;
}

// Anti-pattern: Blindly iterating and sending data without checking backpressure or implementing drain
export function broadcastMarketData(sockets: Set<ServerWebSocket<ClientData>>, payload: string) {
  for (const ws of sockets) {
    // Under slow network conditions, kernel buffers saturate, userland buffers explode, and Bun worker triggers an unrecoverable OOM.
    ws.send(payload);
  }
}

Bun.serve<ClientData>({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID() } })) return;
    return new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    message(ws, message) {
      // No drain handler configured; silent memory accumulation
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic backpressure handling by observing `ws.bufferedAmount` against `HIGH_WATERMARK_BYTES`, validates the return code of `ws.send()`, leverages `backpressureLimit`, bounds queued elements to prevent memory leakage, and uses native `drain(ws)` to drain pending payloads safely.
```typescript
import { ServerWebSocket } from 'bun';

interface SocketState {
  id: string;
  isPaused: boolean;
  queue: string[];
}

const HIGH_WATERMARK_BYTES = 1024 * 1024; // 1 MB
const MAX_QUEUE_DEPTH = 50;

export function dispatchMessage(ws: ServerWebSocket<SocketState>, message: string): boolean {
  if (ws.bufferedAmount > HIGH_WATERMARK_BYTES) {
    ws.data.isPaused = true;
    if (ws.data.queue.length >= MAX_QUEUE_DEPTH) {
      ws.close(1008, 'Buffer overflow: Consumer exceeded backpressure limit');
      return false;
    }
    ws.data.queue.push(message);
    return false;
  }

  const bytesSent = ws.send(message);
  if (bytesSent === -1) {
    // Native backpressure engaged
    ws.data.isPaused = true;
    ws.data.queue.push(message);
    return false;
  }

  return true;
}

Bun.serve<SocketState>({
  port: 8080,
  fetch(req, server) {
    const state: SocketState = { id: crypto.randomUUID(), isPaused: false, queue: [] };
    if (server.upgrade(req, { data: state })) return;
    return new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    maxPayloadLength: 64 * 1024,
    backpressureLimit: HIGH_WATERMARK_BYTES,
    message(ws, message) {
      // Handle client messages safely
    },
    drain(ws) {
      // Socket drained below watermark; flush bounded queue and resume flow
      while (ws.data.queue.length > 0 && ws.bufferedAmount < HIGH_WATERMARK_BYTES) {
        const next = ws.data.queue.shift()!;
        const sent = ws.send(next);
        if (sent === -1) {
          ws.data.queue.unshift(next);
          return;
        }
      }
      if (ws.data.queue.length === 0) {
        ws.data.isPaused = false;
      }
    },
    close(ws) {
      ws.data.queue.length = 0;
    }
  }
});
```

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 Native Clustered WebSocket Memory-Drain Backpressure Invariant

Bun 1.2 Native Clustered WebSocket Memory-Drain Backpressure Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic high-watermark socket buffering and non-blocking backpressure drain policies for Bun 1.2 clustered native WebSockets. Eliminates silent OOM crashes, buffer starvation, and runaway worker heap allocation under slow-consumer scenarios by requiring explicit return code evaluation from `ws.send()` and coordinated `drain` lifecycle handler implementation. 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 Fire-and-Forget `ws.send()` Leading to Silent Out-Of-Memory Panics in Bun Worker Clusters 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 Fire-and-Forget `ws.send()` Leading to Silent Out-Of-Memory Panics in Bun Worker ClustersCritical
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 evaluate the numeric return value of `ws.send(data)` (where -1 indicates dropped/backpressured, 0 indicates dropped due to closure/error, and > 0 indicates byte count dispatched or queued).

Engineers MUST ALWAYS evaluate the numeric return value of `ws.send(data)` (where -1 indicates dropped/backpressured, 0 indicates dropped due to closure/error, and > 0 indicates byte count dispatched or queued).

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 pause producer streams or suspend message dispatch loops immediately when `ws.isBackpressured` evaluates to true or when `ws.bufferedAmount` breaches the configured high-watermark threshold.

Engineers MUST pause producer streams or suspend message dispatch loops immediately when `ws.isBackpressured` evaluates to true or when `ws.bufferedAmount` breaches the configured 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

Engineers MUST implement the native Bun WebSocket `drain(ws)` callback in the server definition to resume paused producer streams when socket kernel/userland buffers drain.

Engineers MUST implement the native Bun WebSocket `drain(ws)` callback in the server definition to resume paused producer streams when socket kernel/userland buffers drain.

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

Engineers MUST NOT maintain unconstrained in-memory JavaScript arrays or unbounded queues per socket instance to compensate for slow network consumers.

Engineers MUST NOT maintain unconstrained in-memory JavaScript arrays or unbounded queues per socket instance to compensate for slow network consumers.

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 configure explicit `maxPayloadLength` and strict socket timeout invariants in `Bun.serve({ websocket

Services MUST configure explicit `maxPayloadLength` and strict socket timeout invariants in `Bun.serve({ websocket: { ... } })` to protect cluster worker heaps from runaway allocations.

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.
6

Engineers MUST terminate recalcitrant or perpetually backpressured sockets using `ws.close(1008, 'Policy Violation

Engineers MUST terminate recalcitrant or perpetually backpressured sockets using `ws.close(1008, 'Policy Violation: Backpressure Timeout')` after a bounded deadline.

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 Clustered WebSocket Memory-Drain Backpressure Invariant critical for AI coding assistants?

Enforces deterministic high-watermark socket buffering and non-blocking backpressure drain policies for Bun 1.2 clustered native WebSockets. Eliminates silent OOM crashes, buffer starvation, and runaway worker heap allocation under slow-consumer scenarios by requiring explicit return code evaluation from `ws.send()` and coordinated `drain` lifecycle handler implementation. 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 Fire-and-Forget `ws.send()` Leading to Silent Out-Of-Memory Panics in Bun Worker Clusters) 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