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

Bun 1.2 Native WebSocket Zero-Copy Kernel Backpressure Standard

Enforces deterministic zero-copy kernel backpressure propagation across Bun 1.2 native WebSockets by binding OS socket buffer high-water marks directly to upstream async iterable stream consumption. Eliminates silent userland heap queue ballooning and engine out-of-memory crashes during high-throughput producer-consumer velocity mismatches. Mandates reactive pause/resume mechanics keyed to socket buffer saturation and native drain event dispatch.

Prohibited Anti-Pattern: Unbounded ws.send() stream iterations without drain-gate synchronization causing fatal heap exhaustion.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Zero-Copy Kernel Backpressure Standard - Enforces deterministic zero-copy kernel backpressure propagation across Bun 1.2 native WebSockets by binding OS socket buffer high-water marks directly to upstream async iterable stream consumption. Eliminates silent userland heap queue ballooning and engine out-of-memory crashes during high-throughput producer-consumer velocity mismatches. Mandates reactive pause/resume mechanics keyed to socket buffer saturation and native drain event dispatch.
globs: src/**/*.ts, server/**/*.ts, src/websockets/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-zero-copy-backpressure-standard"
---

# Bun 1.2 Native WebSocket Zero-Copy Kernel Backpressure Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded ws.send() stream iterations without drain-gate synchronization causing fatal heap exhaustion.

## System Constraints
You are a Principal Systems Engineer enforcing the Bun 1.2 Native WebSocket Zero-Copy Kernel Backpressure Standard. You must ensure all WebSocket data transmission explicitly accounts for native OS socket buffer saturation, using Bun's native drain hooks and zero-copy byte buffers rather than unthrottled loop sends.

## Strict Guidelines
- Engineers MUST ALWAYS check ws.send() return byte-count and evaluate ws.getBufferedAmount() against a defined High-Water Mark (HWM) before continuing upstream consumption.
- Engineers MUST NOT call ws.send() continuously inside unbuffered 'for await' loops or asynchronous generator streams without awaiting socket clearance.
- Code SHOULD transmit binary payloads using zero-copy Uint8Array or ArrayBuffer allocations rather than UTF-8 string conversions to avoid redundant GC passes.
- Services MUST register a native 'drain(ws)' handler in Bun.serve() to notify waiting stream iterators when the socket kernel buffer drops below the Low-Water Mark (LWM).
- Components NEVER buffer messages in custom JavaScript arrays when a socket is saturated; backpressure MUST propagate upstream to the original data producer or client pipeline.

## Bad vs Good Implementations
### Kernel Backpressure Gating with Bun.serve WebSocket Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating through an incoming stream without checking socket buffer capacity pushes bytes faster than the TCP window can acknowledge. The data accumulates unchecked in engine heap buffers, ballooning memory usage and crashing the process under adverse network conditions.
```typescript
import { ServerWebSocket } from 'bun';

// ANTI-PATTERN: Completely ignores OS socket saturation and buffered amount.
// Fast file/channel stream will buffer infinitely in heap memory, triggering OOM.
export async function pumpStreamToSocket(
  ws: ServerWebSocket<unknown>,
  stream: AsyncIterable<Uint8Array>
): Promise<void> {
  for await (const chunk of stream) {
    // ws.send returns the number of bytes sent or buffered, but is treated as fire-and-forget
    ws.send(chunk);
  }
}
```

#### Production Standard (Correct)
> **Standard**: This pattern monitors ws.getBufferedAmount() relative to a 1MB High-Water Mark. Once reached, upstream iteration suspends via a Promise that is settled only when Bun fires the native drain() hook, ensuring strict zero-copy kernel backpressure propagation.
```typescript
import { ServerWebSocket } from 'bun';

interface SocketData {
  drainPromise?: Promise<void>;
  resolveDrain?: () => void;
}

const HIGH_WATER_MARK = 1024 * 1024; // 1MB

export const websocketHandler = {
  drain(ws: ServerWebSocket<SocketData>) {
    if (ws.data.resolveDrain) {
      const resolve = ws.data.resolveDrain;
      ws.data.drainPromise = undefined;
      ws.data.resolveDrain = undefined;
      resolve();
    }
  },
};

export async function pumpStreamToSocket(
  ws: ServerWebSocket<SocketData>,
  stream: AsyncIterable<Uint8Array>
): Promise<void> {
  for await (const chunk of stream) {
    // Zero-copy binary dispatch
    ws.send(chunk);

    if (ws.getBufferedAmount() >= HIGH_WATER_MARK) {
      if (!ws.data.drainPromise) {
        ws.data.drainPromise = new Promise<void>((resolve) => {
          ws.data.resolveDrain = resolve;
        });
      }
      // Halt upstream async generator pulling until OS buffer drains
      await ws.data.drainPromise;
    }
  }
}
```

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 Zero-Copy Kernel Backpressure Standard

Bun 1.2 Native WebSocket Zero-Copy Kernel Backpressure Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic zero-copy kernel backpressure propagation across Bun 1.2 native WebSockets by binding OS socket buffer high-water marks directly to upstream async iterable stream consumption. Eliminates silent userland heap queue ballooning and engine out-of-memory crashes during high-throughput producer-consumer velocity mismatches. Mandates reactive pause/resume mechanics keyed to socket buffer saturation and native drain event dispatch. 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: Unbounded ws.send() stream iterations without drain-gate synchronization causing fatal heap exhaustion. 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 DriftUnbounded ws.send() stream iterations without drain-gate synchronization causing fatal heap exhaustion.Critical
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 check ws.send() return byte-count and evaluate ws.getBufferedAmount() against a defined High-Water Mark (HWM) before continuing upstream consumption.

Engineers MUST ALWAYS check ws.send() return byte-count and evaluate ws.getBufferedAmount() against a defined High-Water Mark (HWM) before continuing upstream consumption.

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 call ws.send() continuously inside unbuffered 'for await' loops or asynchronous generator streams without awaiting socket clearance.

Engineers MUST NOT call ws.send() continuously inside unbuffered 'for await' loops or asynchronous generator streams without awaiting socket clearance.

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

Code SHOULD transmit binary payloads using zero-copy Uint8Array or ArrayBuffer allocations rather than UTF-8 string conversions to avoid redundant GC passes.

Code SHOULD transmit binary payloads using zero-copy Uint8Array or ArrayBuffer allocations rather than UTF-8 string conversions to avoid redundant GC passes.

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 register a native 'drain(ws)' handler in Bun.serve() to notify waiting stream iterators when the socket kernel buffer drops below the Low-Water Mark (LWM).

Services MUST register a native 'drain(ws)' handler in Bun.serve() to notify waiting stream iterators when the socket kernel buffer drops below the Low-Water Mark (LWM).

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 buffer messages in custom JavaScript arrays when a socket is saturated

Components NEVER buffer messages in custom JavaScript arrays when a socket is saturated; backpressure MUST propagate upstream to the original data producer or client pipeline.

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 Zero-Copy Kernel Backpressure Standard critical for AI coding assistants?

Enforces deterministic zero-copy kernel backpressure propagation across Bun 1.2 native WebSockets by binding OS socket buffer high-water marks directly to upstream async iterable stream consumption. Eliminates silent userland heap queue ballooning and engine out-of-memory crashes during high-throughput producer-consumer velocity mismatches. Mandates reactive pause/resume mechanics keyed to socket buffer saturation and native drain event dispatch. 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 (Unbounded ws.send() stream iterations without drain-gate synchronization causing fatal heap exhaustion.) 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