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

Bun 1.2 Native WebSocket Dynamic PerMessage-Deflate Backpressure Enforcement

Enforces strict backpressure controls on Bun 1.2 native WebSocket servers streaming dense event payloads. Dynamically modulates compression and drops deflate frame wrapping when socket write buffers exceed kernel watermark thresholds to prevent severe heap bloat and unrecoverable OOM crashes.

Prohibited Anti-Pattern: Unchecked PerMessage-Deflate Streaming Causing Catastrophic Memory Exhaustion via Buffered Zlib Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native WebSocket Dynamic PerMessage-Deflate Backpressure Enforcement - Enforces strict backpressure controls on Bun 1.2 native WebSocket servers streaming dense event payloads. Dynamically modulates compression and drops deflate frame wrapping when socket write buffers exceed kernel watermark thresholds to prevent severe heap bloat and unrecoverable OOM crashes.
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-dynamic-deflate-backpressure"
---

# Bun 1.2 Native WebSocket Dynamic PerMessage-Deflate Backpressure Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked PerMessage-Deflate Streaming Causing Catastrophic Memory Exhaustion via Buffered Zlib Contexts

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Native WebSocket Dynamic PerMessage-Deflate Backpressure Enforcement. You mandate that WebSocket servers monitor `ws.getBufferedAmount()` prior to dispatching messages. Under high write-buffer saturation, the engine must either bypass compression, queue with bounded buffers, or pause frame consumption to prevent memory amplification from concurrent zlib allocations.

## Strict Guidelines
- Engineers MUST ALWAYS inspect `ws.getBufferedAmount()` before calling `ws.send()` on high-throughput event streams.
- Engineers MUST dynamically set `compress: false` on `ws.send(data, compress)` when `ws.getBufferedAmount()` breaches the configured low-watermark threshold (e.g., 64 KiB).
- Services MUST drop non-critical broadcast messages or apply active upstream backpressure when `ws.getBufferedAmount()` breaches the critical high-watermark threshold (e.g., 1 MiB).
- Engineers MUST NOT configure static global `perMessageDeflate: true` without explicitly handling dynamic per-call compression overrides during saturated network cycles.
- Handlers MUST implement the native `drain(ws)` socket lifecycle hook to resume suspended producers or clear backpressure lockouts.

## Bad vs Good Implementations
### Dynamic Deflate Deactivation Based on Kernel Socket Backpressure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Sending large batches of compressed messages without checking `ws.getBufferedAmount()` causes Bun's internal send queues and zlib streams to accumulate unbounded memory, rapidly triggering out-of-memory termination under degraded client network conditions.
```typescript
import { serve } from 'bun';

interface ClientData {
  id: string;
}

serve<ClientData>({
  port: 3000,
  websocket: {
    perMessageDeflate: true,
    open(ws) {
      console.log(`Client connected: ${ws.data.id}`);
    },
    message(ws, message) {
      // CRITICAL ANTI-PATTERN: Blind broadcast with unconstrained compression
      // Allocates new zlib execution contexts even when the underlying socket is stalled,
      // buffering compressed frames in userspace and causing process OOM.
      for (let i = 0; i < 100_000; i++) {
        ws.send(JSON.stringify({ event: 'metric_update', index: i, payload: 'x'.repeat(1024) }));
      }
    },
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID() } })) return;
    return new Response('Expected WebSocket upgrade', { status: 400 });
  },
});
```

