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

Bun 1.2 Atomics & SharedArrayBuffer Inter-Worker Concurrency Standard

Enforces deterministic, lock-free inter-worker synchronization using SharedArrayBuffer and the Atomics API within Bun 1.2 runtimes. Prevents main event-loop stalls, data races, and torn reads/writes across native Worker threads under heavy compute loads. Mandates explicit memory barriers, aligned typed views, and non-blocking wait/notify patterns on main threads.

Prohibited Anti-Pattern: Unsynchronized SharedArrayBuffer mutations and blocking Atomics.wait on the main worker event loop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Atomics & SharedArrayBuffer Inter-Worker Concurrency Standard - Enforces deterministic, lock-free inter-worker synchronization using SharedArrayBuffer and the Atomics API within Bun 1.2 runtimes. Prevents main event-loop stalls, data races, and torn reads/writes across native Worker threads under heavy compute loads. Mandates explicit memory barriers, aligned typed views, and non-blocking wait/notify patterns on main threads.
globs: src/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-atomics-sharedarraybuffer-concurrency-standard"
---

# Bun 1.2 Atomics & SharedArrayBuffer Inter-Worker Concurrency Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized SharedArrayBuffer mutations and blocking Atomics.wait on the main worker event loop

## System Constraints
You are a Principal Systems Architect enforcing Bun 1.2 Atomics & SharedArrayBuffer Inter-Worker Concurrency Standards. Mandate lock-free communication primitives, strict memory layout alignment, non-blocking notification protocols, and rigorous isolation between compute workers and event-driven I/O contexts.

## Strict Guidelines
- Engineers MUST NEVER execute Atomics.wait on the primary Bun runtime thread, as it halts the libuv/JSC event loop and drops incoming network connections.
- Engineers MUST ALWAYS access SharedArrayBuffer allocations via deterministic TypedArray views (Int32Array or BigInt64Array) using explicit Atomics operations (load, store, exchange, compareExchange, add, sub) rather than standard property assignment.
- Worker communication MUST use single-producer/single-consumer (SPSC) or multi-producer/single-consumer (MPSC) lock-free ring buffers with explicit read/write tail indices updated via Atomics.store with release semantics.
- Code MUST verify cross-thread buffer alignment and explicit byteOffsets when constructing Int32Array (4-byte alignment) or BigInt64Array (8-byte alignment) over raw SharedArrayBuffer memory.
- Workers MUST utilize Atomics.waitAsync or structured Atomics.wait/Atomics.notify with defined finite timeouts to eliminate thread starvation and unrecoverable deadlocks.

## Bad vs Good Implementations
### Lock-Free Ring Buffer State Synchronization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct indexing into a SharedArrayBuffer bypasses memory fences, risking torn writes and processor reordering across CPU cores. Spin-waiting on the main thread starves Bun's event loop, preventing HTTP I/O from being serviced.
```typescript
import { Worker } from 'bun';

const sharedBuffer = new SharedArrayBuffer(1024);
const view = new Uint8Array(sharedBuffer);

// ANTI-PATTERN: Direct mutation causes torn reads/writes across worker threads
// Main thread unsafely assumes updates are sequential without memory barriers
export function produceWork(jobId: number): void {
  view[0] = jobId; // Non-atomic write: subject to CPU reordering and cache-coherency delays
}

export function blockUntilProcessed(): void {
  // ANTI-PATTERN: Spin-waiting on main thread consumes 100% CPU and starves the event loop
  while (view[0] !== 0) {
    /* busy spin */
  }
}
```

