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

Bun 1.2 Worker SharedArrayBuffer Mutex and Memory Visibility Standard

Enforces strict memory ordering and zero-spin synchronization for parallel computational pipelines communicating via SharedArrayBuffer in Bun 1.2 worker threads. Prevents thread deadlocks, cache incoherence, CPU core saturation, and data corruption caused by unsynchronized buffer reads and naive spinlocks.

Prohibited Anti-Pattern: Unsynchronized Direct TypedArray Mutation and CPU-Saturating Spinlocks Across Worker Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker SharedArrayBuffer Mutex and Memory Visibility Standard - Enforces strict memory ordering and zero-spin synchronization for parallel computational pipelines communicating via SharedArrayBuffer in Bun 1.2 worker threads. Prevents thread deadlocks, cache incoherence, CPU core saturation, and data corruption caused by unsynchronized buffer reads and naive spinlocks.
globs: src/**/*.{ts,js}, workers/**/*.{ts,js}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-mutex-synchronization-standard"
---

# Bun 1.2 Worker SharedArrayBuffer Mutex and Memory Visibility Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Direct TypedArray Mutation and CPU-Saturating Spinlocks Across Worker Threads

## System Constraints
You are a Principal Systems Engineer enforcing strict multithreaded synchronization invariants in Bun 1.2 runtimes. Bun worker threads run on distinct OS threads; passing SharedArrayBuffer instances without explicit Atomics and futex-based synchronization triggers silent memory corruption, pipeline desynchronization, and CPU starvation. Mandate explicit memory fences, Atomics.wait/notify patterns, and reject direct TypedArray mutation or busy-wait spinlocks across worker boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS synchronize SharedArrayBuffer access using `Atomics` primitives (`Atomics.load`, `Atomics.store`, `Atomics.compareExchange`, `Atomics.wait`, `Atomics.notify`) instead of direct TypedArray indexing across thread boundaries.
- Engineers MUST NOT implement busy-wait loops (`while (flag[0] === 1) {}`) across worker threads; use `Atomics.wait()` inside Worker contexts to suspend execution at the OS level until signaled by `Atomics.notify()`.
- Code SHOULD enforce dedicated synchronization headers (e.g., an Int32Array at offset 0 of the SharedArrayBuffer) containing explicit state flags: UNLOCKED (0), LOCKED (1), and WAITING (2).
- Services MUST verify that `Atomics.wait()` is invoked ONLY within dedicated worker threads and NEVER on the main event-loop thread, where it throws a TypeError and stalls the Bun HTTP engine.
- Components NEVER rely on implicit memory ordering; all critical section mutations must be flanked by explicit acquire/release atomic fences via `Atomics.compareExchange` and `Atomics.store`.

## Bad vs Good Implementations
### Unsynchronized SharedArrayBuffer Mutation vs. Atomics Futex Mutex Lock

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct indexing on a SharedArrayBuffer bypasses compiler and CPU memory barriers, causing out-of-order execution and stale cache-line reads across OS threads. Furthermore, the while-loop spinlock consumes 100% of an OS thread's core, causing scheduler priority inversion and potential deadlocks in high-throughput pipelines.
```typescript
// BAD: Direct mutation and busy-spin loop across Bun worker threads
export class WorkerPipeline {
  private buffer: SharedArrayBuffer;
  private view: Int32Array;

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

  processChunk(chunkId: number, data: number): void {
    // ANTI-PATTERN: Busy-wait spinlock saturates 100% CPU on host core
    while (this.view[0] === 1) {
      // Burns CPU cycles, causes cache line contention
    }

    // ANTI-PATTERN: Unsynchronized write without memory barriers
    this.view[0] = 1; // Mark busy (non-atomic, susceptible to store-reordering)
    this.view[chunkId + 1] = data;
    this.view[0] = 0; // Release (other threads may observe stale data due to CPU caches)
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements a 3-state futex mutex (UNLOCKED, LOCKED, CONTENDED) utilizing Atomics.compareExchange and Atomics.wait. This guarantees OS-level sleep states during lock contention—preventing CPU exhaustion—and enforces hardware memory barriers ensuring all writes inside the critical section are globally visible to other worker threads.
```typescript
// GOOD: Production-grade Futex-based Mutex with Atomics fences for Bun workers
const UNLOCKED = 0;
const LOCKED = 1;
const CONTENDED = 2;

export class WorkerMutex {
  private lockView: Int32Array;

