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

Bun 1.2 SharedArrayBuffer Cross-Worker Memory Barrier & Ring-Buffer Standard

Establishes lock-free ring-buffer atomic memory barriers across multithreaded Bun workers to ensure thread-safe, zero-copy deserialization of streaming WebSocket payloads. Guarantees that producers commit payload writes to the SharedArrayBuffer with release semantics before incrementing head pointers, while consumer workers enforce acquire fences before accessing buffer regions.

Prohibited Anti-Pattern: Unsynchronized SharedArrayBuffer Mutations and Dirty Reads via Raw Pointer Traversal Without Atomics Barrier Fences

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 SharedArrayBuffer Cross-Worker Memory Barrier & Ring-Buffer Standard - Establishes lock-free ring-buffer atomic memory barriers across multithreaded Bun workers to ensure thread-safe, zero-copy deserialization of streaming WebSocket payloads. Guarantees that producers commit payload writes to the SharedArrayBuffer with release semantics before incrementing head pointers, while consumer workers enforce acquire fences before accessing buffer regions.
globs: src/workers/**/*.{ts,js}, src/network/**/*.{ts,js}, src/buffers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-shared-array-buffer-worker-barrier-standard"
---

# Bun 1.2 SharedArrayBuffer Cross-Worker Memory Barrier & Ring-Buffer Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized SharedArrayBuffer Mutations and Dirty Reads via Raw Pointer Traversal Without Atomics Barrier Fences

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 SharedArrayBuffer Cross-Worker Barrier Standard. Mandate strict lock-free atomic barriers for zero-copy streaming ingest, prohibiting un-fenced pointer manipulation, standard postMessage data cloning, and unaligned typed array accesses.

## Strict Guidelines
- Engineers MUST ALWAYS initialize SharedArrayBuffer instances with explicit 8-byte alignment padding for atomic pointers (head/tail indexes) alongside contiguous binary payload segments.
- Engineers MUST NOT transmit raw WebSocket chunks across Bun workers via postMessage structured cloning when zero-copy processing throughput is required; use SharedArrayBuffer regions exclusively.
- Code SHOULD enforce acquire-release semantics using Atomics.store(index, val) with Atomics.notify() on the producer side, and Atomics.wait() with Atomics.load(index) on worker consumer loops.
- Services MUST verify ring-buffer capacity before writing WebSocket binary data to prevent buffer overrun corruption when consumers lag behind ingress rates.
- Components NEVER read payload bytes from the SharedArrayBuffer prior to validating the atomic head pointer via Atomics.load to eliminate out-of-order execution artifacts and dirty reads.

## Bad vs Good Implementations
### Zero-Copy WebSocket Ingest with Lock-Free Atomic Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly copying WebSocket payload bytes into a shared buffer without acquire-release fences allows the worker to read partial or reordered writes. Passing metadata via postMessage introduces event-loop latency and ignores out-of-order memory visibility across hardware threads.
```typescript
// BAD: Race conditions, uncoordinated memory writes, and data-cloning overhead
import { Worker } from "bun";

const sab = new SharedArrayBuffer(1024 * 1024);
const worker = new Worker("./worker.ts");

Bun.serve({
  port: 8080,
  websocket: {
    message(ws, message) {
      if (message instanceof Uint8Array) {
        // Race condition: Worker reads partially written data without atomic signaling
        const view = new Uint8Array(sab);
        view.set(message, 0);
        worker.postMessage({ offset: 0, length: message.byteLength });
      }
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements an aligned circular ring-buffer where atomic fences isolate control pointers from payload blocks. Uses Atomics.store and Atomics.notify to establish an explicit release barrier, ensuring the consumer sees the fully populated bytes only after head pointer progression.
```typescript
// GOOD: Aligned control headers with atomic barriers and non-blocking zero-copy notifications
const RING_BUFFER_SIZE = 1024 * 1024 * 16; // 16MB buffer
const HEADER_BYTES = 64; // 8 x Int32 control slots (head, tail, etc.)
const sab = new SharedArrayBuffer(RING_BUFFER_SIZE + HEADER_BYTES);

// Index 0: Producer Head, Index 1: Consumer Tail
const controlIndices = new Int32Array(sab, 0, 16);
const payloadBuffer = new Uint8Array(sab, HEADER_BYTES, RING_BUFFER_SIZE);

