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

Bun 1.2 Native Worker SharedArrayBuffer & Atomics Concurrency Standard

Enforces zero-copy SharedArrayBuffer memory sharing synchronized strictly through JavaScript Atomics across Bun 1.2 native workers. Eliminates microsecond-scale structured clone serialization overhead while preventing race conditions, memory tearing, and main-thread synchronous deadlocks.

Prohibited Anti-Pattern: Structured Clone Serialization Overhead & Unsynchronized SharedArrayBuffer Memory Tearing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Worker SharedArrayBuffer & Atomics Concurrency Standard - Enforces zero-copy SharedArrayBuffer memory sharing synchronized strictly through JavaScript Atomics across Bun 1.2 native workers. Eliminates microsecond-scale structured clone serialization overhead while preventing race conditions, memory tearing, and main-thread synchronous deadlocks.
globs: src/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-atomics-concurrency"
---

# Bun 1.2 Native Worker SharedArrayBuffer & Atomics Concurrency Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Structured Clone Serialization Overhead & Unsynchronized SharedArrayBuffer Memory Tearing

## System Constraints
You are a Principal Systems Engineer enforcing the Bun 1.2 Native Worker SharedArrayBuffer Concurrency Standard. You must mandate zero-copy memory transfers via SharedArrayBuffer for microsecond-sensitive IPC, forbid regular object serialization on critical hot paths, enforce strict synchronization via Atomics primitives, and prevent synchronous Atomics.wait execution on the main event loop.

## Strict Guidelines
- Engineers MUST ALWAYS exchange high-frequency or latency-critical data between Bun workers using SharedArrayBuffer backed by TypedArray views rather than passing plain objects via structured clone postMessage.
- Engineers MUST NOT invoke synchronous Atomics.wait() on the main event loop thread; synchronous waiting on the main thread throws a TypeError in conformant JavaScript runtimes. The main thread MUST use Atomics.waitAsync() or non-blocking event mechanisms.
- Workers MUST ALWAYS synchronize shared memory state mutations using Atomics operations (Atomics.load, Atomics.store, Atomics.add, Atomics.compareExchange, Atomics.wait, Atomics.notify) to guarantee memory visibility and prevent torn reads/writes across CPU cores.
- Shared memory layouts MUST align index headers and state flags to 4-byte boundaries for Int32Array or 8-byte boundaries for BigInt64Array, isolating read and write pointers with 64-byte cache-line padding to prevent false sharing.
- Components NEVER rely on arbitrary busy-wait while-loops over SharedArrayBuffer memory addresses; workers waiting for state transitions MUST suspend execution using Atomics.wait() with explicit timeout handling to avoid pegging CPU cores.

## Bad vs Good Implementations
### Zero-Copy Circular Ring Buffer IPC with Atomics vs Structured Cloning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing complex payloads through postMessage incurs V8/JSC structured-clone serialization overhead that can take hundreds of microseconds for large buffers, defeating low-latency guarantees. Conversely, accessing a SharedArrayBuffer via raw TypedArray assignments without Atomics primitives introduces compiler/CPU instruction reordering, torn reads, and wasteful 100% CPU core spinning.
```typescript
// ANTI-PATTERN: Heavy structured clone serialization and unsynchronized shared memory access
import { Worker } from "bun";

interface IngestionMessage {
  id: number;
  timestamp: number;
  payload: Float64Array;
}

// 1. Serialization Overhead: Cloning 100k items/sec causes massive GC pressure & serialization delays
export function dispatchViaClone(worker: Worker, msg: IngestionMessage): void {
  worker.postMessage(msg); // Structured clone deep copies the entire typed array and object envelope
}

// 2. Unsynchronized SharedArrayBuffer Mutation: Susceptible to race conditions and torn reads
export function unsynchronizedWorkerLoop(sharedBuffer: SharedArrayBuffer): void {
  const view = new Int32Array(sharedBuffer);
  // Spin-lock without Atomics causes 100% CPU core utilization and memory reordering bugs
  while (view[0] === 0) {
    // Busy spin with no CPU pause or memory barrier
  }
  const data = view[1]; // Torn read if writer updates view[1] non-atomically
  view[0] = 0; // Lost-update hazard
}
```

