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

Bun 1.2 WebSocket Backpressure & High-Water Mark Invariant

Enforces deterministic flow control on Bun WebSocket connections by gating transmission against socket-buffered byte thresholds and orchestrating re-activation via the drain lifecycle hook. Without backpressure watermarks, slow consumers cause kernel TCP and native Bun memory buffers to accumulate unboundedly, precipitating event-loop starvation and catastrophic out-of-memory (OOM) termination.

Prohibited Anti-Pattern: Fire-and-forget socket writes without getBufferedAmount gating or drain callback synchronization.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 WebSocket Backpressure & High-Water Mark Invariant - Enforces deterministic flow control on Bun WebSocket connections by gating transmission against socket-buffered byte thresholds and orchestrating re-activation via the drain lifecycle hook. Without backpressure watermarks, slow consumers cause kernel TCP and native Bun memory buffers to accumulate unboundedly, precipitating event-loop starvation and catastrophic out-of-memory (OOM) termination.
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-backpressure-watermark-invariant"
---

# Bun 1.2 WebSocket Backpressure & High-Water Mark Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fire-and-forget socket writes without getBufferedAmount gating or drain callback synchronization.

## System Constraints
You are a Principal Software Architect enforcing production resilience in Bun 1.2 WebSocket servers. You must reject any fire-and-forget socket writes that do not evaluate `ws.getBufferedAmount()` against configured high/low watermarks or that fail to leverage the `drain(ws)` hook for flow resumption. Prevent unbounded memory expansion and event-loop thread starvation under asynchronous message production.

## Strict Guidelines
- Engineers MUST ALWAYS inspect `ws.getBufferedAmount()` before dispatching continuous or batch payloads via `ws.send()`.
- Engineers MUST pause upstream producers or enqueue messages into bounded queues when `ws.getBufferedAmount()` exceeds the defined `HIGH_WATERMARK_BYTES` (e.g., 64 KiB to 1 MiB depending on SLA).
- Engineers MUST implement the native `drain(ws)` handler in Bun's `websocket` configuration object to trigger queue flush and resume ingestion once buffered bytes fall below `LOW_WATERMARK_BYTES`.
- Code MUST NEVER invoke `ws.send()` in an unthrottled loop or event-listener callback without handling partial writes or saturation states.
- Services MUST drop connections or shed incoming load with explicit WebSocket close frames (code 1008 or 1011) if bounded internal memory queues exceed maximum safety thresholds during persistent consumer stalls.

## Bad vs Good Implementations
### Streaming Feed Flow Control with High-Watermark and Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example sends telemetry every millisecond without querying `ws.getBufferedAmount()`. If the remote client is latency-constrained or stalls, Bun buffers all unacknowledged packets in memory, leading to memory bloat, GC thrashing, and eventually an unrecoverable process crash.
```typescript
import { serve } from "bun";

interface ClientData {
  id: string;
}

serve<ClientData>({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID() } })) return;
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      // CRITICAL VIOLATION: Unthrottled streaming loop causes unbounded
      // memory growth and native buffer bloat when client reads slowly.
      setInterval(() => {
        const telemetryPayload = JSON.stringify({ timestamp: Date.now(), metrics: Math.random() });
        ws.send(telemetryPayload);
      }, 1);
    },
    message(ws, message) {},
    close(ws) {}
  }
});
```

