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

Bun 1.2 Native Worker SharedArrayBuffer Concurrency Fencing & Bounded Synchronization

Enforces strict synchronization fences and bounded timeouts on Atomics operations over SharedArrayBuffer memory segments between Bun 1.2 main processes and native Worker threads. Prevents event-loop thread starvation, unbounded blocking, and uncoordinated shared memory corruptions in high-throughput compute services.

Prohibited Anti-Pattern: Unbounded Atomics.wait Blocking and Unsynchronized Direct SharedArrayBuffer Mutations Across Worker Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Worker SharedArrayBuffer Concurrency Fencing & Bounded Synchronization - Enforces strict synchronization fences and bounded timeouts on Atomics operations over SharedArrayBuffer memory segments between Bun 1.2 main processes and native Worker threads. Prevents event-loop thread starvation, unbounded blocking, and uncoordinated shared memory corruptions in high-throughput compute services.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/services/**/*.ts, src/lib/concurrency/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-concurrency-fencing"
---

# Bun 1.2 Native Worker SharedArrayBuffer Concurrency Fencing & Bounded Synchronization

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Atomics.wait Blocking and Unsynchronized Direct SharedArrayBuffer Mutations Across Worker Threads

## System Constraints
You are a Principal Software Architect enforcing production-grade concurrency safety in Bun 1.2. Bun's native Worker implementation maps directly to operating system threads. You must ensure that SharedArrayBuffer interactions employ strict memory fencing using Atomics, that Atomics.wait is never invoked on the main event loop thread, that all worker synchronization utilizes bounded timeouts with explicit error handling for 'timed-out', and that worker pool capacities are strictly capped to prevent native thread exhaustion.

## Strict Guidelines
- Engineers MUST NEVER execute Atomics.wait or Atomics.waitAsync without an explicit, bounded millisecond timeout.
- Engineers MUST NEVER invoke Atomics.wait on the primary Bun event-loop thread; blocking wait operations are restricted exclusively to background Worker contexts.
- Engineers MUST ALWAYS access and mutate SharedArrayBuffer indices through Atomics primitives (load, store, exchange, compareExchange, add, sub) to enforce correct acquire/release memory barriers.
- Workers MUST handle all return states of Atomics.wait ('ok', 'not-equal', 'timed-out') with deterministic fallbacks rather than assuming unconditional wakes.
- Services MUST manage workers through a pre-allocated, bounded worker pool capped against navigator.hardwareConcurrency or configured limits, and MUST NOT spawn ephemeral workers per request.

## Bad vs Good Implementations
### Unbounded Wait & Direct Shared Memory Mutation vs. Fenced Bounded Worker Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct typed array index mutations bypass CPU memory fences, permitting cache incoherency and race conditions between threads. Invoking Atomics.wait without a timeout parameter causes workers to hang indefinitely if the corresponding Atomics.notify occurred prior to wait registration, leading to thread-pool starvation.
```typescript
// BAD: Direct SharedArrayBuffer mutation without atomic fences,
// unbounded Atomics.wait risking permanent deadlock, and no timeout handling.
export function processComputeTask(sharedBuffer: SharedArrayBuffer, index: number) {
  const view = new Int32Array(sharedBuffer);
  
  // Non-atomic read and write allows race conditions and CPU cache staleness
  view[index] = view[index] + 1;

  // DANGEROUS: Unbounded wait blocks OS worker thread indefinitely if notify is missed
  const status = Atomics.wait(view, 0, 0);
  if (status === "ok") {
    return view[index];
  }
  return null;
}
```

