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

Bun 1.2 Clustered WebSocket Native Backpressure & Memory Bounding Guardrail

Enforces strict native backpressure monitoring and memory bounding across multi-core Bun 1.2 WebSocket workers running with SO_REUSEPORT. Mandates active buffered-amount validation, drain hook orchestration, and explicit slow-consumer eviction to eliminate cascading Out-Of-Memory (OOM) worker panics during broadcast surges.

Prohibited Anti-Pattern: Unbounded Direct Broadcast Loops Silently Buffering Payload Queues to Worker OOM Termination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Clustered WebSocket Native Backpressure & Memory Bounding Guardrail - Enforces strict native backpressure monitoring and memory bounding across multi-core Bun 1.2 WebSocket workers running with SO_REUSEPORT. Mandates active buffered-amount validation, drain hook orchestration, and explicit slow-consumer eviction to eliminate cascading Out-Of-Memory (OOM) worker panics during broadcast surges.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-cluster-websocket-backpressure-bounding"
---

# Bun 1.2 Clustered WebSocket Native Backpressure & Memory Bounding Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Direct Broadcast Loops Silently Buffering Payload Queues to Worker OOM Termination

## System Constraints
You are a Principal Backend Systems Architect enforcing strict Bun 1.2 WebSocket backpressure management and memory bounding. Bun utilizes uWebSockets under the hood; invoking ws.send() or server.publish() without evaluating ws.getBufferedAmount() causes native C++ buffers to balloon unbounded in the event loop, provoking sudden kernel SIGKILL crashes across clustered workers. Mandate explicit backpressure thresholds, drain hooks, and slow-consumer eviction policies.

## Strict Guidelines
- Engineers MUST ALWAYS inspect ws.getBufferedAmount() against a defined high-water mark (e.g., 512KB) before pushing high-frequency frames to individual clients.
- Engineers MUST implement the WebSocket 'drain(ws)' lifecycle hook to resume paused producer streams when socket buffers drop below low-water marks.
- Engineers MUST NOT perform unthrottled, unbounded array iteration invoking ws.send() across thousands of connections without verifying socket buffer state.
- Services MUST configure 'backpressureLimit' or explicitly close degraded slow-client connections with close code 1008 (Policy Violation) when buffers surpass emergency thresholds.
- Clustered worker architectures MUST configure 'reusePort: true' within Bun.serve() to balance kernel socket distribution and isolate backpressure spikes across CPU cores.

## Bad vs Good Implementations
### Unbounded WebSocket Broadcast vs. Bounded Backpressure Drain Control

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking ws.send() unconditionally across all connected sockets ignores client consumption rates. Unbuffered slow clients accumulate massive native queues in Bun's uWebSockets layer, rapidly exhausting physical server RAM and causing kernel OOM kills across worker processes.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientData { id: string; }
const activeSockets = new Set<ServerWebSocket<ClientData>>();

// ANTI-PATTERN: Indiscriminate synchronous broadcast loop.
// When slow clients lag behind, Bun buffers all messages in native memory,
// rapidly triggering Linux OOM-killer during peak broadcast volume.
export function broadcastMarketData(payload: string) {
  for (const ws of activeSockets) {
    ws.send(payload); // Returns bytes queued, but ignores native buffer growth
  }
}

Bun.serve<ClientData>({
  port: 8080,
  websocket: {
    open(ws) {
      activeSockets.add(ws);
    },
    message(ws, msg) {},
    close(ws) {
      activeSockets.delete(ws);
    }
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID() } })) return;
    return new Response('Expected WebSocket upgrade', { status: 400 });
  }
});
```

#### Production Standard (Correct)
> **Standard**: The production implementation establishes strict memory bounds by checking ws.getBufferedAmount() against high and emergency limits. It gracefully terminates unresponsive slow consumers, marks congested sockets as paused, leverages the native drain() callback to resume when buffers empty, and activates reusePort: true for resilient multi-process clustering.
```typescript
import { ServerWebSocket } from 'bun';

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

