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

Bun 1.2 Native WebSocket Zero-Loss Backpressure Drain Protocol

Guarantees process resilience under high-concurrency event bursts by wiring kernel socket drain readiness directly to async iterator flow-control. Prevents silent message drops and memory bloat caused by unmonitored uWebSockets buffers in Bun.serve.

Prohibited Anti-Pattern: Fire-and-forget ws.send in unthrottled loops triggering uSockets buffer overflow and process OOM.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Zero-Loss Backpressure Drain Protocol - Guarantees process resilience under high-concurrency event bursts by wiring kernel socket drain readiness directly to async iterator flow-control. Prevents silent message drops and memory bloat caused by unmonitored uWebSockets buffers in Bun.serve.
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-protocol"
---

# Bun 1.2 Native WebSocket Zero-Loss Backpressure Drain Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fire-and-forget ws.send in unthrottled loops triggering uSockets buffer overflow and process OOM.

## System Constraints
You are a Principal Software Architect enforcing Bun 1.2 Native WebSocket backpressure safety standards. Mandate zero-loss flow-control by coupling upstream async iterators to Bun's native drain hooks, monitoring buffered amounts, and preventing unbounded memory growth during high-throughput event spikes.

## Strict Guidelines
- Engineers MUST ALWAYS inspect ws.getBufferedAmount() or the return code of ws.send() before pulling subsequent events from async producers.
- Engineers MUST NOT stream data across WebSockets using unthrottled for-await loops without a drain-synchronized pausing mechanism.
- Code SHOULD establish distinct HIGH_WATER_MARK (e.g., 64 KiB) and LOW_WATER_MARK (e.g., 16 KiB) boundaries to eliminate buffer flapping under load.
- Services MUST define the native drain(ws) callback inside Bun.serve({ websocket: { drain(ws) { ... } } }) to resume paused producers when kernel buffers clear.
- Components NEVER swallow WebSocket close events during paused states; deferred drain promises MUST be rejected or resolved on socket termination to prevent iterator deadlock.

## Bad vs Good Implementations
### Unthrottled Stream Consumption into Native Bun WebSocket

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating through the stream without evaluating ws.getBufferedAmount() causes fast producers to flood Bun's internal uSockets send queue when the client socket is saturated. Memory expands unboundedly, ending in dropped frames or a process-wide OOM crash.
```typescript
import { serve } from "bun";

serve<{
  clientId: string;
}>({
  fetch(req, server) {
    server.upgrade(req, { data: { clientId: "client-1" } });
    return undefined;
  },
  websocket: {
    async open(ws) {
      const producer = getEventStream(); // AsyncIterable<Uint8Array>
      // CRITICAL VIOLATION: Loop ignores kernel send buffer limits.
      // Slow consumer causes unbounded uSockets heap growth and process OOM.
      for await (const chunk of producer) {
        ws.send(chunk);
      }
    },
    message(ws, msg) {},
    close(ws) {}
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements an asynchronous backpressure gate. Upstream iteration suspends when ws.getBufferedAmount() hits HIGH_WATER_MARK. Bun's native drain hook resolves the gate when the buffer clears below LOW_WATER_MARK, assuring zero message loss and deterministic memory bounds.
```typescript
import { serve, type ServerWebSocket } from "bun";

const HIGH_WATER_MARK = 64 * 1024; // 64 KiB
const LOW_WATER_MARK = 16 * 1024;  // 16 KiB

interface WsContext {
  clientId: string;
  drainResolver: (() => void) | null;
}

serve<WsContext>({
  fetch(req, server) {
    server.upgrade(req, {
      data: { clientId: crypto.randomUUID(), drainResolver: null }
    });
    return undefined;
  },
  websocket: {
    async open(ws: ServerWebSocket<WsContext>) {
      const producer = getEventStream();
      try {
        for await (const chunk of producer) {
          if (ws.readyState !== 1) break;

          // Halt producer if uSockets buffer exceeds safe limit
          if (ws.getBufferedAmount() >= HIGH_WATER_MARK) {
            await new Promise<void>((resolve) => {
              ws.data.drainResolver = resolve;
            });
          }

          ws.send(chunk);
        }
      } catch (err) {
        ws.close(1011, "Stream processing aborted");
      }
    },
    drain(ws: ServerWebSocket<WsContext>) {
      // Resume upstream consumption when buffer drains below low-water mark
      if (ws.data.drainResolver && ws.getBufferedAmount() <= LOW_WATER_MARK) {
        const unblock = ws.data.drainResolver;
        ws.data.drainResolver = null;
        unblock();
      }
    },
    message(ws, msg) {},
    close(ws: ServerWebSocket<WsContext>) {
      // Clear suspended promises to avoid resource leaks
      if (ws.data.drainResolver) {
        ws.data.drainResolver();
        ws.data.drainResolver = null;
      }
    }
  }
});
```

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 Zero-Loss Backpressure Drain Protocol

Bun 1.2 Native WebSocket Zero-Loss Backpressure Drain Protocol defines an industrial-grade behavioral standard for backend engineering. Guarantees process resilience under high-concurrency event bursts by wiring kernel socket drain readiness directly to async iterator flow-control. Prevents silent message drops and memory bloat caused by unmonitored uWebSockets buffers in Bun.serve. 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 ws.send in unthrottled loops triggering uSockets buffer overflow and 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 DriftFire-and-forget ws.send in unthrottled loops triggering uSockets buffer overflow and process OOM.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() or the return code of ws.send() before pulling subsequent events from async producers.

Engineers MUST ALWAYS inspect ws.getBufferedAmount() or the return code of ws.send() before pulling subsequent events from async producers.

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 stream data across WebSockets using unthrottled for-await loops without a drain-synchronized pausing mechanism.

Engineers MUST NOT stream data across WebSockets using unthrottled for-await loops without a drain-synchronized pausing mechanism.

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

Code SHOULD establish distinct HIGH_WATER_MARK (e.g., 64 KiB) and LOW_WATER_MARK (e.g., 16 KiB) boundaries to eliminate buffer flapping under load.

Code SHOULD establish distinct HIGH_WATER_MARK (e.g., 64 KiB) and LOW_WATER_MARK (e.g., 16 KiB) boundaries to eliminate buffer flapping under load.

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 define the native drain(ws) callback inside Bun.serve({ websocket

Services MUST define the native drain(ws) callback inside Bun.serve({ websocket: { drain(ws) { ... } } }) to resume paused producers when kernel buffers clear.

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 swallow WebSocket close events during paused states

Components NEVER swallow WebSocket close events during paused states; deferred drain promises MUST be rejected or resolved on socket termination to prevent iterator deadlock.

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 Zero-Loss Backpressure Drain Protocol critical for AI coding assistants?

Guarantees process resilience under high-concurrency event bursts by wiring kernel socket drain readiness directly to async iterator flow-control. Prevents silent message drops and memory bloat caused by unmonitored uWebSockets buffers in Bun.serve. 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 ws.send in unthrottled loops triggering uSockets buffer overflow and 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