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

Bun 1.2 Native WebSocket Backpressure & High-Watermark Guardrail

Enforces strict handling of native backpressure in Bun WebSocket servers during high-concurrency fan-out operations. Failing to check the return byte count of `ws.send()` causes unconstrained native buffer allocations in the underlying uSockets/JSC runtime, leading to silent memory leaks and process termination under load.

Prohibited Anti-Pattern: Unchecked `ws.send()` or `ws.publish()` fan-out causing native uSockets buffer inflation and unmitigated OOM kills

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Backpressure & High-Watermark Guardrail - Enforces strict handling of native backpressure in Bun WebSocket servers during high-concurrency fan-out operations. Failing to check the return byte count of `ws.send()` causes unconstrained native buffer allocations in the underlying uSockets/JSC runtime, leading to silent memory leaks and process termination under load.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-native-backpressure-invariant"
---

# Bun 1.2 Native WebSocket Backpressure & High-Watermark Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked `ws.send()` or `ws.publish()` fan-out causing native uSockets buffer inflation and unmitigated OOM kills

## System Constraints
You are a Principal Systems Engineer enforcing strict I/O backpressure contracts on Bun 1.2 WebSocket implementations. In Bun, `ws.send()` returns a number indicating message queue status (-1 for dropped, 0 for backpressure applied/queued natively, >0 for sent bytes). You must prevent unbounded memory consumption by mandating queue size checks (`ws.getBufferedAmount()`), handling `drain(ws)` callbacks, and pausing upstream ingest when the native buffer reaches high-watermark thresholds.

## Strict Guidelines
- Engineers MUST ALWAYS check the return status or `ws.getBufferedAmount()` before and after calling `ws.send()` during batch transmissions.
- Engineers MUST NOT blindly broadcast or loop through client lists invoking `ws.send()` without pausing the producer when client send queues exceed `HIGH_WATERMARK` bytes.
- Services MUST implement the `drain(ws)` WebSocket lifecycle hook in `Bun.serve()` to resume halted data ingestion when the native kernel buffer flushes below `LOW_WATERMARK`.
- Code MUST isolate or terminate lagging clients whose `ws.getBufferedAmount()` exceeds safety thresholds (e.g., 1MB) rather than stalling the entire broadcast pipeline.
- Engineers MUST configure `backpressureLimit` and `closeOnBackpressureLimit` options in `Bun.serve()` when available to delegate hard-limit disconnections to the native runtime.

## Bad vs Good Implementations
### High-Throughput Fan-Out with Native Backpressure Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating over sockets and firing `client.send()` without evaluating return status or buffered amounts causes native memory buffers to balloon when slow clients lag behind. This leads to silent native JSC/uSockets heap exhaustion and non-catchable process crashes under sustained traffic.
```typescript
import { ServerWebSocket } from 'bun';

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

Bun.serve({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    open(ws) {
      clients.add(ws);
    },
    close(ws) {
      clients.delete(ws);
    },
    message(ws, msg) {
      // Blind fan-out: Ignores backpressure and native buffer growth
      for (const client of clients) {
        client.send(msg); // Returns bytes or 0, but is never checked
      }
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Monitors `getBufferedAmount()` against a `HIGH_WATERMARK`, utilizes `drain(ws)` to clear paused states when native buffers drain, and disconnects chronically slow consumers to preserve overall server stability.
```typescript
import { ServerWebSocket } from 'bun';

interface SocketData {
  isPaused: boolean;
}

const HIGH_WATERMARK = 1024 * 512; // 512 KB
const clients = new Set<ServerWebSocket<SocketData>>();

Bun.serve<SocketData>({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req, { data: { isPaused: false } })) return;
    return new Response('Upgrade failed', { status: 400 });
  },
  websocket: {
    open(ws) {
      clients.add(ws);
    },
    close(ws) {
      clients.delete(ws);
    },
    drain(ws) {
      // Resume upstream or mark client healthy when buffer drops
      if (ws.data.isPaused && ws.getBufferedAmount() < HIGH_WATERMARK / 2) {
        ws.data.isPaused = false;
      }
    },
    message(ws, msg) {
      const payload = typeof msg === 'string' ? msg : new Uint8Array(msg);
      for (const client of clients) {
        if (client.getBufferedAmount() > HIGH_WATERMARK) {
          client.data.isPaused = true;
          // Drop slow consumer or drop message to preserve server health
          client.close(1008, 'Rate limit / backpressure exceeded');
          clients.delete(client);
          continue;
        }

        const sentBytes = client.send(payload);
        if (sentBytes === 0) {
          // Kernel buffer queued the frame; check pressure
          if (client.getBufferedAmount() >= HIGH_WATERMARK) {
            client.data.isPaused = true;
          }
        }
      }
    },
  },
});
```

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 & High-Watermark Guardrail

Bun 1.2 Native WebSocket Backpressure & High-Watermark Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict handling of native backpressure in Bun WebSocket servers during high-concurrency fan-out operations. Failing to check the return byte count of `ws.send()` causes unconstrained native buffer allocations in the underlying uSockets/JSC runtime, leading to silent memory leaks and process termination under load. 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()` or `ws.publish()` fan-out causing native uSockets buffer inflation and unmitigated OOM kills 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()` or `ws.publish()` fan-out causing native uSockets buffer inflation and unmitigated OOM killsCritical
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 the return status or `ws.getBufferedAmount()` before and after calling `ws.send()` during batch transmissions.

Engineers MUST ALWAYS check the return status or `ws.getBufferedAmount()` before and after calling `ws.send()` during batch transmissions.

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 blindly broadcast or loop through client lists invoking `ws.send()` without pausing the producer when client send queues exceed `HIGH_WATERMARK` bytes.

Engineers MUST NOT blindly broadcast or loop through client lists invoking `ws.send()` without pausing the producer when client send queues exceed `HIGH_WATERMARK` bytes.

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)` WebSocket lifecycle hook in `Bun.serve()` to resume halted data ingestion when the native kernel buffer flushes below `LOW_WATERMARK`.

Services MUST implement the `drain(ws)` WebSocket lifecycle hook in `Bun.serve()` to resume halted data ingestion when the native kernel buffer flushes below `LOW_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

Code MUST isolate or terminate lagging clients whose `ws.getBufferedAmount()` exceeds safety thresholds (e.g., 1MB) rather than stalling the entire broadcast pipeline.

Code MUST isolate or terminate lagging clients whose `ws.getBufferedAmount()` exceeds safety thresholds (e.g., 1MB) rather than stalling the entire broadcast 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.
5

Engineers MUST configure `backpressureLimit` and `closeOnBackpressureLimit` options in `Bun.serve()` when available to delegate hard-limit disconnections to the native runtime.

Engineers MUST configure `backpressureLimit` and `closeOnBackpressureLimit` options in `Bun.serve()` when available to delegate hard-limit disconnections to the native runtime.

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 & High-Watermark Guardrail critical for AI coding assistants?

Enforces strict handling of native backpressure in Bun WebSocket servers during high-concurrency fan-out operations. Failing to check the return byte count of `ws.send()` causes unconstrained native buffer allocations in the underlying uSockets/JSC runtime, leading to silent memory leaks and process termination under load. 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()` or `ws.publish()` fan-out causing native uSockets buffer inflation and unmitigated OOM kills) 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