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

Data-Race-Free Worker Synchronization via SharedArrayBuffer and Atomics in Bun 1.2

Enforces deterministic, zero-copy inter-worker state synchronization in Bun 1.2 using SharedArrayBuffer and standard Atomics operations. Prevents silent data races, torn reads/writes, and IPC serialization throughput collapse by mandating atomic memory barriers and explicit ring-buffer queue synchronization patterns.

Prohibited Anti-Pattern: Unsynchronized SharedArrayBuffer Mutations and Structured Cloning Serialization Bottlenecks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Data-Race-Free Worker Synchronization via SharedArrayBuffer and Atomics in Bun 1.2 - Enforces deterministic, zero-copy inter-worker state synchronization in Bun 1.2 using SharedArrayBuffer and standard Atomics operations. Prevents silent data races, torn reads/writes, and IPC serialization throughput collapse by mandating atomic memory barriers and explicit ring-buffer queue synchronization patterns.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/**/cluster/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-atomics"
---

# Data-Race-Free Worker Synchronization via SharedArrayBuffer and Atomics in Bun 1.2

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized SharedArrayBuffer Mutations and Structured Cloning Serialization Bottlenecks

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Multi-Worker SharedArrayBuffer Atomic State Synchronization. Mandate invariants that eliminate data races, eliminate postMessage serialization overhead for high-frequency IPC, and ensure deterministic atomic coordination across Bun worker threads.

## Strict Guidelines
- Engineers MUST ALWAYS access SharedArrayBuffer memory backed by TypedArrays exclusively through the Atomics API (e.g., Atomics.load, Atomics.store, Atomics.add, Atomics.compareExchange) for any mutable shared state.
- Engineers MUST NOT mutate or read SharedArrayBuffer typed arrays via standard array indexing (e.g., buffer[0] = 1) across worker boundaries, as this induces non-deterministic torn reads/writes and memory reordering bugs.
- Engineers MUST use Atomics.wait and Atomics.notify exclusively inside dedicated Worker threads (never on the main event loop thread) to prevent unrecoverable event loop deadlocks.
- Code MUST employ fixed-layout memory offsets and explicit byte alignments (e.g., Int32Array aligned to 4-byte boundaries) when slicing SharedArrayBuffer instances into distinct queues or control blocks.
- Services MUST prefer passing SharedArrayBuffer instances at worker initialization over streaming continuous payloads via Worker.postMessage to eliminate V8/JSC structured-clone serialization overhead in high-throughput workloads.

## Bad vs Good Implementations
### High-Throughput State Counter & Ring Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct indexing of a SharedArrayBuffer without Atomics leads to compiler/CPU instruction reordering and lost updates under parallel multi-core execution. Furthermore, executing Atomics.wait on the primary execution context halts the Bun event loop.
```typescript
// Main or Worker thread attempting shared state via raw typed array operations
const sharedBuffer = new SharedArrayBuffer(1024);
const view = new Int32Array(sharedBuffer);

// Anti-pattern: Unsynchronized direct indexing causes race conditions and torn reads
function incrementTaskCount(workerId: number): void {
  const current = view[0];
  // Memory reordering and concurrent writes cause lost updates across Bun workers
  view[0] = current + 1;
  view[1] = workerId; // Torn write: another worker might read view[0] with stale view[1]
}

// Anti-pattern: Blocking the main thread event loop
if (typeof window === "undefined" && !process.env.IS_WORKER) {
  Atomics.wait(view, 0, 0); // Fatal: Atomics.wait throws on main thread in standard runtimes
}
```

