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

Bun 1.2 Native WebSocket Backpressure Drain Watermark Standard

Mandates explicit flow control, buffered byte inspection, and drain lifecycle management for native WebSockets in Bun 1.2. Prevents unbounded native C++ and JavaScriptCore heap expansion that causes silent Linux kernel OOM kills under bursty telemetry and high-throughput streaming workloads.

Prohibited Anti-Pattern: Unchecked Fire-and-Forget ws.send() Under High-Frequency Ingestion Spikes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure Drain Watermark Standard - Mandates explicit flow control, buffered byte inspection, and drain lifecycle management for native WebSockets in Bun 1.2. Prevents unbounded native C++ and JavaScriptCore heap expansion that causes silent Linux kernel OOM kills under bursty telemetry and high-throughput streaming workloads.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-backpressure-drain-watermark"
---

# Bun 1.2 Native WebSocket Backpressure Drain Watermark Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Fire-and-Forget ws.send() Under High-Frequency Ingestion Spikes

## System Constraints
You are a Principal Backend Architect enforcing the Bun 1.2 Native WebSocket Backpressure Drain Watermark Standard. Bun's high-performance WebSocket implementation delegates socket writes to native C++ uWebSockets buffers. If you call ws.send() faster than client network interfaces consume TCP ACK frames, buffered payloads accumulate outside the garbage collector's immediate purview, triggering silent SIGKILL events from the Linux OOM-killer. You MUST enforce buffered payload tracking, high/low watermarks, and native drain() handling across all streaming endpoints.

## Strict Guidelines
- Engineers MUST ALWAYS check ws.getBufferedAmount() against an explicit HIGH_WATERMARK limit prior to invoking ws.send() inside streaming or event-driven contexts.
- Engineers MUST implement the native drain(ws: ServerWebSocket<T>) hook inside the Bun.serve({ websocket: { ... } }) configuration whenever high-frequency telemetry, pub/sub broadcasts, or chunked buffers are streamed.
- Services MUST suspend upstream event emission, pause async queue consumption, or enact a deterministic bounded ring-buffer shedding policy when ws.getBufferedAmount() breaches HIGH_WATERMARK.
- Services MUST NOT resume queued socket dispatches until ws.getBufferedAmount() falls beneath LOW_WATERMARK inside the drain(ws) callback.
- Components NEVER attach unbounded external event listeners directly pushing to ws.send() without cleanup lifecycle hooks inside websocket.close(ws).

## Bad vs Good Implementations
### Naive Push vs Watermark-Governed Drain Flow Control

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling ws.send() unconditionally inside external event listeners ignores socket saturation. In Bun, outbound bytes accumulate in native uWebSockets C++ ring buffers. If clients experience transient TCP latency, the buffered byte count balloons silently, circumventing JSC GC thresholds and triggering kernel OOM termination.
```typescript
import { serve } from "bun";
import { telemetryEmitter } from "./sensor-bus";

interface SocketData {
  sensorId: string;
}

// ANTI-PATTERN: Fire-and-forget pushes ignore native socket buffer queues
export const server = Bun.serve<SocketData>({
  port: 8080,
  fetch(req, srv) {
    if (srv.upgrade(req, { data: { sensorId: "sensor_01" } })) return;
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      telemetryEmitter.on("telemetry", (payload: Uint8Array) => {
        // VIOLATION: Flooding the native uWebSockets buffer queue without checking
        // ws.getBufferedAmount(). Under 10k+ msg/s bursts, native memory accumulates
        // until the OS kernel issues SIGKILL (OOM) with no stack trace.
        ws.send(payload);
      });
    },
    message(ws, msg) {},
    close(ws) {},
    // VIOLATION: Omitting the drain() handler prevents reactive backpressure recovery.
  },
});
```