#### Production Standard (Correct)
> **Standard**: Implements fine-grained backpressure thresholds. Message deflation is dynamically disabled when buffered amount passes `LOW_WATERMARK_BYTES`, shedding CPU and zlib buffer allocation overhead. If saturation exceeds `HIGH_WATERMARK_BYTES`, outbound traffic is paused until the native `drain` event confirms buffer clearance.
```typescript
import { serve, type ServerWebSocket } from 'bun';

interface ClientData {
  id: string;
  isBackpressured: boolean;
}

const LOW_WATERMARK_BYTES = 64 * 1024;    // 64 KiB: disable compression to save CPU/memory
const HIGH_WATERMARK_BYTES = 1024 * 1024; // 1 MiB: pause/drop non-essential frames

function sendAdaptive(
  ws: ServerWebSocket<ClientData>,
  payload: string | Uint8Array
): boolean {
  const buffered = ws.getBufferedAmount();

  if (buffered >= HIGH_WATERMARK_BYTES) {
    ws.data.isBackpressured = true;
    return false; // Drop or defer upstream event
  }

  // Dynamically bypass perMessageDeflate if kernel buffer is accumulating frames
  const shouldCompress = buffered < LOW_WATERMARK_BYTES;
  const bytesSentOrQueued = ws.send(payload, shouldCompress);

  return bytesSentOrQueued > 0;
}

serve<ClientData>({
  port: 3000,
  websocket: {
    perMessageDeflate: true,
    open(ws) {
      ws.data = { id: crypto.randomUUID(), isBackpressured: false };
    },
    message(ws, message) {
      const payload = JSON.stringify({ event: 'telemetry_stream', data: message });
      const dispatched = sendAdaptive(ws, payload);
      if (!dispatched) {
        console.warn(`[Backpressure] Client ${ws.data.id} send buffer saturated (${ws.getBufferedAmount()} bytes)`);
      }
    },
    drain(ws) {
      if (ws.getBufferedAmount() < LOW_WATERMARK_BYTES) {
        ws.data.isBackpressured = false;
      }
    },
  },
  fetch(req, server) {
    if (server.upgrade(req, { data: { id: crypto.randomUUID(), isBackpressured: false } })) {
      return;
    }
    return new Response('WebSocket upgrade expected', { status: 426 });
  },
});
```

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 Dynamic PerMessage-Deflate Backpressure Enforcement

Bun 1.2 Native WebSocket Dynamic PerMessage-Deflate Backpressure Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict backpressure controls on Bun 1.2 native WebSocket servers streaming dense event payloads. Dynamically modulates compression and drops deflate frame wrapping when socket write buffers exceed kernel watermark thresholds to prevent severe heap bloat and unrecoverable OOM crashes. 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 PerMessage-Deflate Streaming Causing Catastrophic Memory Exhaustion via Buffered Zlib Contexts 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 PerMessage-Deflate Streaming Causing Catastrophic Memory Exhaustion via Buffered Zlib ContextsCritical
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 calling `ws.send()` on high-throughput event streams.

Engineers MUST ALWAYS inspect `ws.getBufferedAmount()` before calling `ws.send()` on high-throughput event streams.

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 dynamically set `compress

Engineers MUST dynamically set `compress: false` on `ws.send(data, compress)` when `ws.getBufferedAmount()` breaches the configured low-watermark threshold (e.g., 64 KiB).

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 drop non-critical broadcast messages or apply active upstream backpressure when `ws.getBufferedAmount()` breaches the critical high-watermark threshold (e.g., 1 MiB).

Services MUST drop non-critical broadcast messages or apply active upstream backpressure when `ws.getBufferedAmount()` breaches the critical high-watermark threshold (e.g., 1 MiB).

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

Engineers MUST NOT configure static global `perMessageDeflate

Engineers MUST NOT configure static global `perMessageDeflate: true` without explicitly handling dynamic per-call compression overrides during saturated network cycles.

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

Handlers MUST implement the native `drain(ws)` socket lifecycle hook to resume suspended producers or clear backpressure lockouts.

Handlers MUST implement the native `drain(ws)` socket lifecycle hook to resume suspended producers or clear backpressure lockouts.

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 Dynamic PerMessage-Deflate Backpressure Enforcement critical for AI coding assistants?

Enforces strict backpressure controls on Bun 1.2 native WebSocket servers streaming dense event payloads. Dynamically modulates compression and drops deflate frame wrapping when socket write buffers exceed kernel watermark thresholds to prevent severe heap bloat and unrecoverable OOM crashes. 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 PerMessage-Deflate Streaming Causing Catastrophic Memory Exhaustion via Buffered Zlib Contexts) 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