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

Bun 1.2 Native WebSocket Backpressure & Drain Invariant

Mandates backpressure-aware socket drain monitoring and buffer watermarking on native Bun.serve WebSockets during high-throughput or bursty pub/sub workloads. Uncontrolled socket writes without buffer checks or drain lifecycle handlers lead to unbounded native memory accumulation and silent event-loop starvation.

Prohibited Anti-Pattern: Fire-and-Forget WebSocket Broadcasts Lacking Buffer Inspection and Drain Callbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure & Drain Invariant - Mandates backpressure-aware socket drain monitoring and buffer watermarking on native Bun.serve WebSockets during high-throughput or bursty pub/sub workloads. Uncontrolled socket writes without buffer checks or drain lifecycle handlers lead to unbounded native memory accumulation and silent event-loop starvation.
globs: src/**/*.ts, server/**/*.ts, services/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-backpressure-drainage-boundary"
---

# Bun 1.2 Native WebSocket Backpressure & Drain Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fire-and-Forget WebSocket Broadcasts Lacking Buffer Inspection and Drain Callbacks

## System Constraints
You are a Principal Backend Architect enforcing Bun 1.2 native WebSocket backpressure discipline. Native sockets in Bun allocate memory outside the V8/JSC heap directly in native uWebSockets buffers. You must mandate strict high-water mark validation via ws.getBufferedAmount(), require the implementation of websocket.drain(ws) handlers, and enforce slow-consumer eviction to guarantee deterministic memory safety under load.

## Strict Guidelines
- Engineers MUST ALWAYS implement the `drain(ws)` lifecycle callback in `Bun.serve({ websocket: { drain(ws) { ... } } })` whenever emitting streamed or bursty broadcast messages.
- Engineers MUST inspect `ws.getBufferedAmount()` against a defined High-Water Mark (HWM) before enqueueing additional binary or text frames.
- Engineers MUST NOT call `ws.send()` in unbounded loops across subscriber arrays without evaluating individual socket saturation.
- Code MUST isolate pending frame chunks into bounded outbound queues or explicitly pause producers when a socket's buffered amount exceeds safe thresholds.
- Services MUST evict toxic slow-consumer clients via `ws.close(1008, ...)` if buffered memory crosses critical degradation limits (e.g., > 4MB buffered).
- Components NEVER assume `server.publish()` or `ws.send()` operates with zero-copy infinite buffering without risk of native heap exhaustion.

## Bad vs Good Implementations
### Naive Broadcast Fanout vs. Backpressure-Aware Bounded Queue with Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating across sockets and invoking ws.send() unconditionally ignores underlying TCP buffer saturation. When clients face network latency, Bun queues pending frames in native memory without limit. Without a drain handler and buffer bounds, high-frequency producers cause uncontrollable memory leaks and process crashes.
```typescript
import { ServerWebSocket } from "bun";

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

Bun.serve({
  port: 8080,
  websocket: {
    open(ws) {
      clients.add(ws);
    },
    close(ws) {
      clients.delete(ws);
    },
    message(ws, msg) {},
    // VIOLATION: Missing drain handler to recover from high-water mark backpressure
  },
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("Upgrade failed", { status: 400 });
  },
});

// ANTI-PATTERN: Blindly pushing bursts to all clients without checking buffer saturation
export function broadcastTelemetry(payload: Uint8Array) {
  for (const ws of clients) {
    // Slow network clients will accumulate native buffers until OOM occurs
    ws.send(payload);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit backpressure boundary using ws.getBufferedAmount(), queues overflow frames when buffer bounds are reached, and consumes the queue deterministically via the native drain(ws) callback. Toxic slow consumers exceeding safe upper bounds are terminated cleanly.
```typescript
import { ServerWebSocket } from "bun";

interface ClientState {
  id: string;
  paused: boolean;
  queue: Uint8Array[];
}

const HIGH_WATER_MARK = 1024 * 512; // 512 KB
const MAX_BUFFER_LIMIT = 1024 * 1024 * 4; // 4 MB eviction threshold

