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

Bun 1.2 Zero-Copy Worker Thread IPC Standard

Enforces strict zero-copy Inter-Process Communication (IPC) across Bun native Worker threads using transferable ArrayBuffers and SharedArrayBuffers with Atomics. Eliminates JavaScriptCore (JSC) structured clone serialization overhead and memory copying on CPU-bound payloads. Guarantees deterministic, sub-millisecond execution times for parallel backend workloads.

Prohibited Anti-Pattern: Implicit Structured Clone Serialization of Large TypedArrays and JSON Objects Across Bun Worker Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy Worker Thread IPC Standard - Enforces strict zero-copy Inter-Process Communication (IPC) across Bun native Worker threads using transferable ArrayBuffers and SharedArrayBuffers with Atomics. Eliminates JavaScriptCore (JSC) structured clone serialization overhead and memory copying on CPU-bound payloads. Guarantees deterministic, sub-millisecond execution times for parallel backend workloads.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/**/threads/**/*.ts, src/lib/ipc/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-zero-copy-ipc-standard"
---

# Bun 1.2 Zero-Copy Worker Thread IPC Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Structured Clone Serialization of Large TypedArrays and JSON Objects Across Bun Worker Boundaries

## System Constraints
You are a Principal Software Architect enforcing the Bun 1.2 Zero-Copy Worker Thread IPC Standard. Mandate that all cross-thread message exchanges in Bun utilize transferable ArrayBuffers or SharedArrayBuffers with synchronization primitives. Prohibit passing complex object graphs, JSON strings, or non-transferred TypedArrays across worker boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS pass the underlying ArrayBuffer in the transfer list parameter of worker.postMessage() when sending TypedArrays across thread boundaries.
- Engineers MUST NOT send large JSON objects, serialized strings, or non-transferable TypedArrays across Bun workers, as this triggers expensive JavaScriptCore structured-cloning overhead.
- Code MUST verify that transferred ArrayBuffers are detached (byteLength === 0) on the sending thread post-transfer to prevent unintended concurrent mutation.
- Services handling high-frequency bidirectional IPC MUST utilize SharedArrayBuffer alongside Atomics for signaling and lock-free coordination to eliminate message queue latency.
- Components NEVER instantiate nested object wrappers or deep property trees within worker messages; wrap metadata into fixed-width binary headers or lightweight struct views.

## Bad vs Good Implementations
### Transferable ArrayBuffer IPC vs. Structured Clone Serialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the transfer list in postMessage forces Bun's JavaScriptCore runtime to perform a full structured clone of the 64MB TypedArray. This copies memory across thread boundaries, induces GC pressure, and destroys sub-millisecond performance guarantees.
```typescript
// BAD: Omitting the transfer list causes deep structured clone copying in JSC
import { Worker } from "bun";

const worker = new Worker(new URL("./processor.worker.ts", import.meta.url).href);
const payload = new Uint8Array(1024 * 1024 * 64); // 64MB buffer
crypto.getRandomValues(payload);

// Payload is deeply cloned across threads, incurring GC spikes and >10ms serialization latency
worker.postMessage({
  type: "PROCESS_CHUNK",
  data: payload
});

// Payload remains active in sender memory, creating memory pressure
console.log("Sender byteLength:", payload.byteLength); // Still 67108864
```

#### Production Standard (Correct)
> **Standard**: Passing rawBuffer in the postMessage transfer list detaches memory from the main thread and transfers the pointer directly to the worker thread in O(1) time. Zero byte-copying occurs, resulting in sub-millisecond dispatch and immediate detached-state verification.
```typescript
// GOOD: Transferring ArrayBuffer ownership achieves true zero-copy O(1) memory handoff
import { Worker } from "bun";

const worker = new Worker(new URL("./processor.worker.ts", import.meta.url).href);
const payload = new Uint8Array(1024 * 1024 * 64); // 64MB buffer
crypto.getRandomValues(payload);

const rawBuffer = payload.buffer;

// Transfer ownership of rawBuffer directly without memory allocation or serialization
worker.postMessage(
  {
    type: "PROCESS_CHUNK",
    buffer: rawBuffer
  },
  [rawBuffer]
);

// Sender buffer is immediately detached, preventing race conditions
if (rawBuffer.byteLength !== 0) {
  throw new Error("Buffer transfer failed: ArrayBuffer was not detached.");
}
```

