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

Bun 1.2 Zero-Copy WebSocket Frame Buffer Pooling Standard

Enforces deterministic slab-allocated buffer pooling and zero-copy transmission semantics for Bun WebSocket servers. Prevents microsecond-latency degradation caused by per-message heap allocation, V8/JSC GC thrashing, and intermediate memory cloning during high-frequency bidirectional streaming.

Prohibited Anti-Pattern: Ad-Hoc Uint8Array Allocation and String Payload Serialization in High-Throughput WebSocket Broadcasts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy WebSocket Frame Buffer Pooling Standard - Enforces deterministic slab-allocated buffer pooling and zero-copy transmission semantics for Bun WebSocket servers. Prevents microsecond-latency degradation caused by per-message heap allocation, V8/JSC GC thrashing, and intermediate memory cloning during high-frequency bidirectional streaming.
globs: src/**/*.ts, server/**/*.ts, gateway/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-websocket-buffer-pooling-standard"
---

# Bun 1.2 Zero-Copy WebSocket Frame Buffer Pooling Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ad-Hoc Uint8Array Allocation and String Payload Serialization in High-Throughput WebSocket Broadcasts

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-copy binary serialization and memory pooling invariants for Bun 1.2 WebSocket microservices. Disallow dynamic buffer construction inside frame-dispatch loops, prohibit string payloads in low-latency paths, and mandate deterministic ArrayBuffer view lifecycle management.

## Strict Guidelines
- Engineers MUST ALWAYS pre-allocate fixed-size slab pools using shared ArrayBuffer backings or direct ArrayBuffer instances for high-frequency binary frame dispatch.
- Engineers MUST NOT construct ad-hoc Uint8Array instances, dynamic string payloads, or call JSON.stringify within active WebSocket message, tick, or broadcast loops.
- Code SHOULD leverage Bun-native `ServerWebSocket.send(buffer, compress)` with explicit binary flags and zero intermediate slice copies.
- Services MUST recycle pooled buffer views via explicit pointer resets or release callbacks immediately after non-blocking socket dispatch completes.
- Components NEVER hold long-lived references to transient ArrayBuffer views received in the `message(ws, message)` callback without explicitly borrowing into an isolated replica.

## Bad vs Good Implementations
### High-Frequency WebSocket Broadcast: Dynamic Allocations vs Pre-Allocated Ring Slab Pool

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocates brand-new JSON strings or individual Uint8Array buffers inside iteration loops. This forces the JavaScriptCore GC to constantly clean up short-lived objects under high throughput, introducing multi-millisecond stop-the-world pauses and high CPU overhead.
```typescript
import type { ServerWebSocket } from "bun";

interface MarketTick {
  symbolId: number;
  price: number;
  volume: number;
}

// ANTI-PATTERN: Heap churn per tick, stringification, dynamic allocations
export function broadcastTick(clients: ServerWebSocket<unknown>[], tick: MarketTick): void {
  for (const ws of clients) {
    // Allocates new JSON string and internal UTF-16/UTF-8 conversions per message
    const payload = JSON.stringify(tick);
    ws.send(payload);
  }
}

// ANTI-PATTERN: Dynamic slice allocation inside network hot path
export function broadcastBinarySlow(clients: ServerWebSocket<unknown>[], tick: MarketTick): void {
  for (const ws of clients) {
    const buf = new Uint8Array(16); // Allocates a new heap buffer per subscriber
    const view = new DataView(buf.buffer);
    view.setUint32(0, tick.symbolId, true);
    view.setFloat64(4, tick.price, true);
    view.setUint32(12, tick.volume, true);
    ws.send(buf, true); // Intermediate copy triggered per dispatch
  }
}
```

