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

Bun 1.2 Native WebSocket Backpressure Ring-Buffer Invariant

Enforces deterministic backpressure handling and explicit frame shedding for Bun 1.2 native WebSockets during high-throughput broadcast fan-outs. Prevents process heap exhaustion and native Zig transport buffer crashes by monitoring socket buffer levels and dropping stale unacknowledged messages via a bounded ring buffer.

Prohibited Anti-Pattern: Unchecked Fan-Out Broadcasts Overwhelming Slow WebSocket Consumers into Native OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure Ring-Buffer Invariant - Enforces deterministic backpressure handling and explicit frame shedding for Bun 1.2 native WebSockets during high-throughput broadcast fan-outs. Prevents process heap exhaustion and native Zig transport buffer crashes by monitoring socket buffer levels and dropping stale unacknowledged messages via a bounded ring buffer.
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-ring-buffer"
---

# Bun 1.2 Native WebSocket Backpressure Ring-Buffer Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Fan-Out Broadcasts Overwhelming Slow WebSocket Consumers into Native OOM

## System Constraints
You are a Principal Systems Architect enforcing Bun 1.2 native WebSocket backpressure and memory invariants. Mandate that all high-throughput broadcast patterns monitor client buffer pressure via ws.getBufferedAmount() and implement bounded drop strategies (ring-buffer shedding) rather than unbounded JavaScript heap queuing or blind calls to ws.send() / server.publish().

## Strict Guidelines
- Engineers MUST ALWAYS verify ws.getBufferedAmount() against a defined high-watermark threshold (e.g., 64 KiB) before dispatching high-frequency frames to a WebSocket consumer.
- Engineers MUST NOT aggregate pending WebSocket messages in unbounded JavaScript arrays or unresolved Promise queues when client buffers saturate.
- Services MUST adopt a bounded circular ring buffer or drop-tail policy for ephemeral telemetry and real-time broadcasts when slow consumers lag behind.
- Engineers MUST implement the native drain(ws) callback inside Bun.serve to flush pending ring-buffer frames when native Zig transport queues clear below low-watermark thresholds.
- Components NEVER execute raw for-loops calling ws.send() across thousands of connected sockets without verifying individual socket backpressure states.

## Bad vs Good Implementations
### WebSocket Broadcast with Backpressure Ring-Buffer Shedding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling ws.send() unconditionally pushes frames into Bun's native Zig transport layer buffers. If a consumer is on a slow link or stalls, ws.getBufferedAmount() grows unbounded until the host kernel drops the process via OOM or Bun panics due to transport allocation exhaustion.
```typescript
import { ServerWebSocket } from 'bun';

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

// ANTI-PATTERN: Naive fan-out loop pushing into native socket queue without
// checking buffered amount or native backpressure. Fast producers will
// exhaust native Zig transport memory and trigger process SIGKILL.
export function broadcastMetric(metric: object): void {
  const payload = JSON.stringify(metric);
  for (const ws of clients) {
    ws.send(payload);
  }
}

Bun.serve({
  port: 3000,
  websocket: {
    open(ws) { clients.add(ws); },
    close(ws) { clients.delete(ws); },
    message(ws, msg) {},
  },
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response('Upgrade failed', { status: 400 });
  },
});
```

#### Production Standard (Correct)
> **Standard**: Inspects ws.getBufferedAmount() against HIGH_WATERMARK_BYTES before sending. Under backpressure, messages are queued in a pre-allocated, fixed-capacity ring buffer that sheds oldest frames instead of allocating unbounded memory. Queued frames are safely dispatched in the native drain(ws) callback.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientState {
  ringBuffer: string[];
  capacity: number;
  head: number;
  tail: number;
  size: number;
}

const HIGH_WATERMARK_BYTES = 64 * 1024; // 64 KiB
const RING_BUFFER_CAPACITY = 128;

const clients = new Map<ServerWebSocket<ClientState>, ClientState>();

function enqueueRing(state: ClientState, item: string): void {
  state.ringBuffer[state.tail] = item;
  state.tail = (state.tail + 1) % state.capacity;
  if (state.size < state.capacity) {
    state.size++;
  } else {
    // Shed oldest frame to prevent unbounded heap memory consumption
    state.head = (state.head + 1) % state.capacity;
  }
}

