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

Bun 1.2 Native WebSocket Backpressure and Cooperative Drain Architecture

Enforces strict non-blocking backpressure handling on native Bun WebSockets using ws.send() return codes and the drain() callback. Prevents unbounded native heap exhaustion caused by slow consumer stalls during high-frequency telemetry and event distribution.

Prohibited Anti-Pattern: Blind ws.send() Invocations in High-Throughput Loops Leading to Native Buffer Bloat and OOM Crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure and Cooperative Drain Architecture - Enforces strict non-blocking backpressure handling on native Bun WebSockets using ws.send() return codes and the drain() callback. Prevents unbounded native heap exhaustion caused by slow consumer stalls during high-frequency telemetry and event distribution.
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-drain-pipeline"
---

# Bun 1.2 Native WebSocket Backpressure and Cooperative Drain Architecture

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Blind ws.send() Invocations in High-Throughput Loops Leading to Native Buffer Bloat and OOM Crashes

## System Constraints
You are a Principal Systems Architect enforcing memory safety and non-blocking backpressure patterns on Bun 1.2 native WebSocket servers. You must reject fire-and-forget ws.send() architectures in fast producer loops and mandate explicit buffer monitoring with cooperative drain queues.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the numeric return value of `ws.send(data)` or verify `ws.getBufferedAmount()` prior to queueing subsequent outbound frames.
- Engineers MUST NOT assume `ws.send()` operates asynchronously with an internal boundless queue; Bun allocates native buffers for unsent frames which bypass V8/JSC GC thresholds until out-of-memory occurs.
- Services MUST implement the `drain(ws)` lifecycle handler in the Bun server options to resume streaming whenever socket buffers fall back below the safety threshold.
- Engineers MUST maintain an explicit bounded userland buffer or pause upstream asynchronous iterators/event streams when `ws.send()` returns negative or drops below the accepted bytes threshold.
- Systems MUST terminate delinquent connections via `ws.close(1008, 'Policy Violation: Stalled Consumer')` if unbuffered queue limits or timeout thresholds are breached.

## Bad vs Good Implementations
### Backpressure Handling in Bun Native WebSockets

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: ws.send() returns the number of bytes queued or sent. Ignoring this return value and streaming on a fixed tick allows internal socket buffers to balloon when the client is slow, evading garbage collection and triggering hard process termination via OOM.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface ClientState {
  userId: string;
}

