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

Bun 1.2 Native WebSocket Backpressure & High-Water Mark Drainage Invariant

Enforces proactive high-water mark throttling, buffer size verification, and per-socket queue shedding on Bun 1.2 ServerWebSocket instances. Prevents process-level heap exhaustion and unmonitored bufferedAmount accumulation during high-frequency pub/sub broadcasts to slow consumers.

Prohibited Anti-Pattern: Unchecked ws.send() Broadcasting and Omission of Native drain() Handlers Inducing Memory Bloat

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure & High-Water Mark Drainage Invariant - Enforces proactive high-water mark throttling, buffer size verification, and per-socket queue shedding on Bun 1.2 ServerWebSocket instances. Prevents process-level heap exhaustion and unmonitored bufferedAmount accumulation during high-frequency pub/sub broadcasts to slow consumers.
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-backpressure-drainage-invariant"
---

# Bun 1.2 Native WebSocket Backpressure & High-Water Mark Drainage Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked ws.send() Broadcasting and Omission of Native drain() Handlers Inducing Memory Bloat

## System Constraints
You are a Principal Backend Architect enforcing strict backpressure hygiene for Bun 1.2 native WebSockets. Unchecked calls to `ws.send()` during fan-out broadcasts accumulate native C++ send buffers, creating invisible memory spikes that bypass V8/JSC GC thresholds until the Bun runtime encounters an unrecoverable out-of-memory crash. You must mandate strict bufferedAmount inspection, high-water mark policies, shedding/termination of pathological consumers, and reactive queue drainage via the native `drain` callback.

## Strict Guidelines
- Engineers MUST ALWAYS inspect `ws.bufferedAmount` against an explicit High-Water Mark (HWM) before dispatching high-volume payloads via `ws.send()`.
- Engineers MUST implement the native `drain(ws)` lifecycle callback in `Bun.serve({ websocket: { ... } })` to clear backpressure flags and resume throttled streams.
- Engineers MUST NOT maintain secondary unbounded JavaScript arrays as userland buffers for slow WebSocket consumers.
- Services MUST terminate chronically lagging connections with WebSocket close code 1008 (Policy Violation) if buffered frames exceed maximum tolerable limits (Hard Water Mark).
- Broadcasters MUST shed non-critical telemetry or real-time tick frames immediately when individual peer backpressure is active instead of stalling the event loop.