#### Production Standard (Correct)
> **Standard**: Uses a pre-allocated contiguous ArrayBuffer slab pool and DataView indexers. Memory is allocated once at startup. High-frequency tick serialization mutates existing memory in place and broadcasts a shared buffer view across all active WebSockets, completely bypassing GC allocation churn.
```typescript
import type { ServerWebSocket } from "bun";

// PRODUCTION STANDARD: Reusable frame buffer pool with zero per-dispatch allocation
const FRAME_SIZE = 16;
const POOL_CAPACITY = 64;

class WebSocketFramePool {
  private readonly masterBuffer = new ArrayBuffer(FRAME_SIZE * POOL_CAPACITY);
  private readonly views: Uint8Array[] = [];
  private readonly dataViews: DataView[] = [];
  private head = 0;

  constructor() {
    for (let i = 0; i < POOL_CAPACITY; i++) {
      const offset = i * FRAME_SIZE;
      this.views.push(new Uint8Array(this.masterBuffer, offset, FRAME_SIZE));
      this.dataViews.push(new DataView(this.masterBuffer, offset, FRAME_SIZE));
    }
  }

  public acquire(): { view: Uint8Array; dv: DataView } {
    const index = this.head;
    this.head = (this.head + 1) % POOL_CAPACITY;
    return { view: this.views[index]!, dv: this.dataViews[index]! };
  }
}

const framePool = new WebSocketFramePool();

interface MarketTick {
  symbolId: number;
  price: number;
  volume: number;
}

export function broadcastTickFast(clients: readonly ServerWebSocket<unknown>[], tick: MarketTick): void {
  const { view, dv } = framePool.acquire();
  
  // Binary serialization directly into pre-allocated memory
  dv.setUint32(0, tick.symbolId, true);
  dv.setFloat64(4, tick.price, true);
  dv.setUint32(12, tick.volume, true);

  // Zero-copy dispatch of immutable slab view to all connected clients
  for (let i = 0; i < clients.length; i++) {
    clients[i]!.send(view, 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 Zero-Copy WebSocket Frame Buffer Pooling Standard

Bun 1.2 Zero-Copy WebSocket Frame Buffer Pooling Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic slab-allocated buffer pooling and zero-copy transmission semantics for Bun WebSocket servers. Prevents microsecond-latency degradation caused by per-message heap allocation, V8/JSC GC thrashing, and intermediate memory cloning during high-frequency bidirectional streaming. 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: Ad-Hoc Uint8Array Allocation and String Payload Serialization in High-Throughput WebSocket Broadcasts 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 DriftAd-Hoc Uint8Array Allocation and String Payload Serialization in High-Throughput WebSocket BroadcastsCritical
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 pre-allocate fixed-size slab pools using shared ArrayBuffer backings or direct ArrayBuffer instances for high-frequency binary frame dispatch.

Engineers MUST ALWAYS pre-allocate fixed-size slab pools using shared ArrayBuffer backings or direct ArrayBuffer instances for high-frequency binary frame dispatch.

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 construct ad-hoc Uint8Array instances, dynamic string payloads, or call JSON.stringify within active WebSocket message, tick, or broadcast loops.

Engineers MUST NOT construct ad-hoc Uint8Array instances, dynamic string payloads, or call JSON.stringify within active WebSocket message, tick, or broadcast loops.

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 leverage Bun-native `ServerWebSocket.send(buffer, compress)` with explicit binary flags and zero intermediate slice copies.

Code SHOULD leverage Bun-native `ServerWebSocket.send(buffer, compress)` with explicit binary flags and zero intermediate slice copies.

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 recycle pooled buffer views via explicit pointer resets or release callbacks immediately after non-blocking socket dispatch completes.

Services MUST recycle pooled buffer views via explicit pointer resets or release callbacks immediately after non-blocking socket dispatch completes.

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 hold long-lived references to transient ArrayBuffer views received in the `message(ws, message)` callback without explicitly borrowing into an isolated replica.

Components NEVER hold long-lived references to transient ArrayBuffer views received in the `message(ws, message)` callback without explicitly borrowing into an isolated replica.

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 Zero-Copy WebSocket Frame Buffer Pooling Standard critical for AI coding assistants?

Enforces deterministic slab-allocated buffer pooling and zero-copy transmission semantics for Bun WebSocket servers. Prevents microsecond-latency degradation caused by per-message heap allocation, V8/JSC GC thrashing, and intermediate memory cloning during high-frequency bidirectional streaming. 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 (Ad-Hoc Uint8Array Allocation and String Payload Serialization in High-Throughput WebSocket Broadcasts) 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