#### Production Standard (Correct)
> **Standard**: The good example checks `ws.getBufferedAmount()` against `HIGH_WATERMARK_BYTES` before transmitting. When backpressure develops, outgoing frames are held in a bounded local queue and sending pauses. As the underlying OS TCP send buffer drains, Bun triggers the `drain(ws)` hook, resuming queued dispatches safely.
```typescript
import { serve, type ServerWebSocket } from "bun";

interface ClientData {
  id: string;
  isPaused: boolean;
  queue: string[];
}

const HIGH_WATERMARK_BYTES = 64 * 1024; // 64 KiB
const MAX_QUEUE_DEPTH = 1000;

function tryFlush(ws: ServerWebSocket<ClientData>): void {
  while (ws.data.queue.length > 0) {
    if (ws.getBufferedAmount() >= HIGH_WATERMARK_BYTES) {
      ws.data.isPaused = true;
      return;
    }
    const payload = ws.data.queue.shift();
    if (payload) {
      ws.send(payload);
    }
  }
  ws.data.isPaused = false;
}

serve<ClientData>({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID(), isPaused: false, queue: [] } })) return;
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    open(ws) {
      // Safe bounded queueing with backpressure gating
      const interval = setInterval(() => {
        if (ws.readyState !== 1) {
          clearInterval(interval);
          return;
        }

        const payload = JSON.stringify({ timestamp: Date.now(), metrics: Math.random() });

        if (ws.data.queue.length >= MAX_QUEUE_DEPTH) {
          // Shed connection to protect host from malicious/stalled clients
          ws.close(1008, "Backpressure threshold exceeded: Slow consumer");
          clearInterval(interval);
          return;
        }

        ws.data.queue.push(payload);
        if (!ws.data.isPaused) {
          tryFlush(ws);
        }
      }, 10);
    },
    drain(ws) {
      // Invariant: Native socket buffer has emptied; flush remaining queued items
      tryFlush(ws);
    },
    close(ws) {
      ws.data.queue.length = 0;
    },
    message(ws, message) {}
  }
});
```

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 & High-Water Mark Invariant

Bun 1.2 WebSocket Backpressure & High-Water Mark Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic flow control on Bun WebSocket connections by gating transmission against socket-buffered byte thresholds and orchestrating re-activation via the drain lifecycle hook. Without backpressure watermarks, slow consumers cause kernel TCP and native Bun memory buffers to accumulate unboundedly, precipitating event-loop starvation and catastrophic out-of-memory (OOM) termination. 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: Fire-and-forget socket writes without getBufferedAmount gating or drain callback synchronization. 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 DriftFire-and-forget socket writes without getBufferedAmount gating or drain callback synchronization.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 inspect `ws.getBufferedAmount()` before dispatching continuous or batch payloads via `ws.send()`.

Engineers MUST ALWAYS inspect `ws.getBufferedAmount()` before dispatching continuous or batch payloads via `ws.send()`.

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 pause upstream producers or enqueue messages into bounded queues when `ws.getBufferedAmount()` exceeds the defined `HIGH_WATERMARK_BYTES` (e.g., 64 KiB to 1 MiB depending on SLA).

Engineers MUST pause upstream producers or enqueue messages into bounded queues when `ws.getBufferedAmount()` exceeds the defined `HIGH_WATERMARK_BYTES` (e.g., 64 KiB to 1 MiB depending on SLA).

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

Engineers MUST implement the native `drain(ws)` handler in Bun's `websocket` configuration object to trigger queue flush and resume ingestion once buffered bytes fall below `LOW_WATERMARK_BYTES`.

Engineers MUST implement the native `drain(ws)` handler in Bun's `websocket` configuration object to trigger queue flush and resume ingestion once buffered bytes fall below `LOW_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.
4

Code MUST NEVER invoke `ws.send()` in an unthrottled loop or event-listener callback without handling partial writes or saturation states.

Code MUST NEVER invoke `ws.send()` in an unthrottled loop or event-listener callback without handling partial writes or saturation 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.
5

Services MUST drop connections or shed incoming load with explicit WebSocket close frames (code 1008 or 1011) if bounded internal memory queues exceed maximum safety thresholds during persistent consumer stalls.

Services MUST drop connections or shed incoming load with explicit WebSocket close frames (code 1008 or 1011) if bounded internal memory queues exceed maximum safety thresholds during persistent consumer stalls.

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 & High-Water Mark Invariant critical for AI coding assistants?

Enforces deterministic flow control on Bun WebSocket connections by gating transmission against socket-buffered byte thresholds and orchestrating re-activation via the drain lifecycle hook. Without backpressure watermarks, slow consumers cause kernel TCP and native Bun memory buffers to accumulate unboundedly, precipitating event-loop starvation and catastrophic out-of-memory (OOM) termination. 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 (Fire-and-forget socket writes without getBufferedAmount gating or drain callback synchronization.) 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