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

Bun 1.2 Zero-Copy SharedArrayBuffer IPC & Worker Clustering Standard

Enforces zero-copy inter-process and inter-worker communication across Bun 1.2 worker clusters using SharedArrayBuffer and Atomics synchronization primitives. Eliminates structured-cloning overhead, garbage collector thrashing, and sub-millisecond latency spikes in high-throughput multi-core workloads.

Prohibited Anti-Pattern: Serializing High-Frequency Payloads via Structured Clone postMessage Across Bun Workers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy SharedArrayBuffer IPC & Worker Clustering Standard - Enforces zero-copy inter-process and inter-worker communication across Bun 1.2 worker clusters using SharedArrayBuffer and Atomics synchronization primitives. Eliminates structured-cloning overhead, garbage collector thrashing, and sub-millisecond latency spikes in high-throughput multi-core workloads.
globs: src/**/*.worker.ts, src/**/cluster/**/*.ts, src/**/ipc/**/*.ts, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-sharedarraybuffer-ipc-clustering"
---

# Bun 1.2 Zero-Copy SharedArrayBuffer IPC & Worker Clustering Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Serializing High-Frequency Payloads via Structured Clone postMessage Across Bun Workers

## System Constraints
You are a Principal Software Architect enforcing high-performance multi-threaded invariants in Bun 1.2. Reject any worker architecture that relies on structured cloning or JSON serialization over worker.postMessage for high-frequency binary operations. Mandate zero-copy SharedArrayBuffer allocations, strict TypedArray memory layout alignments, and lockless or futex-driven Atomics synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS pass a single SharedArrayBuffer handle during worker initialization and use fixed TypedArray offsets for subsequent communication instead of continuous postMessage serialization.
- Engineers MUST NOT rely on structured clone transfer semantics (worker.postMessage(data)) for multi-core streaming loops exceeding 1,000 operations per second.
- Code MUST synchronize reader and writer cursors exclusively using the Atomics API (e.g., Atomics.wait, Atomics.notify, Atomics.compareExchange, Atomics.load, Atomics.store) to prevent data races and torn reads.
- Workers MUST enforce 4-byte or 8-byte alignment constraints when mapping TypedArray views over SharedArrayBuffer segments to prevent unaligned memory access penalties in JavaScriptCore.
- Services MUST implement graceful worker shutdown by sending an atomic termination sentinel through a designated control segment rather than ungracefully invoking worker.terminate() mid-transaction.
- Components NEVER allocate dynamic ArrayBuffer instances inside the hot loop; allocations MUST occur ahead of time within a pre-sized contiguous memory slab.

## Bad vs Good Implementations
### Zero-Copy Ring Buffer IPC vs Structured Clone Serialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing objects or plain ArrayBuffers through worker.postMessage invokes JavaScriptCore structured cloning, which duplicates memory across heaps, incurs heap allocation locks, and degrades throughput down to sub-10k ops/sec.
```typescript
// BAD: High-frequency postMessage serializes/clones payloads across worker boundaries
// Causes massive GC pressure, latency spikes, and buffer duplication in Bun workers
import { Worker } from 'worker_threads';

interface TaskPayload {
  id: number;
  timestamp: number;
  data: Uint8Array;
}

export function dispatchWorkload(worker: Worker, items: TaskPayload[]) {
  for (const item of items) {
    // ANTI-PATTERN: Structured cloning forces full payload serialization
    worker.postMessage({
      id: item.id,
      timestamp: item.timestamp,
      data: item.data
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Uses a pre-allocated SharedArrayBuffer shared between Bun threads once during startup. Writers and readers coordinate via Atomics.store and Atomics.notify without serializing data or generating garbage collections, reaching sub-microsecond latency and multi-million ops/sec.
```typescript
// GOOD: Pre-allocated SharedArrayBuffer circular ring buffer with Atomics synchronization
const HEADER_SIZE = 8; // [0]: Write Head, [1]: Read Head
const BUFFER_CAPACITY = 1024 * 1024; // 1MB payload buffer
const TOTAL_SAB_SIZE = (HEADER_SIZE * 4) + BUFFER_CAPACITY;

export interface RingBufferIPC {
  sab: SharedArrayBuffer;
  control: Int32Array;
  data: Uint8Array;
}

