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 Native WebSocket Backpressure & Auto-Paced Drain Invariant

Enforces strict backpressure handling and drain threshold auto-pacing on native Bun 1.2 WebSocket connections. Prevents silent C++ uSockets buffer accumulation, event-loop starvation, and native heap exhaustion under high-throughput concurrent loads by mandating backpressure state inspection and asynchronous stream suspension until native drain hooks fire.

Prohibited Anti-Pattern: Unchecked Native ws.send() Broadcasting Without Drain Listeners or High-Water Mark Throttling

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure & Auto-Paced Drain Invariant - Enforces strict backpressure handling and drain threshold auto-pacing on native Bun 1.2 WebSocket connections. Prevents silent C++ uSockets buffer accumulation, event-loop starvation, and native heap exhaustion under high-throughput concurrent loads by mandating backpressure state inspection and asynchronous stream suspension until native drain hooks fire.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-backpressure-drain-invariant"
---

# Bun 1.2 Native WebSocket Backpressure & Auto-Paced Drain Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Native ws.send() Broadcasting Without Drain Listeners or High-Water Mark Throttling

## System Constraints
You are a Principal Backend Engineer enforcing strict native backpressure and memory invariants for Bun 1.2 WebSockets. Bun builds on native uSockets: `ws.send()` returns -1 when backpressure is initiated, 0 when dropped or closed, and a positive byte count when flushed immediately. You must mandate that every high-throughput or streaming native Bun WebSocket implementation implements the `drain(ws)` lifecycle callback, monitors `ws.getBufferedAmount()`, and applies high/low watermark throttling to upstream producers to prevent memory leaks and event-loop lag.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the return code of `ws.send()`: a return value of -1 indicates backpressure queued, and 0 indicates dropped or failed delivery.
- Engineers MUST implement the native `drain(ws: ServerWebSocket<T>)` handler in the `Bun.serve` websocket configuration to unpause upstream producers or resume throttled queues.
- Engineers MUST NOT perform unthrottled iteration over large sets of sockets using synchronous `ws.send()` without validating `ws.getBufferedAmount()` against a strict high-water mark.
- Services MUST pause stream readers (e.g., Redis Pub/Sub, Postgres CDC, native ReadableStreams) whenever a socket's buffered bytes exceed the defined `HIGH_WATERMARK` threshold.
- Code SHOULD define explicit low-water mark thresholds (e.g., `LOW_WATERMARK = HIGH_WATERMARK / 4`) within `drain` to prevent ping-pong thrashing between paused and resumed states.
- Components NEVER allow unbounded in-memory array queues for slow consumers; unrecoverable lagging sockets exceeding maximum buffer limits MUST be dropped or terminated cleanly.

## Bad vs Good Implementations
### Native WebSocket Pacing via Drain and Watermark Invariants

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly pumping messages without monitoring `ws.send()` or `ws.getBufferedAmount()` bypasses backpressure limits. In Bun 1.2, unchecked native allocations build up inside the underlying uSockets C++ layer, invisible to the V8/JSC garbage collector until an uncatchable heap exhaustion or event-loop stall kills the process.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface ClientData { id: string; }

