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

Bun 1.2 Native WebSocket Streaming Backpressure and ArrayBuffer Detachment Guardrail

Enforces non-blocking backpressure flow control and detached buffer safety on high-throughput Bun 1.2 native WebSocket pipelines. Prevents unbounded kernel buffer queueing, silent zero-byte transmissions from reused detached ArrayBuffers, and EventLoop thread starvation under asymmetric client throughput.

Prohibited Anti-Pattern: Unchecked ws.send() Returns Causing Unbounded Memory Growth and Mutating Detached ArrayBuffers in Pipeline

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Streaming Backpressure and ArrayBuffer Detachment Guardrail - Enforces non-blocking backpressure flow control and detached buffer safety on high-throughput Bun 1.2 native WebSocket pipelines. Prevents unbounded kernel buffer queueing, silent zero-byte transmissions from reused detached ArrayBuffers, and EventLoop thread starvation under asymmetric client throughput.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-websocket-backpressure-detachment-guardrail"
---

# Bun 1.2 Native WebSocket Streaming Backpressure and ArrayBuffer Detachment Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked ws.send() Returns Causing Unbounded Memory Growth and Mutating Detached ArrayBuffers in Pipeline

## System Constraints
You are a Principal Backend Architect enforcing strict WebSocket streaming backpressure and binary buffer memory lifecycle rules in Bun 1.2. Bun's native WebSocket implementation (`Bun.serve({ websocket: ... })`) utilizes raw uWebSockets underneath, where `ws.send()` returns negative or byte-count status indicators rather than throwing upon congestion, and transferrable zero-copy binary streams detach ArrayBuffers upon consumption. Mandate explicit backpressure checks via `ws.getBufferedAmount()`, handle drainage through the `drain(ws)` socket lifecycle hook, and ban mutations or reads against detached ArrayBuffers.

## Strict Guidelines
- Engineers MUST ALWAYS evaluate the return value of `ws.send()` and check `ws.getBufferedAmount()` against an explicit high-water mark (e.g., 64KB) before dispatching binary or text frames.
- Engineers MUST pause upstream async iterators, streams, or message producers immediately when `ws.send()` returns -1 or when `ws.getBufferedAmount() > HIGH_WATER_MARK`.
- Engineers MUST resume upstream data production exclusively inside the WebSocket handler's `drain(ws)` hook when `ws.getBufferedAmount()` falls below the low-water mark.
- Engineers MUST NEVER access or resend an `ArrayBuffer` after passing it to a zero-copy transferable context or transferring it via workers; engineers MUST verify `.byteLength !== 0` or allocate defensively if buffers must be retained across frames.
- Components NEVER store unsent binary payloads in unbounded unbounded JavaScript arrays, which bypasses V8/JSC memory tracking and causes fatal Out-Of-Memory termination.
- Services MUST configure `backpressureLimit` and `closeOnBackpressureLimit` within `Bun.serve({ websocket: { ... } })` options to protect the native runtime from hostile slowloris consumers.

## Bad vs Good Implementations
### Handling Backpressure and ArrayBuffer Invalidation in Bun 1.2 Native WebSockets

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring ws.send() return codes allows unbounded socket buffering in native memory, evading the garbage collector until process crash. Attempting to reuse binary buffers after transferable handoff leads to silent transmission of zero-byte payloads due to ArrayBuffer detachment.
```typescript
import { ServerWebSocket } from 'bun';

interface SessionData { stream: ReadableStream<Uint8Array>; }

Bun.serve<SessionData>({
  websocket: {
    async message(ws: ServerWebSocket<SessionData>, message: string | Buffer) {
      // Flaw 1: Fire-and-forget streaming ignores ws.send() backpressure feedback
      const reader = ws.data.stream.getReader();
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        // Flaw 2: Unchecked send return value causes native buffer bloat and OOM
        ws.send(value.buffer);
        
        // Flaw 3: Reusing value.buffer after potential detachment causes zero-byte frames
        if (value.buffer.byteLength > 0) {
          ws.send(value.buffer);
        }
      }
    },
  },
  fetch(req, server) {
    server.upgrade(req, { data: { stream: getBinaryStream() } });
    return new Response('Upgraded');
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements cooperative backpressure using ws.getBufferedAmount() and the native drain(ws) hook to pause and resume the upstream reader. Protects against buffer detachment issues by creating discrete owned slices, and defines hard boundaries with backpressureLimit to prevent process termination.
```typescript
import { ServerWebSocket } from 'bun';

const HIGH_WATER_MARK = 64 * 1024; // 64 KB

interface SessionData {
  reader?: ReadableStreamDefaultReader<Uint8Array>;
  paused: boolean;
}