const worker = new Worker(new URL("./consumer-worker.ts", import.meta.url));
worker.postMessage({ type: "INIT", sab });

Bun.serve({
  port: 8080,
  websocket: {
    message(ws, chunk) {
      if (!(chunk instanceof Uint8Array)) return;
      const length = chunk.byteLength;
      const head = Atomics.load(controlIndices, 0);
      const tail = Atomics.load(controlIndices, 1);
      
      const freeSpace = (tail <= head) 
        ? RING_BUFFER_SIZE - (head - tail) - 1 
        : tail - head - 1;

      if (length > freeSpace) {
        // Handle backpressure without memory corruption
        ws.close(1013, "Worker buffer backpressure");
        return;
      }

      // Safe contiguous zero-copy ingress
      if (head + length <= RING_BUFFER_SIZE) {
        payloadBuffer.set(chunk, head);
      } else {
        const split = RING_BUFFER_SIZE - head;
        payloadBuffer.set(chunk.subarray(0, split), head);
        payloadBuffer.set(chunk.subarray(split), 0);
      }

      // Memory Barrier: Commit payload writes before publishing updated head
      const nextHead = (head + length) % RING_BUFFER_SIZE;
      Atomics.store(controlIndices, 0, nextHead);
      Atomics.notify(controlIndices, 0, 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: Bun 1.2 SharedArrayBuffer Cross-Worker Memory Barrier & Ring-Buffer Standard

Bun 1.2 SharedArrayBuffer Cross-Worker Memory Barrier & Ring-Buffer Standard defines an industrial-grade behavioral standard for backend engineering. Establishes lock-free ring-buffer atomic memory barriers across multithreaded Bun workers to ensure thread-safe, zero-copy deserialization of streaming WebSocket payloads. Guarantees that producers commit payload writes to the SharedArrayBuffer with release semantics before incrementing head pointers, while consumer workers enforce acquire fences before accessing buffer regions. 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 Dirty Reads via Raw Pointer Traversal Without Atomics Barrier Fences 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 Dirty Reads via Raw Pointer Traversal Without Atomics Barrier FencesCritical
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 initialize SharedArrayBuffer instances with explicit 8-byte alignment padding for atomic pointers (head/tail indexes) alongside contiguous binary payload segments.

Engineers MUST ALWAYS initialize SharedArrayBuffer instances with explicit 8-byte alignment padding for atomic pointers (head/tail indexes) alongside contiguous binary payload segments.

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 transmit raw WebSocket chunks across Bun workers via postMessage structured cloning when zero-copy processing throughput is required

Engineers MUST NOT transmit raw WebSocket chunks across Bun workers via postMessage structured cloning when zero-copy processing throughput is required; use SharedArrayBuffer regions exclusively.

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

Code SHOULD enforce acquire-release semantics using Atomics.store(index, val) with Atomics.notify() on the producer side, and Atomics.wait() with Atomics.load(index) on worker consumer loops.

Code SHOULD enforce acquire-release semantics using Atomics.store(index, val) with Atomics.notify() on the producer side, and Atomics.wait() with Atomics.load(index) on worker consumer loops.

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

Services MUST verify ring-buffer capacity before writing WebSocket binary data to prevent buffer overrun corruption when consumers lag behind ingress rates.

Services MUST verify ring-buffer capacity before writing WebSocket binary data to prevent buffer overrun corruption when consumers lag behind ingress rates.

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

Components NEVER read payload bytes from the SharedArrayBuffer prior to validating the atomic head pointer via Atomics.load to eliminate out-of-order execution artifacts and dirty reads.

Components NEVER read payload bytes from the SharedArrayBuffer prior to validating the atomic head pointer via Atomics.load to eliminate out-of-order execution artifacts and dirty reads.

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 SharedArrayBuffer Cross-Worker Memory Barrier & Ring-Buffer Standard critical for AI coding assistants?

Establishes lock-free ring-buffer atomic memory barriers across multithreaded Bun workers to ensure thread-safe, zero-copy deserialization of streaming WebSocket payloads. Guarantees that producers commit payload writes to the SharedArrayBuffer with release semantics before incrementing head pointers, while consumer workers enforce acquire fences before accessing buffer regions. 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 Dirty Reads via Raw Pointer Traversal Without Atomics Barrier Fences) 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