Bun.serve<ClientState>({
  port: 8080,
  websocket: {
    open(ws) {
      ws.data = { id: crypto.randomUUID(), paused: false, queue: [] };
    },
    drain(ws) {
      // SINK: Drain callback notifies when native buffer is ready for more frames
      const state = ws.data;
      while (state.queue.length > 0 && ws.getBufferedAmount() < HIGH_WATER_MARK) {
        const chunk = state.queue.shift();
        if (chunk) ws.send(chunk);
      }
      if (state.queue.length === 0) {
        state.paused = false;
      }
    },
    close(ws) {
      ws.data.queue = [];
    },
    message() {},
  },
  fetch(req, server) {
    const state: ClientState = { id: crypto.randomUUID(), paused: false, queue: [] };
    if (server.upgrade(req, { data: state })) return;
    return new Response("Upgrade failed", { status: 400 });
  },
});

export function sendSafe(ws: ServerWebSocket<ClientState>, chunk: Uint8Array): void {
  const currentBuffered = ws.getBufferedAmount();

  // Enforce boundary: Evict persistent slow consumers that exceed critical buffer
  if (currentBuffered > MAX_BUFFER_LIMIT) {
    ws.close(1008, "Policy Violation: Buffer Overflow");
    return;
  }

  if (ws.data.paused || currentBuffered >= HIGH_WATER_MARK) {
    ws.data.paused = true;
    ws.data.queue.push(chunk);
    return;
  }

  ws.send(chunk);
}
```

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

Bun 1.2 Native WebSocket Backpressure & Drain Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates backpressure-aware socket drain monitoring and buffer watermarking on native Bun.serve WebSockets during high-throughput or bursty pub/sub workloads. Uncontrolled socket writes without buffer checks or drain lifecycle handlers lead to unbounded native memory accumulation and silent event-loop starvation. 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: Fire-and-Forget WebSocket Broadcasts Lacking Buffer Inspection and Drain Callbacks 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 DriftFire-and-Forget WebSocket Broadcasts Lacking Buffer Inspection and Drain CallbacksCritical
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 implement the `drain(ws)` lifecycle callback in `Bun.serve({ websocket

Engineers MUST ALWAYS implement the `drain(ws)` lifecycle callback in `Bun.serve({ websocket: { drain(ws) { ... } } })` whenever emitting streamed or bursty broadcast messages.

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 inspect `ws.getBufferedAmount()` against a defined High-Water Mark (HWM) before enqueueing additional binary or text frames.

Engineers MUST inspect `ws.getBufferedAmount()` against a defined High-Water Mark (HWM) before enqueueing additional binary or text frames.

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 call `ws.send()` in unbounded loops across subscriber arrays without evaluating individual socket saturation.

Engineers MUST NOT call `ws.send()` in unbounded loops across subscriber arrays without evaluating individual socket saturation.

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 MUST isolate pending frame chunks into bounded outbound queues or explicitly pause producers when a socket's buffered amount exceeds safe thresholds.

Code MUST isolate pending frame chunks into bounded outbound queues or explicitly pause producers when a socket's buffered amount exceeds safe 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

Services MUST evict toxic slow-consumer clients via `ws.close(1008, ...)` if buffered memory crosses critical degradation limits (e.g., > 4MB buffered).

Services MUST evict toxic slow-consumer clients via `ws.close(1008, ...)` if buffered memory crosses critical degradation limits (e.g., > 4MB buffered).

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 assume `server.publish()` or `ws.send()` operates with zero-copy infinite buffering without risk of native heap exhaustion.

Components NEVER assume `server.publish()` or `ws.send()` operates with zero-copy infinite buffering without risk of native heap exhaustion.

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

Mandates backpressure-aware socket drain monitoring and buffer watermarking on native Bun.serve WebSockets during high-throughput or bursty pub/sub workloads. Uncontrolled socket writes without buffer checks or drain lifecycle handlers lead to unbounded native memory accumulation and silent event-loop starvation. 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 (Fire-and-Forget WebSocket Broadcasts Lacking Buffer Inspection and Drain Callbacks) 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