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

Bun 1.2 Worker SharedArrayBuffer Zero-Copy Atomic Mutation Barrier

Enforces strict memory barriers and atomic state transitions when mutating SharedArrayBuffer instances across Bun 1.2 isolated Worker threads. Guarantees zero-copy pipeline integrity by prohibiting non-atomic writes to shared regions while readers are concurrently attached, avoiding torn reads, cache incoherency, and silent data corruption under high-throughput parallel execution.

Prohibited Anti-Pattern: Unsynchronized Raw TypedArray Mutations on Cross-Thread SharedArrayBuffer Instances

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker SharedArrayBuffer Zero-Copy Atomic Mutation Barrier - Enforces strict memory barriers and atomic state transitions when mutating SharedArrayBuffer instances across Bun 1.2 isolated Worker threads. Guarantees zero-copy pipeline integrity by prohibiting non-atomic writes to shared regions while readers are concurrently attached, avoiding torn reads, cache incoherency, and silent data corruption under high-throughput parallel execution.
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-atomic-barrier"
---

# Bun 1.2 Worker SharedArrayBuffer Zero-Copy Atomic Mutation Barrier

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Raw TypedArray Mutations on Cross-Thread SharedArrayBuffer Instances

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-copy concurrency invariants in Bun 1.2 runtime clusters. Mandate explicit memory layout partitioning, atomic state flags (Atomics.wait, Atomics.notify, Atomics.compareExchange), and hardware-level memory barriers on all SharedArrayBuffer allocations shared between main threads and Bun Worker instances. Reject all unsynchronized TypedArray mutations, non-atomic status checks, and data-race hazards.

## Strict Guidelines
- Engineers MUST ALWAYS allocate a dedicated header partition at offset 0 of any SharedArrayBuffer containing Int32Array control words for atomic synchronization (e.g., lock state, sequence generation, committed byte length).
- Engineers MUST NOT mutate raw TypedArray views (Uint8Array, Float64Array) backing a SharedArrayBuffer without first acquiring an explicit atomic lock or advancing a ring-buffer commit cursor via Atomics.compareExchange or Atomics.store.
- Worker pipelines MUST use Atomics.wait (in dedicated Worker threads only) and Atomics.notify to transition buffer lifecycle states (READY, PROCESSING, COMMITTED, CONSUMED) rather than relying on spin-locks or uncoordinated postMessage signals.
- Main threads MUST NEVER invoke Atomics.wait as it will block the Bun event loop; the main thread MUST either poll non-blockingly via Atomics.load or delegate synchronous coordination entirely to dedicated worker-to-worker barriers.
- Engineers MUST explicitly pass SharedArrayBuffer instances through postMessage transfer semantics without structural cloning overhead, keeping memory allocations stable across the worker pool lifecycle.

## Bad vs Good Implementations
### Zero-Copy Parallel Buffer Mutation with Atomic State Barriers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing directly to Uint8Array over a SharedArrayBuffer while another worker is reading or writing causes data races, torn reads, and cache incoherency. Relying on asynchronous postMessage for sequential ordering fails to provide atomic memory barriers at the microsecond level under heavy saturation.
```typescript
// ANTI-PATTERN: Data race hazard - Unsynchronized mutation of shared memory
import { Worker } from "bun";

const BUFFER_SIZE = 1024 * 1024;
const sab = new SharedArrayBuffer(BUFFER_SIZE);
const dataView = new Uint8Array(sab);

const worker = new Worker(new URL("./processor.ts", import.meta.url));
worker.postMessage({ buffer: sab });

// Main thread blindly writes payload without checking worker state or acquiring a lock
setInterval(() => {
  for (let i = 0; i < 1000; i++) {
    dataView[i] = Math.floor(Math.random() * 256); // Torn write / concurrent read corrupts data
  }
  worker.postMessage({ status: "UPDATE_AVAILABLE" });
}, 10);

// processor.ts: (worker reads directly without synchronizing on memory barrier)
// dataView.slice(0, 1000) causes reading torn/partial memory
```