function dequeueRing(state: ClientState): string | undefined {
  if (state.size === 0) return undefined;
  const item = state.ringBuffer[state.head];
  state.head = (state.head + 1) % state.capacity;
  state.size--;
  return item;
}

export function broadcastMetric(metric: object): void {
  const payload = JSON.stringify(metric);

  for (const [ws, state] of clients) {
    // Invariant: Native transport backpressure check
    if (ws.getBufferedAmount() > HIGH_WATERMARK_BYTES) {
      // Socket congested: Shed or buffer into bounded ring buffer only
      enqueueRing(state, payload);
      continue;
    }

    const sent = ws.send(payload);
    if (sent === -1) {
      // Kernel backpressure tripped immediately: shed frame to ring buffer
      enqueueRing(state, payload);
    }
  }
}

Bun.serve<ClientState>({
  port: 3000,
  websocket: {
    open(ws) {
      const state: ClientState = {
        ringBuffer: new Array(RING_BUFFER_CAPACITY),
        capacity: RING_BUFFER_CAPACITY,
        head: 0,
        tail: 0,
        size: 0,
      };
      clients.set(ws, state);
    },
    close(ws) {
      clients.delete(ws);
    },
    drain(ws) {
      const state = clients.get(ws);
      if (!state) return;

      // Drain queued ring-buffer frames while native transport has capacity
      while (state.size > 0 && ws.getBufferedAmount() < HIGH_WATERMARK_BYTES) {
        const pending = dequeueRing(state);
        if (!pending) break;
        if (ws.send(pending) === -1) {
          break;
        }
      }
    },
    message(ws, msg) {},
  },
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return 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 Backpressure Ring-Buffer Invariant

Bun 1.2 Native WebSocket Backpressure Ring-Buffer Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic backpressure handling and explicit frame shedding for Bun 1.2 native WebSockets during high-throughput broadcast fan-outs. Prevents process heap exhaustion and native Zig transport buffer crashes by monitoring socket buffer levels and dropping stale unacknowledged messages via a bounded ring buffer. 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 Fan-Out Broadcasts Overwhelming Slow WebSocket Consumers into Native OOM 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 Fan-Out Broadcasts Overwhelming Slow WebSocket Consumers into Native OOMCritical
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 verify ws.getBufferedAmount() against a defined high-watermark threshold (e.g., 64 KiB) before dispatching high-frequency frames to a WebSocket consumer.

Engineers MUST ALWAYS verify ws.getBufferedAmount() against a defined high-watermark threshold (e.g., 64 KiB) before dispatching high-frequency frames to a WebSocket consumer.

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 aggregate pending WebSocket messages in unbounded JavaScript arrays or unresolved Promise queues when client buffers saturate.

Engineers MUST NOT aggregate pending WebSocket messages in unbounded JavaScript arrays or unresolved Promise queues when client buffers saturate.

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 adopt a bounded circular ring buffer or drop-tail policy for ephemeral telemetry and real-time broadcasts when slow consumers lag behind.

Services MUST adopt a bounded circular ring buffer or drop-tail policy for ephemeral telemetry and real-time broadcasts when slow consumers lag behind.

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 implement the native drain(ws) callback inside Bun.serve to flush pending ring-buffer frames when native Zig transport queues clear below low-watermark thresholds.

Engineers MUST implement the native drain(ws) callback inside Bun.serve to flush pending ring-buffer frames when native Zig transport queues clear below low-watermark 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

Components NEVER execute raw for-loops calling ws.send() across thousands of connected sockets without verifying individual socket backpressure states.

Components NEVER execute raw for-loops calling ws.send() across thousands of connected sockets without verifying individual socket backpressure 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.
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 Ring-Buffer Invariant critical for AI coding assistants?

Enforces deterministic backpressure handling and explicit frame shedding for Bun 1.2 native WebSockets during high-throughput broadcast fan-outs. Prevents process heap exhaustion and native Zig transport buffer crashes by monitoring socket buffer levels and dropping stale unacknowledged messages via a bounded ring buffer. 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 Fan-Out Broadcasts Overwhelming Slow WebSocket Consumers into Native OOM) 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