## Bad vs Good Implementations
### Unbounded Fan-out Broadcast vs. Backpressure-Aware Drainage with Shedding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling server.publish() or looping over ws.send() without monitoring bufferedAmount or handling drainage creates silent native buffer accumulation when consumers lag. Bun cannot garbage collect un-transmitted C++ socket buffers, causing deterministic OOM crashes under burst traffic.
```typescript
import { serve } from 'bun';

type ClientData = { id: string };

const server = serve<ClientData>({
  port: 3000,
  fetch(req, server) {
    server.upgrade(req, { data: { id: crypto.randomUUID() } });
    return new Response('Upgrading', { status: 101 });
  },
  websocket: {
    message(ws, message) {},
    open(ws) {}
  }
});

// Anti-pattern: Broadcasts directly to all sockets without checking backpressure.
// Slow clients accumulate megabytes of un-drained native buffers in Bun's C++ layer.
export function broadcastEvent(event: Record<string, unknown>) {
  const payload = JSON.stringify(event);
  // server.publish or iterating sockets blindly creates invisible memory inflation
  server.publish('market-feed', payload);
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation strictly monitors `ws.bufferedAmount` against explicit High-Water (512KB) and Hard-Limit (2MB) marks. When congestion occurs, non-critical frames are shed immediately, abusive/slow consumers are severed with code 1008, and the native `drain` hook guarantees resumption of traffic only after buffer clearance.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface SocketState {
  id: string;
  isBackpressured: boolean;
}

const BUFFER_HIGH_WATER_MARK = 1024 * 512; // 512 KB
const BUFFER_CRITICAL_LIMIT = 1024 * 1024 * 2; // 2 MB

const server = serve<SocketState>({
  port: 3000,
  fetch(req, server) {
    const success = server.upgrade(req, {
      data: { id: crypto.randomUUID(), isBackpressured: false }
    });
    return success ? undefined : new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    open(ws: ServerWebSocket<SocketState>) {
      ws.subscribe('market-feed');
    },
    message(ws: ServerWebSocket<SocketState>, message) {
      // Standard message handling
    },
    drain(ws: ServerWebSocket<SocketState>) {
      // Invariant: Native drain callback is triggered when bufferedAmount drops
      if (ws.bufferedAmount < BUFFER_HIGH_WATER_MARK) {
        ws.data.isBackpressured = false;
      }
    },
    close(ws: ServerWebSocket<SocketState>) {
      ws.unsubscribe('market-feed');
    }
  }
});

export function safeDispatch(ws: ServerWebSocket<SocketState>, data: string | Uint8Array): boolean {
  if (ws.bufferedAmount >= BUFFER_CRITICAL_LIMIT) {
    // Terminate slow consumer exceeding hard safety boundary
    ws.close(1008, 'Slow consumer exceeded backpressure limit');
    return false;
  }

  if (ws.bufferedAmount >= BUFFER_HIGH_WATER_MARK) {
    ws.data.isBackpressured = true;
    // Shed non-critical message frame rather than amplifying memory
    return false;
  }

  const sentBytes = ws.send(data);
  return sentBytes > 0;
}
```

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 & High-Water Mark Drainage Invariant

Bun 1.2 Native WebSocket Backpressure & High-Water Mark Drainage Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces proactive high-water mark throttling, buffer size verification, and per-socket queue shedding on Bun 1.2 ServerWebSocket instances. Prevents process-level heap exhaustion and unmonitored bufferedAmount accumulation during high-frequency pub/sub broadcasts to slow consumers. 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() Broadcasting and Omission of Native drain() Handlers Inducing Memory Bloat 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() Broadcasting and Omission of Native drain() Handlers Inducing Memory BloatCritical
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.bufferedAmount` against an explicit High-Water Mark (HWM) before dispatching high-volume payloads via `ws.send()`.

Engineers MUST ALWAYS inspect `ws.bufferedAmount` against an explicit High-Water Mark (HWM) before dispatching high-volume payloads via `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 implement the native `drain(ws)` lifecycle callback in `Bun.serve({ websocket

Engineers MUST implement the native `drain(ws)` lifecycle callback in `Bun.serve({ websocket: { ... } })` to clear backpressure flags and resume throttled streams.

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 maintain secondary unbounded JavaScript arrays as userland buffers for slow WebSocket consumers.

Engineers MUST NOT maintain secondary unbounded JavaScript arrays as userland buffers for slow WebSocket 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.
4

Services MUST terminate chronically lagging connections with WebSocket close code 1008 (Policy Violation) if buffered frames exceed maximum tolerable limits (Hard Water Mark).

Services MUST terminate chronically lagging connections with WebSocket close code 1008 (Policy Violation) if buffered frames exceed maximum tolerable limits (Hard Water Mark).

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

Broadcasters MUST shed non-critical telemetry or real-time tick frames immediately when individual peer backpressure is active instead of stalling the event loop.

Broadcasters MUST shed non-critical telemetry or real-time tick frames immediately when individual peer backpressure is active instead of stalling 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.
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 & High-Water Mark Drainage Invariant critical for AI coding assistants?

Enforces proactive high-water mark throttling, buffer size verification, and per-socket queue shedding on Bun 1.2 ServerWebSocket instances. Prevents process-level heap exhaustion and unmonitored bufferedAmount accumulation during high-frequency pub/sub broadcasts to slow consumers. 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() Broadcasting and Omission of Native drain() Handlers Inducing Memory Bloat) 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