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

Bun 1.2 Multi-Worker SharedArrayBuffer Zero-Copy and Atomic Memory Fences

Mandates zero-copy memory boundaries across Bun 1.2 Worker instances using SharedArrayBuffer and explicit Transferable objects to eliminate structured clone serialization latencies. Enforces strict synchronization invariants using the Atomics API to prevent data races and memory corruption in shared typed arrays.

Prohibited Anti-Pattern: Implicit Structured Cloning and Unsynchronized Shared Memory Access in Multi-Threaded Workers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Worker SharedArrayBuffer Zero-Copy and Atomic Memory Fences - Mandates zero-copy memory boundaries across Bun 1.2 Worker instances using SharedArrayBuffer and explicit Transferable objects to eliminate structured clone serialization latencies. Enforces strict synchronization invariants using the Atomics API to prevent data races and memory corruption in shared typed arrays.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/services/**/*.ts, src/lib/concurrency/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-zero-copy-standard"
---

# Bun 1.2 Multi-Worker SharedArrayBuffer Zero-Copy and Atomic Memory Fences

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Structured Cloning and Unsynchronized Shared Memory Access in Multi-Threaded Workers

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Multi-Worker SharedArrayBuffer Zero-Copy Transfer Boundaries. Mandate zero structured-clone overhead for high-throughput compute microservices. Require all cross-thread binary buffers to leverage SharedArrayBuffer with Atomics memory synchronization or explicit Transferable ArrayBuffer ownership handoffs. Reject any implicit serialization of typed arrays or raw buffers across Worker boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS initialize shared memory regions with `new SharedArrayBuffer(byteLength)` and pass typed array views rather than cloning standard `ArrayBuffer` instances.
- Engineers MUST NOT execute cross-worker communications using bare `postMessage(data)` when `data` contains multi-megabyte payloads, typed arrays, or tensor structures without specifying the transfer list or using a `SharedArrayBuffer`.
- Code MUST synchronize all read, write, and condition signaling across shared buffers exclusively through the `Atomics` API (`Atomics.store`, `Atomics.load`, `Atomics.wait`, `Atomics.notify`, `Atomics.compareExchange`).
- Services MUST NEVER invoke `Atomics.wait` on the main Bun event-loop thread; synchronous waiting is restricted to dedicated background Worker threads, while the main thread MUST use `Atomics.waitAsync` or non-blocking polling.
- Worker boundaries SHOULD structure shared memory into discrete header and payload byte partitions, enforcing 4-byte or 8-byte alignment for typed view offsets to prevent unaligned atomic access faults.

## Bad vs Good Implementations
### Zero-Copy State Coordination via SharedArrayBuffer and Atomics

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a non-shared Uint8Array directly via postMessage invokes the structured clone algorithm. In high-frequency pipelines, this causes severe memory churn, multi-millisecond serialization latencies, and high GC pressure in Bun workers.
```typescript
// ANTI-PATTERN: Forces expensive structured cloning across the thread boundary
// and introduces data race vulnerability on state update.
import { Worker } from "bun";

const worker = new Worker(new URL("./compute.worker.ts", import.meta.url));
const payload = new Uint8Array(1024 * 1024 * 16); // 16MB payload

// Triggers full heap clone across V8/JSC isolate boundary
worker.postMessage({ type: "PROCESS", buffer: payload });

worker.onmessage = (event) => {
  // Insecure and high GC overhead
  console.log("Processed status:", event.data.status);
};
```