#### Production Standard (Correct)
> **Standard**: All mutations and state checks utilize Atomics.add and Atomics.compareExchange, guaranteeing that CPU-level memory barriers are enforced. This eliminates torn reads and race conditions across multiple Bun worker processes while enabling zero-copy sharing.
```typescript
// Synchronized, data-race-free coordination using Bun 1.2 compatible TypedArray + Atomics
const STATE_INDEX = 0;
const WORKER_LOCK_INDEX = 1;

export class WorkerSyncState {
  private readonly view: Int32Array;

  constructor(private readonly sharedBuffer: SharedArrayBuffer) {
    // Ensure 4-byte alignment guarantee for Int32Array
    this.view = new Int32Array(this.sharedBuffer, 0, 2);
  }

  public incrementCounter(): number {
    // Atomic addition guarantees cache coherence and serializable ordering
    return Atomics.add(this.view, STATE_INDEX, 1);
  }

  public acquireLock(workerId: number): boolean {
    // Spin-wait or atomic compare-and-swap for mutual exclusion
    return Atomics.compareExchange(this.view, WORKER_LOCK_INDEX, 0, workerId) === 0;
  }

  public releaseLock(workerId: number): void {
    const previous = Atomics.compareExchange(this.view, WORKER_LOCK_INDEX, workerId, 0);
    if (previous === workerId) {
      Atomics.notify(this.view, WORKER_LOCK_INDEX, 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: Data-Race-Free Worker Synchronization via SharedArrayBuffer and Atomics in Bun 1.2

Data-Race-Free Worker Synchronization via SharedArrayBuffer and Atomics in Bun 1.2 defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic, zero-copy inter-worker state synchronization in Bun 1.2 using SharedArrayBuffer and standard Atomics operations. Prevents silent data races, torn reads/writes, and IPC serialization throughput collapse by mandating atomic memory barriers and explicit ring-buffer queue synchronization patterns. 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 Mutations and Structured Cloning Serialization Bottlenecks 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 Mutations and Structured Cloning Serialization BottlenecksCritical
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 access SharedArrayBuffer memory backed by TypedArrays exclusively through the Atomics API (e.g., Atomics.load, Atomics.store, Atomics.add, Atomics.compareExchange) for any mutable shared state.

Engineers MUST ALWAYS access SharedArrayBuffer memory backed by TypedArrays exclusively through the Atomics API (e.g., Atomics.load, Atomics.store, Atomics.add, Atomics.compareExchange) for any mutable shared state.

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 mutate or read SharedArrayBuffer typed arrays via standard array indexing (e.g., buffer[0] = 1) across worker boundaries, as this induces non-deterministic torn reads/writes and memory reordering bugs.

Engineers MUST NOT mutate or read SharedArrayBuffer typed arrays via standard array indexing (e.g., buffer[0] = 1) across worker boundaries, as this induces non-deterministic torn reads/writes and memory reordering bugs.

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 exclusively inside dedicated Worker threads (never on the main event loop thread) to prevent unrecoverable event loop deadlocks.

Engineers MUST use Atomics.wait and Atomics.notify exclusively inside dedicated Worker threads (never on the main event loop thread) to prevent unrecoverable event loop deadlocks.

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

Code MUST employ fixed-layout memory offsets and explicit byte alignments (e.g., Int32Array aligned to 4-byte boundaries) when slicing SharedArrayBuffer instances into distinct queues or control blocks.

Code MUST employ fixed-layout memory offsets and explicit byte alignments (e.g., Int32Array aligned to 4-byte boundaries) when slicing SharedArrayBuffer instances into distinct queues or control blocks.

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

Services MUST prefer passing SharedArrayBuffer instances at worker initialization over streaming continuous payloads via Worker.postMessage to eliminate V8/JSC structured-clone serialization overhead in high-throughput workloads.

Services MUST prefer passing SharedArrayBuffer instances at worker initialization over streaming continuous payloads via Worker.postMessage to eliminate V8/JSC structured-clone serialization overhead in high-throughput workloads.

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 Data-Race-Free Worker Synchronization via SharedArrayBuffer and Atomics in Bun 1.2 critical for AI coding assistants?

Enforces deterministic, zero-copy inter-worker state synchronization in Bun 1.2 using SharedArrayBuffer and standard Atomics operations. Prevents silent data races, torn reads/writes, and IPC serialization throughput collapse by mandating atomic memory barriers and explicit ring-buffer queue synchronization patterns. 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 Mutations and Structured Cloning Serialization Bottlenecks) 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

Data-Race-Free