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

Bun 1.2 Native Worker Concurrency & Shared Memory Barrier Standard

Bun 1.2 executes native Web Workers with direct access to SharedArrayBuffer instances, enabling sub-millisecond inter-thread messaging. Unfenced mutations and unsynchronized reads across worker boundaries cause torn writes, cache incoherence, and process-terminating segment faults under heavy I/O pressure. This standard mandates explicit memory fences, typed layouts, and Atomics synchronization across all multi-threaded worker pipelines.

Prohibited Anti-Pattern: Unsynchronized SharedArrayBuffer Mutation and Unfenced Worker Ring Buffer R/W Access

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Worker Concurrency & Shared Memory Barrier Standard - Bun 1.2 executes native Web Workers with direct access to SharedArrayBuffer instances, enabling sub-millisecond inter-thread messaging. Unfenced mutations and unsynchronized reads across worker boundaries cause torn writes, cache incoherence, and process-terminating segment faults under heavy I/O pressure. This standard mandates explicit memory fences, typed layouts, and Atomics synchronization across all multi-threaded worker pipelines.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/**/concurrency/**/*.ts, src/**/ipc/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-shared-memory-atomics-barrier-standard"
---

# Bun 1.2 Native Worker Concurrency & Shared Memory Barrier Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized SharedArrayBuffer Mutation and Unfenced Worker Ring Buffer R/W Access

## System Constraints
You are a Principal Systems Architect enforcing Bun 1.2 Native Worker Concurrency & Shared Memory Barrier Standards. You must reject any direct mutation of TypedArrays backed by SharedArrayBuffer that bypasses the global Atomics API. You must enforce atomic memory barriers, futex waiting patterns (Atomics.wait/Atomics.notify), strict memory layout definitions, and structured lifecycle cleanup for all worker pools.

## Strict Guidelines
- Engineers MUST ALWAYS manipulate SharedArrayBuffer data structures through the global Atomics API (e.g., Atomics.load, Atomics.store, Atomics.compareExchange, Atomics.add).
- Engineers MUST NOT read or write to shared typed array slots using direct index assignments (e.g., `view[0] = 1`) across multi-threaded worker boundaries.
- Engineers MUST use `Atomics.wait` and `Atomics.notify` with explicit millisecond timeouts to coordinate producer-consumer transitions instead of hot CPU spin-wait loops.
- Services MUST define rigid memory layout constants with byte-aligned offsets when carving out control blocks, payload headers, and circular buffers in a single SharedArrayBuffer.
- Workers MUST isolate incoming SharedArrayBuffer structures from mutation until lock acquisition is confirmed via atomic test-and-set or compare-and-swap (CAS) routines.
- Code SHOULD verify that `crossOriginIsolated` semantics and memory allocations are pre-allocated at service initialization to prevent runtime allocation failures under load.

## Bad vs Good Implementations
### Atomic Memory Barrier vs. Unsynchronized SharedArrayBuffer Mutation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct indexing on a SharedArrayBuffer bypasses CPU memory fences, creating torn writes, compiler re-ordering hazards, and CPU cache synchronization failures. Unbounded spin loops cause high CPU utilization and scheduler starvation in Bun native worker threads.
```typescript
// Anti-Pattern: Unsynchronized shared state leading to race conditions and torn reads
export class WorkerRingBuffer {
  private state: Int32Array;

  constructor(sharedBuffer: SharedArrayBuffer) {
    this.state = new Int32Array(sharedBuffer);
  }

  public push(val: number): void {
    // DANGEROUS: Direct indexing bypasses CPU store barriers and causes cache incoherence
    while (this.state[0] === 1) {
      // Burning CPU with an empty spin-loop
    }
    this.state[1] = val; // Torn write possible if another thread reads concurrently
    this.state[0] = 1;
  }

  public pop(): number {
    while (this.state[0] === 0) {
      // High CPU spin-wait
    }
    const val = this.state[1];
    this.state[0] = 0;
    return val;
  }
}
```

