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

Bun 1.2 WebSocket Backpressure Watermark Standard

Enforces strict egress buffer monitoring and ingestion pausing on Bun WebSocket connections using ws.getBufferedAmount() and return values from ws.send(). Prevents unmitigated heap exhaustion and process OOM kills in high-throughput event loops by establishing high and low watermarks that govern client read suspension and frame emission.

Prohibited Anti-Pattern: Unbounded WebSocket Writes Without Backpressure Yielding Process OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 WebSocket Backpressure Watermark Standard - Enforces strict egress buffer monitoring and ingestion pausing on Bun WebSocket connections using ws.getBufferedAmount() and return values from ws.send(). Prevents unmitigated heap exhaustion and process OOM kills in high-throughput event loops by establishing high and low watermarks that govern client read suspension and frame emission.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}, services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-websocket-backpressure-watermark-standard"
---

# Bun 1.2 WebSocket Backpressure Watermark Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded WebSocket Writes Without Backpressure Yielding Process OOM

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 WebSocket Backpressure Watermark Standard. Mandate that every WebSocket frame producer rigorously evaluates `ws.getBufferedAmount()` and respects `ws.send()` return codes. Ensure ingestion pipelines pause data flow when high watermarks are hit and only resume operations when the buffer recedes below configured low watermarks or upon the `drain` event.

## Strict Guidelines
- Engineers MUST ALWAYS inspect `ws.getBufferedAmount()` before queuing large outbound payloads or evaluate the byte count returned by `ws.send(payload)`.
- Engineers MUST NOT continuously invoke `ws.send()` inside unthrottled loops or broad pub/sub dispatchers without handling non-zero queue buildup.
- Services MUST implement explicit High-Watermark (HWM, e.g., 1MB) and Low-Watermark (LWM, e.g., 256KB) thresholds per socket to pause upstream ingress or drop non-critical telemetry frames.
- Handlers MUST utilize the Bun `drain(ws)` lifecycle callback to reactivate downstream producers and resume paused ingestion pipelines once the kernel transmission queue flushes.
- Sockets that exceed a critical hard-limit watermark (e.g., 16MB) MUST be immediately terminated via `ws.close(1008, 'Policy Violation: Buffer Overflow')` to protect global process memory.

## Bad vs Good Implementations
### Fire-and-Forget Broadcast vs Watermark-Regulated Backpressure Stream

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring ws.getBufferedAmount() and the return value of ws.send() allows unbounded accumulation in native memory when network transmission is slower than stream production, ultimately causing process-wide SIGKILL from OOM.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientData {
  id: string;
}

export function handleTelemetryStream(ws: ServerWebSocket<ClientData>, stream: AsyncIterable<Uint8Array>) {
  (async () => {
    // ANTI-PATTERN: Blindly sending chunks without inspecting buffered amount
    // Slow network clients will cause Bun's internal C++ socket buffer to grow unbounded
    for await (const chunk of stream) {
      ws.send(chunk);
    }
  })();
}
```

#### Production Standard (Correct)
> **Standard**: Inspects socket buffer size prior to pushing new frames, suspends the asynchronous generator ingestion at the high watermark (1MB), and registers a resume trigger that the Bun 'drain' callback activates once socket pressure normalizes.
```typescript
import { ServerWebSocket } from 'bun';

interface ClientData {
  id: string;
  isPaused?: boolean;
  resumeStream?: () => void;
}

const HIGH_WATERMARK_BYTES = 1024 * 1024; // 1MB
const HARD_TERMINATION_BYTES = 8 * 1024 * 1024; // 8MB

export async function handleTelemetryStream(
  ws: ServerWebSocket<ClientData>,
  stream: AsyncIterable<Uint8Array>
) {
  for await (const chunk of stream) {
    const buffered = ws.getBufferedAmount();

    if (buffered >= HARD_TERMINATION_BYTES) {
      ws.close(1008, 'Backpressure threshold exceeded');
      return;
    }

    if (buffered >= HIGH_WATERMARK_BYTES) {
      // Suspend producer until socket buffer is drained
      await new Promise<void>((resolve) => {
        ws.data.isPaused = true;
        ws.data.resumeStream = resolve;
      });
    }

    const sendResult = ws.send(chunk);
    if (sendResult === -1) {
      // Socket closed or failed
      break;
    }
  }
}

// In Bun server definition:
// websocket: {
//   drain(ws) {
//     if (ws.data.isPaused && ws.getBufferedAmount() <= HIGH_WATERMARK_BYTES / 2) {
//       ws.data.isPaused = false;
//       ws.data.resumeStream?.();
//       ws.data.resumeStream = undefined;
//     }
//   }
// }
```

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 WebSocket Backpressure Watermark Standard

Bun 1.2 WebSocket Backpressure Watermark Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict egress buffer monitoring and ingestion pausing on Bun WebSocket connections using ws.getBufferedAmount() and return values from ws.send(). Prevents unmitigated heap exhaustion and process OOM kills in high-throughput event loops by establishing high and low watermarks that govern client read suspension and frame emission. 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 WebSocket Writes Without Backpressure Yielding Process 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 DriftUnbounded WebSocket Writes Without Backpressure Yielding Process 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 inspect `ws.getBufferedAmount()` before queuing large outbound payloads or evaluate the byte count returned by `ws.send(payload)`.

Engineers MUST ALWAYS inspect `ws.getBufferedAmount()` before queuing large outbound payloads or evaluate the byte count returned by `ws.send(payload)`.

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 continuously invoke `ws.send()` inside unthrottled loops or broad pub/sub dispatchers without handling non-zero queue buildup.

Engineers MUST NOT continuously invoke `ws.send()` inside unthrottled loops or broad pub/sub dispatchers without handling non-zero queue buildup.

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 explicit High-Watermark (HWM, e.g., 1MB) and Low-Watermark (LWM, e.g., 256KB) thresholds per socket to pause upstream ingress or drop non-critical telemetry frames.

Services MUST implement explicit High-Watermark (HWM, e.g., 1MB) and Low-Watermark (LWM, e.g., 256KB) thresholds per socket to pause upstream ingress or drop non-critical telemetry 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.
4

Handlers MUST utilize the Bun `drain(ws)` lifecycle callback to reactivate downstream producers and resume paused ingestion pipelines once the kernel transmission queue flushes.

Handlers MUST utilize the Bun `drain(ws)` lifecycle callback to reactivate downstream producers and resume paused ingestion pipelines once the kernel transmission queue flushes.

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

Sockets that exceed a critical hard-limit watermark (e.g., 16MB) MUST be immediately terminated via `ws.close(1008, 'Policy Violation

Sockets that exceed a critical hard-limit watermark (e.g., 16MB) MUST be immediately terminated via `ws.close(1008, 'Policy Violation: Buffer Overflow')` to protect global process memory.

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

Enforces strict egress buffer monitoring and ingestion pausing on Bun WebSocket connections using ws.getBufferedAmount() and return values from ws.send(). Prevents unmitigated heap exhaustion and process OOM kills in high-throughput event loops by establishing high and low watermarks that govern client read suspension and frame emission. 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 WebSocket Writes Without Backpressure Yielding Process 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