### Lock-Free SharedArrayBuffer and Atomics Ring Buffer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Flooding Bun workers with thousands of high-frequency postMessage payloads saturates the microtask queue and incurs severe event loop scheduling overhead.
```typescript
// BAD: Using message passing loops for high-frequency synchronization
import { Worker } from "bun";

const worker = new Worker(new URL("./counter.worker.ts", import.meta.url).href);

for (let i = 0; i < 100_000; i++) {
  // Generates 100k event-loop turn iterations and serialization checks
  worker.postMessage({ type: "INCREMENT", delta: 1 });
}
```

#### Production Standard (Correct)
> **Standard**: SharedArrayBuffer allows both the main thread and Bun native workers to read and write directly to identical physical memory using Atomics primitives, completely bypassing IPC serialization.
```typescript
// GOOD: SharedArrayBuffer with Atomics for zero-latency cross-thread state
import { Worker } from "bun";

const sharedBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * 4);
const state = new Int32Array(sharedBuffer);
const worker = new Worker(new URL("./counter.worker.ts", import.meta.url).href);

// Share memory reference once
worker.postMessage({ type: "INIT", sharedBuffer });

// Ultra-fast lock-free operations across threads
for (let i = 0; i < 100_000; i++) {
  Atomics.add(state, 0, 1);
}

// Wake waiting thread if synchronized
Atomics.notify(state, 0, 1);
```

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 Worker Thread IPC Standard

Bun 1.2 Zero-Copy Worker Thread IPC Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict zero-copy Inter-Process Communication (IPC) across Bun native Worker threads using transferable ArrayBuffers and SharedArrayBuffers with Atomics. Eliminates JavaScriptCore (JSC) structured clone serialization overhead and memory copying on CPU-bound payloads. Guarantees deterministic, sub-millisecond execution times for parallel backend 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: Implicit Structured Clone Serialization of Large TypedArrays and JSON Objects Across Bun Worker Boundaries 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 DriftImplicit Structured Clone Serialization of Large TypedArrays and JSON Objects Across Bun Worker BoundariesCritical
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 the underlying ArrayBuffer in the transfer list parameter of worker.postMessage() when sending TypedArrays across thread boundaries.

Engineers MUST ALWAYS pass the underlying ArrayBuffer in the transfer list parameter of worker.postMessage() when sending TypedArrays across thread boundaries.

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 send large JSON objects, serialized strings, or non-transferable TypedArrays across Bun workers, as this triggers expensive JavaScriptCore structured-cloning overhead.

Engineers MUST NOT send large JSON objects, serialized strings, or non-transferable TypedArrays across Bun workers, as this triggers expensive JavaScriptCore structured-cloning overhead.

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 verify that transferred ArrayBuffers are detached (byteLength === 0) on the sending thread post-transfer to prevent unintended concurrent mutation.

Code MUST verify that transferred ArrayBuffers are detached (byteLength === 0) on the sending thread post-transfer to prevent unintended concurrent mutation.

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 handling high-frequency bidirectional IPC MUST utilize SharedArrayBuffer alongside Atomics for signaling and lock-free coordination to eliminate message queue latency.

Services handling high-frequency bidirectional IPC MUST utilize SharedArrayBuffer alongside Atomics for signaling and lock-free coordination to eliminate message queue latency.

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 instantiate nested object wrappers or deep property trees within worker messages

Components NEVER instantiate nested object wrappers or deep property trees within worker messages; wrap metadata into fixed-width binary headers or lightweight struct views.

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

Enforces strict zero-copy Inter-Process Communication (IPC) across Bun native Worker threads using transferable ArrayBuffers and SharedArrayBuffers with Atomics. Eliminates JavaScriptCore (JSC) structured clone serialization overhead and memory copying on CPU-bound payloads. Guarantees deterministic, sub-millisecond execution times for parallel backend 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 (Implicit Structured Clone Serialization of Large TypedArrays and JSON Objects Across Bun Worker Boundaries) 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