#### Production Standard (Correct)
> **Standard**: Uses Atomics.compareExchange and Atomics.store to enforce acquire-release memory order across threads, applies a mandatory timeout to Atomics.wait to prevent permanent worker deadlocks, and cleanly branches on all three potential outcomes ('ok', 'not-equal', 'timed-out').
```typescript
// GOOD: Strict atomic fencing, bounded timeout, and comprehensive state resolution
export const STATE_INDEX = 0;
export const DATA_INDEX = 1;
export const STATE_IDLE = 0;
export const STATE_BUSY = 1;
export const STATE_READY = 2;

export const DEFAULT_TIMEOUT_MS = 5000;

export function executeWorkerTask(
  controlBuffer: SharedArrayBuffer,
  timeoutMs: number = DEFAULT_TIMEOUT_MS
): number {
  const ctrl = new Int32Array(controlBuffer);

  // Transition state to BUSY atomically using compare-and-swap fence
  const prev = Atomics.compareExchange(ctrl, STATE_INDEX, STATE_IDLE, STATE_BUSY);
  if (prev !== STATE_IDLE) {
    throw new Error(`Worker coordination conflict: expected IDLE (0), found ${prev}`);
  }

  // Bounded wait on control slot: wait until state is no longer STATE_BUSY
  const waitResult = Atomics.wait(ctrl, STATE_INDEX, STATE_BUSY, timeoutMs);

  switch (waitResult) {
    case "ok":
    case "not-equal": {
      // Synchronized read with Acquire barrier semantics
      const finalState = Atomics.load(ctrl, STATE_INDEX);
      if (finalState === STATE_READY) {
        return Atomics.load(ctrl, DATA_INDEX);
      }
      throw new Error(`Worker woke with unexpected terminal state: ${finalState}`);
    }
    case "timed-out":
      // Reset state and signal failure to prevent permanent deadlock
      Atomics.store(ctrl, STATE_INDEX, STATE_IDLE);
      throw new Error(`Worker synchronization timed out after ${timeoutMs}ms`);
  }
}
```

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 Native Worker SharedArrayBuffer Concurrency Fencing & Bounded Synchronization

Bun 1.2 Native Worker SharedArrayBuffer Concurrency Fencing & Bounded Synchronization defines an industrial-grade behavioral standard for backend engineering. Enforces strict synchronization fences and bounded timeouts on Atomics operations over SharedArrayBuffer memory segments between Bun 1.2 main processes and native Worker threads. Prevents event-loop thread starvation, unbounded blocking, and uncoordinated shared memory corruptions in high-throughput compute services. 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: Unbounded Atomics.wait Blocking and Unsynchronized Direct SharedArrayBuffer Mutations 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 DriftUnbounded Atomics.wait Blocking and Unsynchronized Direct SharedArrayBuffer Mutations 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 NEVER execute Atomics.wait or Atomics.waitAsync without an explicit, bounded millisecond timeout.

Engineers MUST NEVER execute Atomics.wait or Atomics.waitAsync without an explicit, bounded millisecond timeout.

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 NEVER invoke Atomics.wait on the primary Bun event-loop thread

Engineers MUST NEVER invoke Atomics.wait on the primary Bun event-loop thread; blocking wait operations are restricted exclusively to background Worker contexts.

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 ALWAYS access and mutate SharedArrayBuffer indices through Atomics primitives (load, store, exchange, compareExchange, add, sub) to enforce correct acquire/release memory barriers.

Engineers MUST ALWAYS access and mutate SharedArrayBuffer indices through Atomics primitives (load, store, exchange, compareExchange, add, sub) to enforce correct acquire/release memory 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.
4

Workers MUST handle all return states of Atomics.wait ('ok', 'not-equal', 'timed-out') with deterministic fallbacks rather than assuming unconditional wakes.

Workers MUST handle all return states of Atomics.wait ('ok', 'not-equal', 'timed-out') with deterministic fallbacks rather than assuming unconditional wakes.

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 manage workers through a pre-allocated, bounded worker pool capped against navigator.hardwareConcurrency or configured limits, and MUST NOT spawn ephemeral workers per request.

Services MUST manage workers through a pre-allocated, bounded worker pool capped against navigator.hardwareConcurrency or configured limits, and MUST NOT spawn ephemeral workers per request.

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 SharedArrayBuffer Concurrency Fencing & Bounded Synchronization critical for AI coding assistants?

Enforces strict synchronization fences and bounded timeouts on Atomics operations over SharedArrayBuffer memory segments between Bun 1.2 main processes and native Worker threads. Prevents event-loop thread starvation, unbounded blocking, and uncoordinated shared memory corruptions in high-throughput compute services. 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 (Unbounded Atomics.wait Blocking and Unsynchronized Direct SharedArrayBuffer Mutations 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