serve<ClientData>({
  port: 3000,
  fetch(req, server) {
    server.upgrade(req, { data: { id: crypto.randomUUID() } });
    return new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    message(ws, message) {
      // CRITICAL BUG: Blind loop ignores ws.send() return code (-1 / 0)
      // and ignores ws.getBufferedAmount(). Floods native uSockets C++ buffer
      // causing event-loop stall and silent OOM crash under massive socket fan-out.
      for (let i = 0; i < 100_000; i++) {
        ws.send(`event-payload-${i}`);
      }
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements the native `drain` callback and enforces `HIGH_WATERMARK` / `LOW_WATERMARK` checks against `ws.getBufferedAmount()` and `ws.send()`. Halts writes when native buffers are saturated and smoothly resumes upstream generation only after the buffer drains below the safe threshold.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface SocketData {
  id: string;
  isPaused: boolean;
  streamController?: ReadableStreamDefaultReader<Uint8Array>;
}

const HIGH_WATERMARK = 1024 * 1024; // 1 MB backpressure ceiling
const LOW_WATERMARK = 256 * 1024;   // 256 KB resume threshold

export const server = serve<SocketData>({
  port: 3000,
  fetch(req, srv) {
    const upgraded = srv.upgrade(req, {
      data: { id: crypto.randomUUID(), isPaused: false }
    });
    return upgraded ? undefined : new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    open(ws: ServerWebSocket<SocketData>) {
      ws.data.isPaused = false;
    },
    message(ws: ServerWebSocket<SocketData>, message) {
      // Enforce backpressure check on individual writes
      const sendResult = ws.send(message);
      if (sendResult === -1 || ws.getBufferedAmount() > HIGH_WATERMARK) {
        ws.data.isPaused = true;
      }
    },
    drain(ws: ServerWebSocket<SocketData>) {
      // Triggered by Bun's native uSockets when socket buffer drains
      if (ws.data.isPaused && ws.getBufferedAmount() <= LOW_WATERMARK) {
        ws.data.isPaused = false;
        // Resume paused generator, reader, or dispatch next queued frame
      }
    },
    close(ws: ServerWebSocket<SocketData>, code, reason) {
      if (ws.data.streamController) {
        void ws.data.streamController.cancel();
      }
    }
  }
});
```

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 & Auto-Paced Drain Invariant

Bun 1.2 Native WebSocket Backpressure & Auto-Paced Drain Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict backpressure handling and drain threshold auto-pacing on native Bun 1.2 WebSocket connections. Prevents silent C++ uSockets buffer accumulation, event-loop starvation, and native heap exhaustion under high-throughput concurrent loads by mandating backpressure state inspection and asynchronous stream suspension until native drain hooks fire. 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 Native ws.send() Broadcasting Without Drain Listeners or High-Water Mark Throttling 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 Native ws.send() Broadcasting Without Drain Listeners or High-Water Mark ThrottlingCritical
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 return code of `ws.send()`

Engineers MUST ALWAYS inspect the return code of `ws.send()`: a return value of -1 indicates backpressure queued, and 0 indicates dropped or failed delivery.

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

Engineers MUST implement the native `drain(ws: ServerWebSocket<T>)` handler in the `Bun.serve` websocket configuration to unpause upstream producers or resume throttled queues.

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 iteration over large sets of sockets using synchronous `ws.send()` without validating `ws.getBufferedAmount()` against a strict high-water mark.

Engineers MUST NOT perform unthrottled iteration over large sets of sockets using synchronous `ws.send()` without validating `ws.getBufferedAmount()` against a strict high-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.
4

Services MUST pause stream readers (e.g., Redis Pub/Sub, Postgres CDC, native ReadableStreams) whenever a socket's buffered bytes exceed the defined `HIGH_WATERMARK` threshold.

Services MUST pause stream readers (e.g., Redis Pub/Sub, Postgres CDC, native ReadableStreams) whenever a socket's buffered bytes exceed the 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.
5

Code SHOULD define explicit low-water mark thresholds (e.g., `LOW_WATERMARK = HIGH_WATERMARK / 4`) within `drain` to prevent ping-pong thrashing between paused and resumed states.

Code SHOULD define explicit low-water mark thresholds (e.g., `LOW_WATERMARK = HIGH_WATERMARK / 4`) within `drain` to prevent ping-pong thrashing between paused and resumed states.

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

Components NEVER allow unbounded in-memory array queues for slow consumers

Components NEVER allow unbounded in-memory array queues for slow consumers; unrecoverable lagging sockets exceeding maximum buffer limits MUST be dropped or terminated cleanly.

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 & Auto-Paced Drain Invariant critical for AI coding assistants?

Enforces strict backpressure handling and drain threshold auto-pacing on native Bun 1.2 WebSocket connections. Prevents silent C++ uSockets buffer accumulation, event-loop starvation, and native heap exhaustion under high-throughput concurrent loads by mandating backpressure state inspection and asynchronous stream suspension until native drain hooks fire. 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 Native ws.send() Broadcasting Without Drain Listeners or High-Water Mark Throttling) 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