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

Bun 1.2 Worker Thread SharedArrayBuffer Atomics Mutex Timeout Guardrail

Enforces deterministic bounded timeout wrappers around all Atomics.wait calls within multi-threaded Bun 1.2 worker pools. Unbounded Atomics.wait invocations in worker threads cause unrecoverable thread deadlocks, resource exhaustion, and persistent event loop starvation when locking worker threads fail to release shared memory locks.

Prohibited Anti-Pattern: Unbounded Atomics.wait Invocations Causing Permanent Worker Thread Deadlocks and Zombie Pool Exhaustion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker Thread SharedArrayBuffer Atomics Mutex Timeout Guardrail - Enforces deterministic bounded timeout wrappers around all Atomics.wait calls within multi-threaded Bun 1.2 worker pools. Unbounded Atomics.wait invocations in worker threads cause unrecoverable thread deadlocks, resource exhaustion, and persistent event loop starvation when locking worker threads fail to release shared memory locks.
globs: src/**/*.{ts,js,mjs}, workers/**/*.{ts,js,mjs}, lib/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-atomics-mutex-timeout-guardrail"
---

# Bun 1.2 Worker Thread SharedArrayBuffer Atomics Mutex Timeout Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Atomics.wait Invocations Causing Permanent Worker Thread Deadlocks and Zombie Pool Exhaustion

## System Constraints
You are a Principal Backend Systems Architect enforcing strict concurrency invariants in Bun 1.2 worker pools. Mandate bounded wait timeouts, error-state unwinding, and poison-pill detection on all SharedArrayBuffer Atomics operations to prevent worker thread deadlocks and pool starvation.

## Strict Guidelines
- Engineers MUST ALWAYS pass an explicit, bounded non-negative timeout parameter (in milliseconds) to Atomics.wait when synchronizing on SharedArrayBuffer instances.
- Engineers MUST NOT invoke Atomics.wait without a timeout argument or pass Infinity as the wait duration.
- Workers MUST handle the 'timed-out' return value from Atomics.wait by unwinding thread state, releasing acquired partial locks, and throwing or handling a typed LockTimeoutError.
- Workers MUST wrap critical sections between mutex acquisition and release in try...finally blocks to guarantee Atomics.store and Atomics.notify execution even during unhandled exceptions.
- Engineers MUST verify that Atomics.wait is only executed on dedicated worker threads (Bun Worker or node:worker_threads), as invoking Atomics.wait on the main thread throws a TypeError in conformant JavaScript runtimes.

## Bad vs Good Implementations
### Unbounded Mutex Acquisition vs. Bounded Reentrant Mutex with Timeout Fallback

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Atomics.wait(this.state, 0, 1) omits the timeout parameter. If the thread holding the lock encounters an unhandled exception or termination, waiting threads deadlock forever, causing silent zombie worker threads and pool starvation in Bun.
```typescript
export class UnsafeWorkerMutex {
  private state: Int32Array;

  constructor(sharedBuffer: SharedArrayBuffer, offset: number = 0) {
    this.state = new Int32Array(sharedBuffer, offset, 1);
  }

  lock(): void {
    // ANTI-PATTERN: Indefinite wait with no timeout parameter.
    // If another worker thread crashes or exits unexpectedly while holding the lock,
    // this thread blocks permanently, starving the Bun worker pool.
    while (Atomics.compareExchange(this.state, 0, 0, 1) !== 0) {
      Atomics.wait(this.state, 0, 1);
    }
  }

  unlock(): void {
    Atomics.store(this.state, 0, 0);
    Atomics.notify(this.state, 0, 1);
  }
}
```