#### Production Standard (Correct)
> **Standard**: Allocates a single SharedArrayBuffer structured with explicit cache-line padding between write and read pointers. Producers publish values with Atomics.store and signal sleeping threads with Atomics.notify. Consumers park cleanly using Atomics.wait without burning CPU cycles, achieving sub-microsecond zero-copy latency without GC allocation or structured clone serialization.
```typescript
// PRODUCTION INVARIANT: Atomics-synchronized futex-style ring buffer over SharedArrayBuffer
import { Worker } from "bun";

// Memory Layout (64-byte cache line padded):
// [0]: Write Index (Int32, Atomic)
// [1]: Read Index  (Int32, Atomic)
// [2..15]: Padding to prevent false sharing
// [16..N]: Data ring buffer slots (Int32)
const HEADER_SLOTS = 16;
const RING_CAPACITY = 1024;
const TOTAL_BYTES = (HEADER_SLOTS + RING_CAPACITY) * Int32Array.BYTES_PER_ELEMENT;

export interface SharedQueueChannel {
  sab: SharedArrayBuffer;
  control: Int32Array;
  data: Int32Array;
}

export function createSharedQueueChannel(): SharedQueueChannel {
  const sab = new SharedArrayBuffer(TOTAL_BYTES);
  const control = new Int32Array(sab, 0, HEADER_SLOTS);
  const data = new Int32Array(sab, HEADER_SLOTS * Int32Array.BYTES_PER_ELEMENT, RING_CAPACITY);
  return { sab, control, data };
}

export function enqueueItem(channel: SharedQueueChannel, value: number): boolean {
  const writeIndex = Atomics.load(channel.control, 0);
  const readIndex = Atomics.load(channel.control, 1);
  const nextWrite = (writeIndex + 1) % RING_CAPACITY;

  if (nextWrite === readIndex) {
    return false; // Queue full - backpressure
  }

  Atomics.store(channel.data, writeIndex, value);
  Atomics.store(channel.control, 0, nextWrite);
  Atomics.notify(channel.control, 0, 1); // Wake single consumer
  return true;
}

export function workerConsumerLoop(channel: SharedQueueChannel, signal: { active: boolean }): void {
  while (signal.active) {
    const writeIndex = Atomics.load(channel.control, 0);
    const readIndex = Atomics.load(channel.control, 1);

    if (writeIndex === readIndex) {
      // Zero CPU spin: Sleep worker thread until notified or 250ms timeout expires
      Atomics.wait(channel.control, 0, writeIndex, 250);
      continue;
    }

    const value = Atomics.load(channel.data, readIndex);
    const nextRead = (readIndex + 1) % RING_CAPACITY;
    Atomics.store(channel.control, 1, nextRead);

    // Process value with sub-microsecond IPC latency
    void value;
  }
}
```

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 Worker SharedArrayBuffer & Atomics Concurrency Standard

Bun 1.2 Native Worker SharedArrayBuffer & Atomics Concurrency Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-copy SharedArrayBuffer memory sharing synchronized strictly through JavaScript Atomics across Bun 1.2 native workers. Eliminates microsecond-scale structured clone serialization overhead while preventing race conditions, memory tearing, and main-thread synchronous deadlocks. 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: Structured Clone Serialization Overhead & Unsynchronized SharedArrayBuffer Memory Tearing 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 DriftStructured Clone Serialization Overhead & Unsynchronized SharedArrayBuffer Memory TearingCritical
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 exchange high-frequency or latency-critical data between Bun workers using SharedArrayBuffer backed by TypedArray views rather than passing plain objects via structured clone postMessage.

Engineers MUST ALWAYS exchange high-frequency or latency-critical data between Bun workers using SharedArrayBuffer backed by TypedArray views rather than passing plain objects via structured clone postMessage.

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 invoke synchronous Atomics.wait() on the main event loop thread

Engineers MUST NOT invoke synchronous Atomics.wait() on the main event loop thread; synchronous waiting on the main thread throws a TypeError in conformant JavaScript runtimes. The main thread MUST use Atomics.waitAsync() or non-blocking event mechanisms.

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

Workers MUST ALWAYS synchronize shared memory state mutations using Atomics operations (Atomics.load, Atomics.store, Atomics.add, Atomics.compareExchange, Atomics.wait, Atomics.notify) to guarantee memory visibility and prevent torn reads/writes across CPU cores.

Workers MUST ALWAYS synchronize shared memory state mutations using Atomics operations (Atomics.load, Atomics.store, Atomics.add, Atomics.compareExchange, Atomics.wait, Atomics.notify) to guarantee memory visibility and prevent torn reads/writes across CPU cores.

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

Shared memory layouts MUST align index headers and state flags to 4-byte boundaries for Int32Array or 8-byte boundaries for BigInt64Array, isolating read and write pointers with 64-byte cache-line padding to prevent false sharing.

Shared memory layouts MUST align index headers and state flags to 4-byte boundaries for Int32Array or 8-byte boundaries for BigInt64Array, isolating read and write pointers with 64-byte cache-line padding to prevent false sharing.

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 rely on arbitrary busy-wait while-loops over SharedArrayBuffer memory addresses

Components NEVER rely on arbitrary busy-wait while-loops over SharedArrayBuffer memory addresses; workers waiting for state transitions MUST suspend execution using Atomics.wait() with explicit timeout handling to avoid pegging CPU cores.

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

Enforces zero-copy SharedArrayBuffer memory sharing synchronized strictly through JavaScript Atomics across Bun 1.2 native workers. Eliminates microsecond-scale structured clone serialization overhead while preventing race conditions, memory tearing, and main-thread synchronous deadlocks. 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 (Structured Clone Serialization Overhead & Unsynchronized SharedArrayBuffer Memory Tearing) 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