const HIGH_WATERMARK_BYTES = 512 * 1024; // 512 KB
const EMERGENCY_DROP_LIMIT = 2 * 1024 * 1024; // 2 MB
const activeSockets = new Set<ServerWebSocket<ClientData>>();

export function safeBroadcast(payload: Uint8Array | string) {
  for (const ws of activeSockets) {
    const buffered = ws.getBufferedAmount();

    if (buffered >= EMERGENCY_DROP_LIMIT) {
      // Hard drop slow consumers starving worker memory pool
      ws.close(1008, 'Buffer overflow: client too slow');
      activeSockets.delete(ws);
      continue;
    }

    if (buffered >= HIGH_WATERMARK_BYTES) {
      // Client is congested; backpressure applied
      ws.data.isPaused = true;
      continue;
    }

    const sendResult = ws.send(payload);
    if (sendResult === 0 || ws.getBufferedAmount() > HIGH_WATERMARK_BYTES) {
      ws.data.isPaused = true;
    }
  }
}

Bun.serve<ClientData>({
  port: 8080,
  reusePort: true, // Multi-core clustered distribution
  websocket: {
    backpressureLimit: EMERGENCY_DROP_LIMIT,
    open(ws) {
      ws.data.isPaused = false;
      activeSockets.add(ws);
    },
    drain(ws) {
      // Triggered natively when bufferedAmount falls to safe levels
      if (ws.getBufferedAmount() < HIGH_WATERMARK_BYTES / 2) {
        ws.data.isPaused = false;
      }
    },
    message(ws, msg) {},
    close(ws) {
      activeSockets.delete(ws);
    }
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID(), isPaused: false } })) return;
    return new Response('Expected WebSocket upgrade', { 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 Clustered WebSocket Native Backpressure & Memory Bounding Guardrail

Bun 1.2 Clustered WebSocket Native Backpressure & Memory Bounding Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict native backpressure monitoring and memory bounding across multi-core Bun 1.2 WebSocket workers running with SO_REUSEPORT. Mandates active buffered-amount validation, drain hook orchestration, and explicit slow-consumer eviction to eliminate cascading Out-Of-Memory (OOM) worker panics during broadcast surges. 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 Direct Broadcast Loops Silently Buffering Payload Queues to Worker OOM Termination 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 Direct Broadcast Loops Silently Buffering Payload Queues to Worker OOM TerminationCritical
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 ws.getBufferedAmount() against a defined high-water mark (e.g., 512KB) before pushing high-frequency frames to individual clients.

Engineers MUST ALWAYS inspect ws.getBufferedAmount() against a defined high-water mark (e.g., 512KB) before pushing high-frequency frames to individual clients.

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 implement the WebSocket 'drain(ws)' lifecycle hook to resume paused producer streams when socket buffers drop below low-water marks.

Engineers MUST implement the WebSocket 'drain(ws)' lifecycle hook to resume paused producer streams when socket buffers drop below low-water marks.

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 perform unthrottled, unbounded array iteration invoking ws.send() across thousands of connections without verifying socket buffer state.

Engineers MUST NOT perform unthrottled, unbounded array iteration invoking ws.send() across thousands of connections without verifying socket buffer state.

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 configure 'backpressureLimit' or explicitly close degraded slow-client connections with close code 1008 (Policy Violation) when buffers surpass emergency thresholds.

Services MUST configure 'backpressureLimit' or explicitly close degraded slow-client connections with close code 1008 (Policy Violation) when buffers surpass emergency thresholds.

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

Clustered worker architectures MUST configure 'reusePort

Clustered worker architectures MUST configure 'reusePort: true' within Bun.serve() to balance kernel socket distribution and isolate backpressure spikes across CPU cores.

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 Clustered WebSocket Native Backpressure & Memory Bounding Guardrail critical for AI coding assistants?

Enforces strict native backpressure monitoring and memory bounding across multi-core Bun 1.2 WebSocket workers running with SO_REUSEPORT. Mandates active buffered-amount validation, drain hook orchestration, and explicit slow-consumer eviction to eliminate cascading Out-Of-Memory (OOM) worker panics during broadcast surges. 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 Direct Broadcast Loops Silently Buffering Payload Queues to Worker OOM Termination) 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