async function pumpStream(ws: ServerWebSocket<SessionData>): Promise<void> {
  const data = ws.data;
  if (!data.reader || data.paused) return;

  while (!data.paused) {
    if (ws.getBufferedAmount() >= HIGH_WATER_MARK) {
      data.paused = true;
      return;
    }

    const { done, value } = await data.reader.read();
    if (done) {
      ws.close(1000, 'Stream finished');
      return;
    }

    // Zero-copy transmission: allocate standalone slice to avoid retaining backing pools
    const chunk = value.byteOffset === 0 && value.byteLength === value.buffer.byteLength
      ? value.buffer
      : value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);

    // ws.send returns the number of bytes sent, or -1/0 on backpressure constraint
    const sendResult = ws.send(chunk);
    if (sendResult <= 0 || ws.getBufferedAmount() >= HIGH_WATER_MARK) {
      data.paused = true;
      return;
    }
  }
}

Bun.serve<SessionData>({
  websocket: {
    backpressureLimit: 1024 * 1024, // 1MB native cutoff
    closeOnBackpressureLimit: true,
    open(ws) {
      pumpStream(ws);
    },
    drain(ws) {
      if (ws.data.paused && ws.getBufferedAmount() < HIGH_WATER_MARK / 2) {
        ws.data.paused = false;
        pumpStream(ws);
      }
    },
    close(ws) {
      ws.data.reader?.cancel();
    }
  },
  fetch(req, server) {
    const stream = getBinaryStream();
    const upgraded = server.upgrade(req, {
      data: { reader: stream.getReader(), paused: false }
    });
    return upgraded ? undefined : new Response('Upgrade failed', { status: 400 });
  }
});
```

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 Streaming Backpressure and ArrayBuffer Detachment Guardrail

Bun 1.2 Native WebSocket Streaming Backpressure and ArrayBuffer Detachment Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces non-blocking backpressure flow control and detached buffer safety on high-throughput Bun 1.2 native WebSocket pipelines. Prevents unbounded kernel buffer queueing, silent zero-byte transmissions from reused detached ArrayBuffers, and EventLoop thread starvation under asymmetric client throughput. 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() Returns Causing Unbounded Memory Growth and Mutating Detached ArrayBuffers in Pipeline 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() Returns Causing Unbounded Memory Growth and Mutating Detached ArrayBuffers in PipelineCritical
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 evaluate the return value of `ws.send()` and check `ws.getBufferedAmount()` against an explicit high-water mark (e.g., 64KB) before dispatching binary or text frames.

Engineers MUST ALWAYS evaluate the return value of `ws.send()` and check `ws.getBufferedAmount()` against an explicit high-water mark (e.g., 64KB) before dispatching 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.
2

Engineers MUST pause upstream async iterators, streams, or message producers immediately when `ws.send()` returns -1 or when `ws.getBufferedAmount() > HIGH_WATER_MARK`.

Engineers MUST pause upstream async iterators, streams, or message producers immediately when `ws.send()` returns -1 or when `ws.getBufferedAmount() > 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.
3

Engineers MUST resume upstream data production exclusively inside the WebSocket handler's `drain(ws)` hook when `ws.getBufferedAmount()` falls below the low-water mark.

Engineers MUST resume upstream data production exclusively inside the WebSocket handler's `drain(ws)` hook when `ws.getBufferedAmount()` falls below the low-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

Engineers MUST NEVER access or resend an `ArrayBuffer` after passing it to a zero-copy transferable context or transferring it via workers

Engineers MUST NEVER access or resend an `ArrayBuffer` after passing it to a zero-copy transferable context or transferring it via workers; engineers MUST verify `.byteLength !== 0` or allocate defensively if buffers must be retained across 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.
5

Components NEVER store unsent binary payloads in unbounded unbounded JavaScript arrays, which bypasses V8/JSC memory tracking and causes fatal Out-Of-Memory termination.

Components NEVER store unsent binary payloads in unbounded unbounded JavaScript arrays, which bypasses V8/JSC memory tracking and causes fatal Out-Of-Memory termination.

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

Services MUST configure `backpressureLimit` and `closeOnBackpressureLimit` within `Bun.serve({ websocket

Services MUST configure `backpressureLimit` and `closeOnBackpressureLimit` within `Bun.serve({ websocket: { ... } })` options to protect the native runtime from hostile slowloris 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.
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 Streaming Backpressure and ArrayBuffer Detachment Guardrail critical for AI coding assistants?

Enforces non-blocking backpressure flow control and detached buffer safety on high-throughput Bun 1.2 native WebSocket pipelines. Prevents unbounded kernel buffer queueing, silent zero-byte transmissions from reused detached ArrayBuffers, and EventLoop thread starvation under asymmetric client throughput. 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() Returns Causing Unbounded Memory Growth and Mutating Detached ArrayBuffers in Pipeline) 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