#### Production Standard (Correct)
> **Standard**: The bounded mutex recalculates remaining time against an absolute deadline and passes it to Atomics.wait. A 'timed-out' return raises an explicit LockTimeoutError, preventing worker deadlocks. The runLocked helper ensures deterministic lock release via try...finally.
```typescript
export class LockTimeoutError extends Error {
  constructor(timeoutMs: number) {
    super(`Failed to acquire lock within ${timeoutMs}ms: potential worker deadlock.`);
    this.name = 'LockTimeoutError';
  }
}

export class BoundedWorkerMutex {
  private static readonly UNLOCKED = 0;
  private static readonly LOCKED = 1;
  private readonly state: Int32Array;

  constructor(sharedBuffer: SharedArrayBuffer, byteOffset: number = 0) {
    this.state = new Int32Array(sharedBuffer, byteOffset, 1);
  }

  acquire(timeoutMs: number = 5000): void {
    const deadline = performance.now() + timeoutMs;

    while (Atomics.compareExchange(this.state, 0, BoundedWorkerMutex.UNLOCKED, BoundedWorkerMutex.LOCKED) !== BoundedWorkerMutex.UNLOCKED) {
      const remainingMs = deadline - performance.now();
      if (remainingMs <= 0) {
        throw new LockTimeoutError(timeoutMs);
      }

      const result = Atomics.wait(this.state, 0, BoundedWorkerMutex.LOCKED, remainingMs);
      if (result === 'timed-out') {
        throw new LockTimeoutError(timeoutMs);
      }
    }
  }

  release(): void {
    const previous = Atomics.swap(this.state, 0, BoundedWorkerMutex.UNLOCKED);
    if (previous === BoundedWorkerMutex.LOCKED) {
      Atomics.notify(this.state, 0, 1);
    }
  }

  runLocked<T>(fn: () => T, timeoutMs: number = 5000): T {
    this.acquire(timeoutMs);
    try {
      return fn();
    } finally {
      this.release();
    }
  }
}
```

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 Thread SharedArrayBuffer Atomics Mutex Timeout Guardrail

Bun 1.2 Worker Thread SharedArrayBuffer Atomics Mutex Timeout Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic bounded timeout wrappers around all Atomics.wait calls within multi-threaded Bun 1.2 worker pools. Unbounded Atomics.wait invocations in worker threads cause unrecoverable thread deadlocks, resource exhaustion, and persistent event loop starvation when locking worker threads fail to release shared memory locks. 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 Invocations Causing Permanent Worker Thread Deadlocks and Zombie Pool Exhaustion 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 Invocations Causing Permanent Worker Thread Deadlocks and Zombie Pool ExhaustionCritical
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 pass an explicit, bounded non-negative timeout parameter (in milliseconds) to Atomics.wait when synchronizing on SharedArrayBuffer instances.

Engineers MUST ALWAYS pass an explicit, bounded non-negative timeout parameter (in milliseconds) to Atomics.wait when synchronizing on SharedArrayBuffer instances.

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 invoke Atomics.wait without a timeout argument or pass Infinity as the wait duration.

Engineers MUST NOT invoke Atomics.wait without a timeout argument or pass Infinity as the wait duration.

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

Workers MUST handle the 'timed-out' return value from Atomics.wait by unwinding thread state, releasing acquired partial locks, and throwing or handling a typed LockTimeoutError.

Workers MUST handle the 'timed-out' return value from Atomics.wait by unwinding thread state, releasing acquired partial locks, and throwing or handling a typed LockTimeoutError.

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 wrap critical sections between mutex acquisition and release in try...finally blocks to guarantee Atomics.store and Atomics.notify execution even during unhandled exceptions.

Workers MUST wrap critical sections between mutex acquisition and release in try...finally blocks to guarantee Atomics.store and Atomics.notify execution even during unhandled exceptions.

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 verify that Atomics.wait is only executed on dedicated worker threads (Bun Worker or node

Engineers MUST verify that Atomics.wait is only executed on dedicated worker threads (Bun Worker or node:worker_threads), as invoking Atomics.wait on the main thread throws a TypeError in conformant JavaScript runtimes.

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 Thread SharedArrayBuffer Atomics Mutex Timeout Guardrail critical for AI coding assistants?

Enforces deterministic bounded timeout wrappers around all Atomics.wait calls within multi-threaded Bun 1.2 worker pools. Unbounded Atomics.wait invocations in worker threads cause unrecoverable thread deadlocks, resource exhaustion, and persistent event loop starvation when locking worker threads fail to release shared memory locks. 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 Invocations Causing Permanent Worker Thread Deadlocks and Zombie Pool Exhaustion) 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