#### Production Standard (Correct)
> **Standard**: The memory segment is allocated exactly once via SharedArrayBuffer. Pointer metadata is shared instantly without serialization overhead, and state access is governed by atomic store/notify memory fences to eliminate data races.
```typescript
// PRODUCTION STANDARD: SharedArrayBuffer zero-copy transfer with Atomics synchronization
import { Worker } from "bun";

// Byte offsets: [0..3]: Control Flag (0=idle, 1=ready, 2=complete), [4..7]: Payload length, [8..N]: Ring buffer
const HEADER_BYTES = 8;
const PAYLOAD_BYTES = 1024 * 1024 * 16; // 16MB buffer
const sab = new SharedArrayBuffer(HEADER_BYTES + PAYLOAD_BYTES);

const controlView = new Int32Array(sab, 0, 2);
const payloadView = new Uint8Array(sab, HEADER_BYTES, PAYLOAD_BYTES);

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

// Pass SharedArrayBuffer reference directly (zero-copy pointer exchange)
worker.postMessage({ type: "INIT_SHARED_BUFFER", buffer: sab });

// Write data zero-copy into shared partition
payloadView.fill(0x7f);
Atomics.store(controlView, 1, PAYLOAD_BYTES); // Store length safely

// Release fence: notify worker that data is ready
Atomics.store(controlView, 0, 1);
Atomics.notify(controlView, 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 Multi-Worker SharedArrayBuffer Zero-Copy and Atomic Memory Fences

Bun 1.2 Multi-Worker SharedArrayBuffer Zero-Copy and Atomic Memory Fences defines an industrial-grade behavioral standard for backend engineering. Mandates zero-copy memory boundaries across Bun 1.2 Worker instances using SharedArrayBuffer and explicit Transferable objects to eliminate structured clone serialization latencies. Enforces strict synchronization invariants using the Atomics API to prevent data races and memory corruption in shared typed arrays. 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 Cloning and Unsynchronized Shared Memory Access in Multi-Threaded 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 DriftImplicit Structured Cloning and Unsynchronized Shared Memory Access in Multi-Threaded 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 initialize shared memory regions with `new SharedArrayBuffer(byteLength)` and pass typed array views rather than cloning standard `ArrayBuffer` instances.

Engineers MUST ALWAYS initialize shared memory regions with `new SharedArrayBuffer(byteLength)` and pass typed array views rather than cloning standard `ArrayBuffer` instances.

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 execute cross-worker communications using bare `postMessage(data)` when `data` contains multi-megabyte payloads, typed arrays, or tensor structures without specifying the transfer list or using a `SharedArrayBuffer`.

Engineers MUST NOT execute cross-worker communications using bare `postMessage(data)` when `data` contains multi-megabyte payloads, typed arrays, or tensor structures without specifying the transfer list or using a `SharedArrayBuffer`.

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 all read, write, and condition signaling across shared buffers exclusively through the `Atomics` API (`Atomics.store`, `Atomics.load`, `Atomics.wait`, `Atomics.notify`, `Atomics.compareExchange`).

Code MUST synchronize all read, write, and condition signaling across shared buffers exclusively through the `Atomics` API (`Atomics.store`, `Atomics.load`, `Atomics.wait`, `Atomics.notify`, `Atomics.compareExchange`).

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 NEVER invoke `Atomics.wait` on the main Bun event-loop thread

Services MUST NEVER invoke `Atomics.wait` on the main Bun event-loop thread; synchronous waiting is restricted to dedicated background Worker threads, while the main thread MUST use `Atomics.waitAsync` or non-blocking polling.

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

Worker boundaries SHOULD structure shared memory into discrete header and payload byte partitions, enforcing 4-byte or 8-byte alignment for typed view offsets to prevent unaligned atomic access faults.

Worker boundaries SHOULD structure shared memory into discrete header and payload byte partitions, enforcing 4-byte or 8-byte alignment for typed view offsets to prevent unaligned atomic access faults.

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 Multi-Worker SharedArrayBuffer Zero-Copy and Atomic Memory Fences critical for AI coding assistants?

Mandates zero-copy memory boundaries across Bun 1.2 Worker instances using SharedArrayBuffer and explicit Transferable objects to eliminate structured clone serialization latencies. Enforces strict synchronization invariants using the Atomics API to prevent data races and memory corruption in shared typed arrays. 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 Cloning and Unsynchronized Shared Memory Access in Multi-Threaded 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