serve<ClientState>({
  port: 3000,
  fetch(req, server) {
    server.upgrade(req, { data: { userId: 'usr_100' } });
    return undefined;
  },
  websocket: {
    message(ws, message) {},
    open(ws: ServerWebSocket<ClientState>) {
      // CRITICAL FLAW: Blindly streaming high-frequency data without checking
      // return value or handling buffer backpressure. If the client experiences network
      // jitter or deliberately stalls reads, Bun's internal C++ frame buffer grows indefinitely,
      // leading to catastrophic native memory exhaustion (OOM).
      const interval = setInterval(() => {
        const telemetryFrame = Buffer.alloc(1024 * 64); // 64KB synthetic payload
        ws.send(telemetryFrame);
      }, 1);
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit cooperative drain pattern. Buffers are gated by `ws.getBufferedAmount()` and the return value of `ws.send()`. If socket pressure mounts, messages enter a bounded userland queue, upstream producers are paused, and work resumes via the native `drain(ws)` hook. Stalled consumers exceeding safety ceilings are dropped.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface ClientState {
  userId: string;
  isPaused: boolean;
  pendingQueue: Uint8Array[];
  maxQueueBytes: number;
  currentQueueBytes: number;
}

const MAX_BUFFERED_BYTES = 1024 * 1024; // 1MB native buffer cutoff
const MAX_PENDING_BYTES = 1024 * 512;   // 512KB userland queue cutoff

serve<ClientState>({
  port: 3000,
  fetch(req, server) {
    server.upgrade(req, {
      data: {
        userId: 'usr_100',
        isPaused: false,
        pendingQueue: [],
        maxQueueBytes: MAX_PENDING_BYTES,
        currentQueueBytes: 0
      }
    });
    return undefined;
  },
  websocket: {
    message(ws, message) {},
    open(ws: ServerWebSocket<ClientState>) {
      // Connected
    },
    drain(ws: ServerWebSocket<ClientState>) {
      // COOPERATIVE RESUMPTION: Bun triggers drain when native buffer flushes
      while (ws.data.pendingQueue.length > 0) {
        if (ws.getBufferedAmount() >= MAX_BUFFERED_BYTES) {
          return; // Native buffer full again; wait for next drain
        }

        const nextChunk = ws.data.pendingQueue.shift()!;
        ws.data.currentQueueBytes -= nextChunk.byteLength;
        
        const sent = ws.send(nextChunk);
        if (sent <= 0) {
          // Re-queue if native layer rejected frame
          ws.data.pendingQueue.unshift(nextChunk);
          ws.data.currentQueueBytes += nextChunk.byteLength;
          return;
        }
      }
      ws.data.isPaused = false;
    },
    close(ws: ServerWebSocket<ClientState>, code, reason) {
      ws.data.pendingQueue = [];
      ws.data.currentQueueBytes = 0;
    }
  }
});

export function enqueueTelemetry(ws: ServerWebSocket<ClientState>, payload: Uint8Array): boolean {
  if (ws.data.currentQueueBytes + payload.byteLength > ws.data.maxQueueBytes) {
    // Terminate stalled consumer to protect process integrity
    ws.close(1008, 'Rate limit exceeded: Buffer overflow');
    return false;
  }

  if (ws.data.isPaused || ws.getBufferedAmount() > MAX_BUFFERED_BYTES) {
    ws.data.isPaused = true;
    ws.data.pendingQueue.push(payload);
    ws.data.currentQueueBytes += payload.byteLength;
    return false;
  }

  const sent = ws.send(payload);
  if (sent <= 0) {
    ws.data.isPaused = true;
    ws.data.pendingQueue.push(payload);
    ws.data.currentQueueBytes += payload.byteLength;
    return false;
  }

  return true;
}
```

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 and Cooperative Drain Architecture

Bun 1.2 Native WebSocket Backpressure and Cooperative Drain Architecture defines an industrial-grade behavioral standard for backend engineering. Enforces strict non-blocking backpressure handling on native Bun WebSockets using ws.send() return codes and the drain() callback. Prevents unbounded native heap exhaustion caused by slow consumer stalls during high-frequency telemetry and event distribution. 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: Blind ws.send() Invocations in High-Throughput Loops Leading to Native Buffer Bloat and OOM Crashes 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 DriftBlind ws.send() Invocations in High-Throughput Loops Leading to Native Buffer Bloat and OOM CrashesCritical
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 numeric return value of `ws.send(data)` or verify `ws.getBufferedAmount()` prior to queueing subsequent outbound frames.

Engineers MUST ALWAYS inspect the numeric return value of `ws.send(data)` or verify `ws.getBufferedAmount()` prior to queueing subsequent outbound 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.
2

Engineers MUST NOT assume `ws.send()` operates asynchronously with an internal boundless queue

Engineers MUST NOT assume `ws.send()` operates asynchronously with an internal boundless queue; Bun allocates native buffers for unsent frames which bypass V8/JSC GC thresholds until out-of-memory occurs.

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

Services MUST implement the `drain(ws)` lifecycle handler in the Bun server options to resume streaming whenever socket buffers fall back below the safety threshold.

Services MUST implement the `drain(ws)` lifecycle handler in the Bun server options to resume streaming whenever socket buffers fall back below the safety 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.
4

Engineers MUST maintain an explicit bounded userland buffer or pause upstream asynchronous iterators/event streams when `ws.send()` returns negative or drops below the accepted bytes threshold.

Engineers MUST maintain an explicit bounded userland buffer or pause upstream asynchronous iterators/event streams when `ws.send()` returns negative or drops below the accepted bytes 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

Systems MUST terminate delinquent connections via `ws.close(1008, 'Policy Violation

Systems MUST terminate delinquent connections via `ws.close(1008, 'Policy Violation: Stalled Consumer')` if unbuffered queue limits or timeout thresholds are breached.

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 and Cooperative Drain Architecture critical for AI coding assistants?

Enforces strict non-blocking backpressure handling on native Bun WebSockets using ws.send() return codes and the drain() callback. Prevents unbounded native heap exhaustion caused by slow consumer stalls during high-frequency telemetry and event distribution. 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 (Blind ws.send() Invocations in High-Throughput Loops Leading to Native Buffer Bloat and OOM Crashes) 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