#### Production Standard (Correct)
> **Standard**: Implements an isolated control header holding atomic memory flags. The writer acquires the mutex via Atomics.compareExchange before executing zero-copy memory copies into the shared segment. It updates the sequence and length counter with release semantics (Atomics.store) and unblocks waiting workers via Atomics.notify, ensuring guaranteed memory visibility without torn reads.
```typescript
// PRODUCTION STANDARD: Explicit Header Partitioning + Atomic Sequence Barrier
import { Worker } from "bun";

const HEADER_BYTES = 64; // 16 Int32 slots reserved for atomic control words
const DATA_BYTES = 1024 * 1024;
const sab = new SharedArrayBuffer(HEADER_BYTES + DATA_BYTES);

// Index 0: Lock Status (0 = FREE, 1 = ACQUIRED)
// Index 1: Sequence / Generation Counter
// Index 2: Byte Payload Length
const controlView = new Int32Array(sab, 0, HEADER_BYTES / Int32Array.BYTES_PER_ELEMENT);
const payloadView = new Uint8Array(sab, HEADER_BYTES, DATA_BYTES);

const worker = new Worker(new URL("./processor.ts", import.meta.url));
worker.postMessage({ buffer: sab, headerOffset: 0, payloadOffset: HEADER_BYTES });

function writePayloadSafely(data: Uint8Array): boolean {
  if (data.byteLength > DATA_BYTES) throw new RangeError("Payload exceeds shared partition");

  // Try to acquire the atomic lock (transition 0 -> 1)
  if (Atomics.compareExchange(controlView, 0, 0, 1) !== 0) {
    return false; // Lock contention, caller can back off or queue
  }

  try {
    payloadView.set(data, 0);
    Atomics.store(controlView, 2, data.byteLength); // Publish payload length
    const nextSeq = Atomics.add(controlView, 1, 1) + 1; // Atomic barrier sequence bump
    Atomics.notify(controlView, 1, 1); // Wake waiting worker thread
    return true;
  } finally {
    // Release lock (transition 1 -> 0)
    Atomics.store(controlView, 0, 0);
  }
}
```

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 Zero-Copy Atomic Mutation Barrier

Bun 1.2 Worker SharedArrayBuffer Zero-Copy Atomic Mutation Barrier defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory barriers and atomic state transitions when mutating SharedArrayBuffer instances across Bun 1.2 isolated Worker threads. Guarantees zero-copy pipeline integrity by prohibiting non-atomic writes to shared regions while readers are concurrently attached, avoiding torn reads, cache incoherency, and silent data corruption under high-throughput parallel execution. 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 Raw TypedArray Mutations on Cross-Thread SharedArrayBuffer Instances 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 Raw TypedArray Mutations on Cross-Thread SharedArrayBuffer InstancesCritical
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 allocate a dedicated header partition at offset 0 of any SharedArrayBuffer containing Int32Array control words for atomic synchronization (e.g., lock state, sequence generation, committed byte length).

Engineers MUST ALWAYS allocate a dedicated header partition at offset 0 of any SharedArrayBuffer containing Int32Array control words for atomic synchronization (e.g., lock state, sequence generation, committed byte length).

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 raw TypedArray views (Uint8Array, Float64Array) backing a SharedArrayBuffer without first acquiring an explicit atomic lock or advancing a ring-buffer commit cursor via Atomics.compareExchange or Atomics.store.

Engineers MUST NOT mutate raw TypedArray views (Uint8Array, Float64Array) backing a SharedArrayBuffer without first acquiring an explicit atomic lock or advancing a ring-buffer commit cursor via Atomics.compareExchange or 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.
3

Worker pipelines MUST use Atomics.wait (in dedicated Worker threads only) and Atomics.notify to transition buffer lifecycle states (READY, PROCESSING, COMMITTED, CONSUMED) rather than relying on spin-locks or uncoordinated postMessage signals.

Worker pipelines MUST use Atomics.wait (in dedicated Worker threads only) and Atomics.notify to transition buffer lifecycle states (READY, PROCESSING, COMMITTED, CONSUMED) rather than relying on spin-locks or uncoordinated postMessage signals.

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

Main threads MUST NEVER invoke Atomics.wait as it will block the Bun event loop

Main threads MUST NEVER invoke Atomics.wait as it will block the Bun event loop; the main thread MUST either poll non-blockingly via Atomics.load or delegate synchronous coordination entirely to dedicated worker-to-worker barriers.

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

Engineers MUST explicitly pass SharedArrayBuffer instances through postMessage transfer semantics without structural cloning overhead, keeping memory allocations stable across the worker pool lifecycle.

Engineers MUST explicitly pass SharedArrayBuffer instances through postMessage transfer semantics without structural cloning overhead, keeping memory allocations stable across the worker pool lifecycle.

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 Zero-Copy Atomic Mutation Barrier critical for AI coding assistants?

Enforces strict memory barriers and atomic state transitions when mutating SharedArrayBuffer instances across Bun 1.2 isolated Worker threads. Guarantees zero-copy pipeline integrity by prohibiting non-atomic writes to shared regions while readers are concurrently attached, avoiding torn reads, cache incoherency, and silent data corruption under high-throughput parallel execution. 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 Raw TypedArray Mutations on Cross-Thread SharedArrayBuffer Instances) 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