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

Bun 1.2 Multi-Threaded Worker Zero-Copy Ring Buffer Standard

Enforces zero-copy, lock-free inter-thread communication in Bun 1.2 runtimes using SharedArrayBuffer and atomic synchronization primitives. Prevents V8/JSC structured clone serialization overhead and eliminates event-loop microtask starvation under high-throughput data streaming. Guarantees cache-line padded atomic indices and strictly bounded contiguous memory layouts between the main reactor and native worker threads.

Prohibited Anti-Pattern: Starving the Main Event Loop via High-Frequency postMessage Structured Cloning and Unbounded Microtask Enqueueing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Threaded Worker Zero-Copy Ring Buffer Standard - Enforces zero-copy, lock-free inter-thread communication in Bun 1.2 runtimes using SharedArrayBuffer and atomic synchronization primitives. Prevents V8/JSC structured clone serialization overhead and eliminates event-loop microtask starvation under high-throughput data streaming. Guarantees cache-line padded atomic indices and strictly bounded contiguous memory layouts between the main reactor and native worker threads.
globs: src/workers/**/*.{ts,js}, src/lib/concurrency/**/*.{ts,js}, src/pipeline/**/*.{ts,js}, src/**/*.worker.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-zerocopy-ringbuffer-production-standard"
---

# Bun 1.2 Multi-Threaded Worker Zero-Copy Ring Buffer Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Starving the Main Event Loop via High-Frequency postMessage Structured Cloning and Unbounded Microtask Enqueueing

## System Constraints
You are a Principal Systems Engineer and Concurrency Architect enforcing the Bun 1.2 Multi-Threaded Worker Zero-Copy Ring Buffer Standard. You must strictly forbid the use of high-throughput worker.postMessage() with structured clone payloads for continuous data pipelines. Require developers to allocate fixed-size SharedArrayBuffer structures with 64-byte cache-aligned atomic control blocks (head, tail, capacity) and use Atomics.wait/Atomics.notify or low-overhead atomic polling to avoid main thread event-loop starvation and GC pressure.

## Strict Guidelines
- Engineers MUST ALWAYS allocate a single SharedArrayBuffer to bridge Bun native workers for continuous data streams exceeding 100 operations/sec.
- Engineers MUST NOT pass complex objects, raw arrays, or non-transferable TypedArrays through worker.postMessage() in hot execution paths.
- Memory layouts MUST pad atomic head and tail pointers to 64 bytes (16 x Uint32) to prevent false sharing across separate CPU L1/L2 cache lines.
- Workers MUST coordinate through Atomics.load, Atomics.store, and Atomics.wait/Atomics.notify on Int32Array views, never via spin-locks without yield or backoff.
- Buffer slots MUST be power-of-two sizes so circular modulo operations use bitwise masking ((index + 1) & (CAPACITY - 1)) rather than costly division operations.
- Consumers MUST validate frame boundaries before reading raw byte regions to prevent partial or torn reads caused by concurrent writes.

## Bad vs Good Implementations
### Zero-Copy Circular Ring Buffer vs Structured Clone postMessage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing serializable objects or converting TypedArrays to standard arrays via postMessage invokes the structured clone algorithm on every call. At scale, this consumes massive CPU cycles on both threads, creates severe V8/JSC GC pressure, and floods the event loop microtask queue, causing latency spikes and starvation.
```typescript
// ANTI-PATTERN: High-frequency serialization causes GC churn and starves the event loop
import { Worker } from "bun";

const worker = new Worker(new URL("./pipeline.worker.ts", import.meta.url).href);

// Emits 50,000 packets/sec - triggers JSON/structured-clone overhead and queue explosion
export function streamToWorker(sensorChunks: Float64Array[]): void {
  for (const chunk of sensorChunks) {
    // Serializes the entire TypedArray on every invocation
    worker.postMessage({
      type: "DATA_BATCH",
      payload: Array.from(chunk),
      timestamp: performance.now()
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Allocates a single SharedArrayBuffer up-front. Indexes are accessed via Int32Array using Atomics, separated by 64 bytes to eliminate cache-line ping-pong (false sharing). Data is copied directly into shared memory without structured cloning, achieving constant O(1) allocation overhead and zero main-thread microtask starvation.
```typescript
// PRODUCTION STANDARD: SharedArrayBuffer Ring Buffer with 64-byte padded Atomics
import { Worker } from "bun";

const RING_BUFFER_CAPACITY = 1024 * 1024; // 1MB payload buffer (Power of 2)
const INDEX_HEAD = 0; // Worker read index
const INDEX_TAIL = 16; // Producer write index (64-byte cache line separation: 16 * 4 bytes)
const HEADER_SIZE = 128; // Reserved byte offset for control block