  constructor(sharedBuffer: SharedArrayBuffer, lockOffsetIndex: number = 0) {
    // Int32Array is required for Atomics.wait/notify operations
    this.lockView = new Int32Array(sharedBuffer, lockOffsetIndex * Int32Array.BYTES_PER_ELEMENT, 1);
  }

  lock(): void {
    // Fast path: Attempt to transition directly from UNLOCKED to LOCKED
    if (Atomics.compareExchange(this.lockView, 0, UNLOCKED, LOCKED) === UNLOCKED) {
      return;
    }

    // Slow path: Wait via OS futex without spinning CPU
    do {
      // Mark lock as CONTENDED if not already set, or ensure state is acknowledged
      if (this.lockView[0] === CONTENDED || Atomics.compareExchange(this.lockView, 0, LOCKED, CONTENDED) !== UNLOCKED) {
        // Atomics.wait blocks thread until Atomics.notify wakes it, consuming 0% CPU
        Atomics.wait(this.lockView, 0, CONTENDED);
      }
    } while (Atomics.compareExchange(this.lockView, 0, UNLOCKED, CONTENDED) !== UNLOCKED);
  }

  unlock(): void {
    // Transition back to UNLOCKED with memory barrier fence
    const prev = Atomics.exchange(this.lockView, 0, UNLOCKED);
    if (prev === CONTENDED) {
      // Wake up exactly one waiting thread
      Atomics.notify(this.lockView, 0, 1);
    }
  }

  runCriticalSection<T>(fn: () => T): T {
    this.lock();
    try {
      return fn();
    } finally {
      this.unlock();
    }
  }
}
```

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 Worker SharedArrayBuffer Mutex and Memory Visibility Standard

Bun 1.2 Worker SharedArrayBuffer Mutex and Memory Visibility Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory ordering and zero-spin synchronization for parallel computational pipelines communicating via SharedArrayBuffer in Bun 1.2 worker threads. Prevents thread deadlocks, cache incoherence, CPU core saturation, and data corruption caused by unsynchronized buffer reads and naive spinlocks. 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 Direct TypedArray Mutation and CPU-Saturating Spinlocks Across Worker Threads 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 Direct TypedArray Mutation and CPU-Saturating Spinlocks Across Worker ThreadsCritical
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 synchronize SharedArrayBuffer access using `Atomics` primitives (`Atomics.load`, `Atomics.store`, `Atomics.compareExchange`, `Atomics.wait`, `Atomics.notify`) instead of direct TypedArray indexing across thread boundaries.

Engineers MUST ALWAYS synchronize SharedArrayBuffer access using `Atomics` primitives (`Atomics.load`, `Atomics.store`, `Atomics.compareExchange`, `Atomics.wait`, `Atomics.notify`) instead of direct TypedArray indexing 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 implement busy-wait loops (`while (flag[0] === 1) {}`) across worker threads

Engineers MUST NOT implement busy-wait loops (`while (flag[0] === 1) {}`) across worker threads; use `Atomics.wait()` inside Worker contexts to suspend execution at the OS level until signaled by `Atomics.notify()`.

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 SHOULD enforce dedicated synchronization headers (e.g., an Int32Array at offset 0 of the SharedArrayBuffer) containing explicit state flags

Code SHOULD enforce dedicated synchronization headers (e.g., an Int32Array at offset 0 of the SharedArrayBuffer) containing explicit state flags: UNLOCKED (0), LOCKED (1), and WAITING (2).

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 verify that `Atomics.wait()` is invoked ONLY within dedicated worker threads and NEVER on the main event-loop thread, where it throws a TypeError and stalls the Bun HTTP engine.

Services MUST verify that `Atomics.wait()` is invoked ONLY within dedicated worker threads and NEVER on the main event-loop thread, where it throws a TypeError and stalls the Bun HTTP engine.

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 implicit memory ordering

Components NEVER rely on implicit memory ordering; all critical section mutations must be flanked by explicit acquire/release atomic fences via `Atomics.compareExchange` and `Atomics.store`.

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 Worker SharedArrayBuffer Mutex and Memory Visibility Standard critical for AI coding assistants?

Enforces strict memory ordering and zero-spin synchronization for parallel computational pipelines communicating via SharedArrayBuffer in Bun 1.2 worker threads. Prevents thread deadlocks, cache incoherence, CPU core saturation, and data corruption caused by unsynchronized buffer reads and naive spinlocks. 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 Direct TypedArray Mutation and CPU-Saturating Spinlocks Across Worker Threads) 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