export function createSharedRingBuffer(): RingBufferIPC {
  const sab = new SharedArrayBuffer(TOTAL_SAB_SIZE);
  const control = new Int32Array(sab, 0, HEADER_SIZE);
  const data = new Uint8Array(sab, HEADER_SIZE * 4, BUFFER_CAPACITY);
  
  // Initialize write (index 0) and read (index 1) pointers
  Atomics.store(control, 0, 0);
  Atomics.store(control, 1, 0);
  
  return { sab, control, data };
}

export function writePayload(ipc: RingBufferIPC, chunk: Uint8Array): boolean {
  const writeIndex = Atomics.load(ipc.control, 0);
  const readIndex = Atomics.load(ipc.control, 1);
  
  const available = (readIndex - writeIndex - 1 + BUFFER_CAPACITY) % BUFFER_CAPACITY;
  if (chunk.length + 4 > available) {
    return false; // Buffer full; drop or apply backpressure
  }
  
  // Write frame size (4 bytes) followed by binary payload
  const frameView = new DataView(ipc.data.buffer, ipc.data.byteOffset + writeIndex, 4);
  frameView.setUint32(0, chunk.length, true);
  ipc.data.set(chunk, writeIndex + 4);
  
  const nextWriteIndex = (writeIndex + 4 + chunk.length) % BUFFER_CAPACITY;
  Atomics.store(ipc.control, 0, nextWriteIndex);
  Atomics.notify(ipc.control, 0, 1);
  return true;
}
```

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 Zero-Copy SharedArrayBuffer IPC & Worker Clustering Standard

Bun 1.2 Zero-Copy SharedArrayBuffer IPC & Worker Clustering Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-copy inter-process and inter-worker communication across Bun 1.2 worker clusters using SharedArrayBuffer and Atomics synchronization primitives. Eliminates structured-cloning overhead, garbage collector thrashing, and sub-millisecond latency spikes in high-throughput multi-core workloads. 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: Serializing High-Frequency Payloads via Structured Clone postMessage Across Bun Workers 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 DriftSerializing High-Frequency Payloads via Structured Clone postMessage Across Bun WorkersCritical
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 pass a single SharedArrayBuffer handle during worker initialization and use fixed TypedArray offsets for subsequent communication instead of continuous postMessage serialization.

Engineers MUST ALWAYS pass a single SharedArrayBuffer handle during worker initialization and use fixed TypedArray offsets for subsequent communication instead of continuous postMessage serialization.

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 rely on structured clone transfer semantics (worker.postMessage(data)) for multi-core streaming loops exceeding 1,000 operations per second.

Engineers MUST NOT rely on structured clone transfer semantics (worker.postMessage(data)) for multi-core streaming loops exceeding 1,000 operations per second.

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 MUST synchronize reader and writer cursors exclusively using the Atomics API (e.g., Atomics.wait, Atomics.notify, Atomics.compareExchange, Atomics.load, Atomics.store) to prevent data races and torn reads.

Code MUST synchronize reader and writer cursors exclusively using the Atomics API (e.g., Atomics.wait, Atomics.notify, Atomics.compareExchange, Atomics.load, Atomics.store) to prevent data races and torn reads.

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

Workers MUST enforce 4-byte or 8-byte alignment constraints when mapping TypedArray views over SharedArrayBuffer segments to prevent unaligned memory access penalties in JavaScriptCore.

Workers MUST enforce 4-byte or 8-byte alignment constraints when mapping TypedArray views over SharedArrayBuffer segments to prevent unaligned memory access penalties in JavaScriptCore.

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 implement graceful worker shutdown by sending an atomic termination sentinel through a designated control segment rather than ungracefully invoking worker.terminate() mid-transaction.

Services MUST implement graceful worker shutdown by sending an atomic termination sentinel through a designated control segment rather than ungracefully invoking worker.terminate() mid-transaction.

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.
6

Components NEVER allocate dynamic ArrayBuffer instances inside the hot loop

Components NEVER allocate dynamic ArrayBuffer instances inside the hot loop; allocations MUST occur ahead of time within a pre-sized contiguous memory slab.

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 SharedArrayBuffer IPC & Worker Clustering Standard critical for AI coding assistants?

Enforces zero-copy inter-process and inter-worker communication across Bun 1.2 worker clusters using SharedArrayBuffer and Atomics synchronization primitives. Eliminates structured-cloning overhead, garbage collector thrashing, and sub-millisecond latency spikes in high-throughput multi-core workloads. 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 (Serializing High-Frequency Payloads via Structured Clone postMessage Across Bun Workers) 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