const sharedBuffer = new SharedArrayBuffer(HEADER_SIZE + RING_BUFFER_CAPACITY);
const controlView = new Int32Array(sharedBuffer, 0, 32);
const dataView = new Uint8Array(sharedBuffer, HEADER_SIZE, RING_BUFFER_CAPACITY);
const MASK = RING_BUFFER_CAPACITY - 1;

const worker = new Worker(new URL("./pipeline.worker.ts", import.meta.url).href);
worker.postMessage({ type: "INIT", sharedBuffer }); // Transferred once at startup

export function writeBytesZeroCopy(data: Uint8Array): boolean {
  const head = Atomics.load(controlView, INDEX_HEAD);
  const tail = Atomics.load(controlView, INDEX_TAIL);
  const available = RING_BUFFER_CAPACITY - ((tail - head) & MASK);

  if (data.byteLength + 4 > available) {
    return false; // Buffer overflow protection; backpressure applied
  }

  let writePtr = tail & MASK;
  // Write 4-byte frame header (length-prefixed)
  const len = data.byteLength;
  for (let i = 0; i < 4; i++) {
    dataView[(writePtr + i) & MASK] = (len >> (i * 8)) & 0xff;
  }
  writePtr = (writePtr + 4) & MASK;

  // Copy bytes directly without serialization
  for (let i = 0; i < len; i++) {
    dataView[(writePtr + i) & MASK] = data[i];
  }

  Atomics.store(controlView, INDEX_TAIL, (tail + len + 4) & 0x7fffffff);
  Atomics.notify(controlView, INDEX_TAIL, 1);
  return true;
}
```

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 Multi-Threaded Worker Zero-Copy Ring Buffer Standard

Bun 1.2 Multi-Threaded Worker Zero-Copy Ring Buffer Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-copy, lock-free inter-thread communication in Bun 1.2 runtimes using SharedArrayBuffer and atomic synchronization primitives. Prevents V8/JSC structured clone serialization overhead and eliminates event-loop microtask starvation under high-throughput data streaming. Guarantees cache-line padded atomic indices and strictly bounded contiguous memory layouts between the main reactor and native worker 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: Starving the Main Event Loop via High-Frequency postMessage Structured Cloning and Unbounded Microtask Enqueueing 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 DriftStarving the Main Event Loop via High-Frequency postMessage Structured Cloning and Unbounded Microtask EnqueueingCritical
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 single SharedArrayBuffer to bridge Bun native workers for continuous data streams exceeding 100 operations/sec.

Engineers MUST ALWAYS allocate a single SharedArrayBuffer to bridge Bun native workers for continuous data streams exceeding 100 operations/sec.

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 pass complex objects, raw arrays, or non-transferable TypedArrays through worker.postMessage() in hot execution paths.

Engineers MUST NOT pass complex objects, raw arrays, or non-transferable TypedArrays through worker.postMessage() in hot execution paths.

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

Memory layouts MUST pad atomic head and tail pointers to 64 bytes (16 x Uint32) to prevent false sharing across separate CPU L1/L2 cache lines.

Memory layouts MUST pad atomic head and tail pointers to 64 bytes (16 x Uint32) to prevent false sharing across separate CPU L1/L2 cache lines.

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 coordinate through Atomics.load, Atomics.store, and Atomics.wait/Atomics.notify on Int32Array views, never via spin-locks without yield or backoff.

Workers MUST coordinate through Atomics.load, Atomics.store, and Atomics.wait/Atomics.notify on Int32Array views, never via spin-locks without yield or backoff.

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

Buffer slots MUST be power-of-two sizes so circular modulo operations use bitwise masking ((index + 1) & (CAPACITY - 1)) rather than costly division operations.

Buffer slots MUST be power-of-two sizes so circular modulo operations use bitwise masking ((index + 1) & (CAPACITY - 1)) rather than costly division operations.

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.
6

Consumers MUST validate frame boundaries before reading raw byte regions to prevent partial or torn reads caused by concurrent writes.

Consumers MUST validate frame boundaries before reading raw byte regions to prevent partial or torn reads caused by concurrent writes.

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 Multi-Threaded Worker Zero-Copy Ring Buffer Standard critical for AI coding assistants?

Enforces zero-copy, lock-free inter-thread communication in Bun 1.2 runtimes using SharedArrayBuffer and atomic synchronization primitives. Prevents V8/JSC structured clone serialization overhead and eliminates event-loop microtask starvation under high-throughput data streaming. Guarantees cache-line padded atomic indices and strictly bounded contiguous memory layouts between the main reactor and native worker 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 (Starving the Main Event Loop via High-Frequency postMessage Structured Cloning and Unbounded Microtask Enqueueing) 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