#### Production Standard (Correct)
> **Standard**: Implements explicit high/low watermarks against ws.getBufferedAmount() and pairs it with Bun's native websocket.drain hook. Outbound payloads are contained in a bounded queue when backpressure is tripped, and transmission gracefully resumes only after the native socket empties below the low-watermark threshold.
```typescript
import { serve, type ServerWebSocket } from "bun";
import { telemetryEmitter } from "./sensor-bus";

interface SocketData {
  sensorId: string;
  isBackpressured: boolean;
  queue: Uint8Array[];
  unsubscribe?: () => void;
}

const HIGH_WATERMARK = 1024 * 1024; // 1 MB: Pause transmission
const LOW_WATERMARK = 256 * 1024;   // 256 KB: Resume transmission
const MAX_QUEUE_ITEMS = 1000;       // Eviction cap to protect memory

export const server = Bun.serve<SocketData>({
  port: 8080,
  fetch(req, srv) {
    const data: SocketData = {
      sensorId: "sensor_01",
      isBackpressured: false,
      queue: [],
    };
    if (srv.upgrade(req, { data })) return;
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      const onData = (payload: Uint8Array) => {
        if (ws.data.isBackpressured || ws.getBufferedAmount() >= HIGH_WATERMARK) {
          ws.data.isBackpressured = true;
          if (ws.data.queue.length >= MAX_QUEUE_ITEMS) {
            ws.data.queue.shift(); // Drop oldest frame to preserve bounded memory
          }
          ws.data.queue.push(payload);
          return;
        }

        ws.send(payload);
        if (ws.getBufferedAmount() >= HIGH_WATERMARK) {
          ws.data.isBackpressured = true;
        }
      };

      telemetryEmitter.on("telemetry", onData);
      ws.data.unsubscribe = () => telemetryEmitter.off("telemetry", onData);
    },
    drain(ws: ServerWebSocket<SocketData>) {
      // Flushes bounded queue when the OS socket buffer empties
      while (ws.data.queue.length > 0) {
        if (ws.getBufferedAmount() >= HIGH_WATERMARK) {
          return; // Still saturated; wait for next native drain event
        }
        const chunk = ws.data.queue.shift();
        if (chunk) ws.send(chunk);
      }

      if (ws.getBufferedAmount() <= LOW_WATERMARK) {
        ws.data.isBackpressured = false;
      }
    },
    close(ws) {
      ws.data.unsubscribe?.();
      ws.data.queue.length = 0;
    },
    message(ws, msg) {},
  },
});
```

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 Drain Watermark Standard

Bun 1.2 Native WebSocket Backpressure Drain Watermark Standard defines an industrial-grade behavioral standard for backend engineering. Mandates explicit flow control, buffered byte inspection, and drain lifecycle management for native WebSockets in Bun 1.2. Prevents unbounded native C++ and JavaScriptCore heap expansion that causes silent Linux kernel OOM kills under bursty telemetry and high-throughput streaming workloads. 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 Fire-and-Forget ws.send() Under High-Frequency Ingestion Spikes 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 Fire-and-Forget ws.send() Under High-Frequency Ingestion SpikesCritical
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.getBufferedAmount() against an explicit HIGH_WATERMARK limit prior to invoking ws.send() inside streaming or event-driven contexts.

Engineers MUST ALWAYS check ws.getBufferedAmount() against an explicit HIGH_WATERMARK limit prior to invoking ws.send() inside streaming or event-driven contexts.

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 implement the native drain(ws

Engineers MUST implement the native drain(ws: ServerWebSocket<T>) hook inside the Bun.serve({ websocket: { ... } }) configuration whenever high-frequency telemetry, pub/sub broadcasts, or chunked buffers are streamed.

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 suspend upstream event emission, pause async queue consumption, or enact a deterministic bounded ring-buffer shedding policy when ws.getBufferedAmount() breaches HIGH_WATERMARK.

Services MUST suspend upstream event emission, pause async queue consumption, or enact a deterministic bounded ring-buffer shedding policy when ws.getBufferedAmount() breaches HIGH_WATERMARK.

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 NOT resume queued socket dispatches until ws.getBufferedAmount() falls beneath LOW_WATERMARK inside the drain(ws) callback.

Services MUST NOT resume queued socket dispatches until ws.getBufferedAmount() falls beneath LOW_WATERMARK inside the drain(ws) callback.

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 attach unbounded external event listeners directly pushing to ws.send() without cleanup lifecycle hooks inside websocket.close(ws).

Components NEVER attach unbounded external event listeners directly pushing to ws.send() without cleanup lifecycle hooks inside websocket.close(ws).

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 Watermark Standard critical for AI coding assistants?

Mandates explicit flow control, buffered byte inspection, and drain lifecycle management for native WebSockets in Bun 1.2. Prevents unbounded native C++ and JavaScriptCore heap expansion that causes silent Linux kernel OOM kills under bursty telemetry and high-throughput streaming workloads. 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 Fire-and-Forget ws.send() Under High-Frequency Ingestion Spikes) 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