#### Production Standard (Correct)
> **Standard**: The production pattern uses `Atomics.compareExchange` for lock-free mutual exclusion, leverages kernel-level futex calls via `Atomics.wait` to suspend the thread without burning CPU cycles, and performs all reads/writes via `Atomics.store` and `Atomics.load` to guarantee sequential consistency and cache flushing.
```typescript
// Production-Grade: Explicit Atomics with futex-based blocking and memory barriers
export const enum BufferOffset {
  Lock = 0,
  State = 1,
  Data = 2,
}

export const enum LockState {
  Unlocked = 0,
  Locked = 1,
}

export class WorkerRingBuffer {
  private readonly view: Int32Array;
  private static readonly TIMEOUT_MS = 1_000;

  constructor(sharedBuffer: SharedArrayBuffer) {
    this.view = new Int32Array(sharedBuffer);
  }

  public push(val: number): boolean {
    // Acquire lock using Atomic Compare-And-Swap (CAS)
    while (Atomics.compareExchange(this.view, BufferOffset.Lock, LockState.Unlocked, LockState.Locked) !== LockState.Unlocked) {
      // Futex wait: sleep until notified or timeout expires
      const waitStatus = Atomics.wait(this.view, BufferOffset.Lock, LockState.Locked, WorkerRingBuffer.TIMEOUT_MS);
      if (waitStatus === 'timed-out') {
        return false;
      }
    }

    try {
      // Safe write protected by atomic memory barrier
      Atomics.store(this.view, BufferOffset.Data, val);
      Atomics.store(this.view, BufferOffset.State, 1);
      return true;
    } finally {
      // Release lock and wake up one waiting consumer thread
      Atomics.store(this.view, BufferOffset.Lock, LockState.Unlocked);
      Atomics.notify(this.view, BufferOffset.Lock, 1);
    }
  }

  public pop(): number | null {
    while (Atomics.compareExchange(this.view, BufferOffset.Lock, LockState.Unlocked, LockState.Locked) !== LockState.Unlocked) {
      const waitStatus = Atomics.wait(this.view, BufferOffset.Lock, LockState.Locked, WorkerRingBuffer.TIMEOUT_MS);
      if (waitStatus === 'timed-out') {
        return null;
      }
    }

    try {
      if (Atomics.load(this.view, BufferOffset.State) === 0) {
        return null;
      }
      const value = Atomics.load(this.view, BufferOffset.Data);
      Atomics.store(this.view, BufferOffset.State, 0);
      return value;
    } finally {
      Atomics.store(this.view, BufferOffset.Lock, LockState.Unlocked);
      Atomics.notify(this.view, BufferOffset.Lock, 1);
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Native Worker Concurrency & Shared Memory Barrier Standard

Bun 1.2 Native Worker Concurrency & Shared Memory Barrier Standard defines an industrial-grade behavioral standard for backend engineering. Bun 1.2 executes native Web Workers with direct access to SharedArrayBuffer instances, enabling sub-millisecond inter-thread messaging. Unfenced mutations and unsynchronized reads across worker boundaries cause torn writes, cache incoherence, and process-terminating segment faults under heavy I/O pressure. This standard mandates explicit memory fences, typed layouts, and Atomics synchronization across all multi-threaded worker pipelines. 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: Unsynchronized SharedArrayBuffer Mutation and Unfenced Worker Ring Buffer R/W Access 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 DriftUnsynchronized SharedArrayBuffer Mutation and Unfenced Worker Ring Buffer R/W AccessCritical
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 manipulate SharedArrayBuffer data structures through the global Atomics API (e.g., Atomics.load, Atomics.store, Atomics.compareExchange, Atomics.add).

Engineers MUST ALWAYS manipulate SharedArrayBuffer data structures through the global Atomics API (e.g., Atomics.load, Atomics.store, Atomics.compareExchange, Atomics.add).

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 read or write to shared typed array slots using direct index assignments (e.g., `view[0] = 1`) across multi-threaded worker boundaries.

Engineers MUST NOT read or write to shared typed array slots using direct index assignments (e.g., `view[0] = 1`) across multi-threaded worker 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.
3

Engineers MUST use `Atomics.wait` and `Atomics.notify` with explicit millisecond timeouts to coordinate producer-consumer transitions instead of hot CPU spin-wait loops.

Engineers MUST use `Atomics.wait` and `Atomics.notify` with explicit millisecond timeouts to coordinate producer-consumer transitions instead of hot CPU spin-wait 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.
4

Services MUST define rigid memory layout constants with byte-aligned offsets when carving out control blocks, payload headers, and circular buffers in a single SharedArrayBuffer.

Services MUST define rigid memory layout constants with byte-aligned offsets when carving out control blocks, payload headers, and circular buffers in a single 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.
5

Workers MUST isolate incoming SharedArrayBuffer structures from mutation until lock acquisition is confirmed via atomic test-and-set or compare-and-swap (CAS) routines.

Workers MUST isolate incoming SharedArrayBuffer structures from mutation until lock acquisition is confirmed via atomic test-and-set or compare-and-swap (CAS) routines.

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

Code SHOULD verify that `crossOriginIsolated` semantics and memory allocations are pre-allocated at service initialization to prevent runtime allocation failures under load.

Code SHOULD verify that `crossOriginIsolated` semantics and memory allocations are pre-allocated at service initialization to prevent runtime allocation failures under load.

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 Concurrency & Shared Memory Barrier Standard critical for AI coding assistants?

Bun 1.2 executes native Web Workers with direct access to SharedArrayBuffer instances, enabling sub-millisecond inter-thread messaging. Unfenced mutations and unsynchronized reads across worker boundaries cause torn writes, cache incoherence, and process-terminating segment faults under heavy I/O pressure. This standard mandates explicit memory fences, typed layouts, and Atomics synchronization across all multi-threaded worker pipelines. 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 (Unsynchronized SharedArrayBuffer Mutation and Unfenced Worker Ring Buffer R/W Access) 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