#### Production Standard (Correct)
> **Standard**: Employs Atomics.compareExchange for lock-free state transitions, explicit 4-byte aligned Int32Array views to prevent torn updates, and Atomics.waitAsync to prevent blocking Bun's primary execution thread while synchronizing with compute workers.
```typescript
import { Worker } from 'bun';

// PRODUCTION FIX: Explicit 4-byte aligned Int32Array view over SharedArrayBuffer
const STATE_INDEX = 0;
const DATA_INDEX = 1;
const STATUS_IDLE = 0;
const STATUS_READY = 1;

// Allocate buffer: 4-byte boundary for Int32Array
const sharedBuffer = new SharedArrayBuffer(8);
const stateView = new Int32Array(sharedBuffer);

export function dispatchWork(jobId: number): boolean {
  // Ensure worker is idle before acquiring slot using atomic compare-and-exchange
  const prev = Atomics.compareExchange(stateView, STATE_INDEX, STATUS_IDLE, STATUS_READY);
  if (prev !== STATUS_IDLE) {
    return false; // Queue saturated, defer without blocking
  }

  Atomics.store(stateView, DATA_INDEX, jobId);
  // Wake up at most 1 waiting worker thread safely
  Atomics.notify(stateView, STATE_INDEX, 1);
  return true;
}

export async function awaitJobAsync(timeoutMs = 5000): Promise<boolean> {
  // PRODUCTION FIX: Non-blocking Atomics.waitAsync safe for the primary event loop
  const result = Atomics.waitAsync(stateView, STATE_INDEX, STATUS_READY, timeoutMs);
  if (result.async) {
    const outcome = await result.value;
    return outcome !== 'timed-out';
  }
  return result.value !== 'timed-out';
}
```

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

Bun 1.2 Atomics & SharedArrayBuffer Inter-Worker Concurrency Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic, lock-free inter-worker synchronization using SharedArrayBuffer and the Atomics API within Bun 1.2 runtimes. Prevents main event-loop stalls, data races, and torn reads/writes across native Worker threads under heavy compute loads. Mandates explicit memory barriers, aligned typed views, and non-blocking wait/notify patterns on main threads. 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 blocking Atomics.wait on the main worker event loop 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 blocking Atomics.wait on the main worker event loopCritical
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 NEVER execute Atomics.wait on the primary Bun runtime thread, as it halts the libuv/JSC event loop and drops incoming network connections.

Engineers MUST NEVER execute Atomics.wait on the primary Bun runtime thread, as it halts the libuv/JSC event loop and drops incoming network connections.

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 ALWAYS access SharedArrayBuffer allocations via deterministic TypedArray views (Int32Array or BigInt64Array) using explicit Atomics operations (load, store, exchange, compareExchange, add, sub) rather than standard property assignment.

Engineers MUST ALWAYS access SharedArrayBuffer allocations via deterministic TypedArray views (Int32Array or BigInt64Array) using explicit Atomics operations (load, store, exchange, compareExchange, add, sub) rather than standard property assignment.

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

Worker communication MUST use single-producer/single-consumer (SPSC) or multi-producer/single-consumer (MPSC) lock-free ring buffers with explicit read/write tail indices updated via Atomics.store with release semantics.

Worker communication MUST use single-producer/single-consumer (SPSC) or multi-producer/single-consumer (MPSC) lock-free ring buffers with explicit read/write tail indices updated via Atomics.store with release semantics.

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 verify cross-thread buffer alignment and explicit byteOffsets when constructing Int32Array (4-byte alignment) or BigInt64Array (8-byte alignment) over raw SharedArrayBuffer memory.

Code MUST verify cross-thread buffer alignment and explicit byteOffsets when constructing Int32Array (4-byte alignment) or BigInt64Array (8-byte alignment) over raw SharedArrayBuffer memory.

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 utilize Atomics.waitAsync or structured Atomics.wait/Atomics.notify with defined finite timeouts to eliminate thread starvation and unrecoverable deadlocks.

Workers MUST utilize Atomics.waitAsync or structured Atomics.wait/Atomics.notify with defined finite timeouts to eliminate thread starvation and unrecoverable 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.
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 Atomics & SharedArrayBuffer Inter-Worker Concurrency Standard critical for AI coding assistants?

Enforces deterministic, lock-free inter-worker synchronization using SharedArrayBuffer and the Atomics API within Bun 1.2 runtimes. Prevents main event-loop stalls, data races, and torn reads/writes across native Worker threads under heavy compute loads. Mandates explicit memory barriers, aligned typed views, and non-blocking wait/notify patterns on main threads. 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 blocking Atomics.wait on the main worker event loop) 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