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

Bun 1.2 Worker SharedArrayBuffer Zero-Copy Serialization Standard

Enforces zero-copy inter-worker communication across Bun 1.2 microservices by eliminating the structured clone algorithm on hot execution paths. Concurrency domains must operate over pre-allocated SharedArrayBuffer instances synchronized via Atomics primitives, eliminating heap fragmentation, CPU serialization overhead, and garbage collection thrashing in high-throughput workloads.

Prohibited Anti-Pattern: Structured Clone Heap Deserialization Bottlenecks in High-Volume Worker Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker SharedArrayBuffer Zero-Copy Serialization Standard - Enforces zero-copy inter-worker communication across Bun 1.2 microservices by eliminating the structured clone algorithm on hot execution paths. Concurrency domains must operate over pre-allocated SharedArrayBuffer instances synchronized via Atomics primitives, eliminating heap fragmentation, CPU serialization overhead, and garbage collection thrashing in high-throughput workloads.
globs: src/workers/**/*.{ts,js}, src/concurrency/**/*.{ts,js}, src/services/**/*.{ts,js}, src/lib/buffers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-zero-copy-guardrail"
---

# Bun 1.2 Worker SharedArrayBuffer Zero-Copy Serialization Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Structured Clone Heap Deserialization Bottlenecks in High-Volume Worker Pipelines

## System Constraints
You are a Principal Software Architect enforcing zero-copy concurrency architectures in Bun 1.2 services. You must reject any worker messaging pattern that relies on standard structured cloning (postMessage with serializable objects) in hot execution paths or high-throughput batch processors. Mandate the use of pre-allocated SharedArrayBuffer memory domains, TypedArray views, and Atomics synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS initialize Workers by transferring a single, pre-allocated SharedArrayBuffer during bootstrap instead of transmitting message payloads on every execution cycle.
- Engineers MUST NOT invoke `postMessage(data)` with dynamic JavaScript objects, arrays, or JSON-serializable payloads on hot data paths (greater than 100 ops/sec).
- Services MUST synchronize state across thread boundaries using `Atomics.wait`, `Atomics.notify`, `Atomics.load`, and `Atomics.store` over shared Int32Array control blocks.
- Code SHOULD enforce ring-buffer or disruptor memory patterns with contiguous byte alignments (64-byte cache line alignment preferred) inside the SharedArrayBuffer.
- Components NEVER reallocate or mutate the underlying SharedArrayBuffer capacity at runtime; capacity must be bounded and validated at service startup.
- Engineers MUST explicitly verify that cross-origin isolation flags (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`) are satisfied if workers interface with web-adjacent contexts.

## Bad vs Good Implementations
### Hot-Path Inter-Worker Message Passing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing complex dynamic payloads via postMessage forces Bun to execute the structured clone algorithm. For high-volume services, deep-copying arrays and nested objects between threads locks the main thread event loop, incurs massive memory allocations, and degrades throughput.
```typescript
import { Worker } from 'bun';

// ANTI-PATTERN: Serializing large batches over structured clone on every tick.
// Causes catastrophic CPU spikes from serialization and V8/JSC GC thrashing.
const worker = new Worker(new URL('./compute.worker.ts', import.meta.url).href);

export async function dispatchBatch(records: Array<{ id: number; timestamp: number; value: number }>) {
  worker.postMessage({ 
    type: 'PROCESS_BATCH', 
    records // Deep-copied via structured clone on every invocation
  });
}
```

#### Production Standard (Correct)
> **Standard**: SharedArrayBuffer is instantiated once at initialization and mapped to DataView/TypedArray layouts. Writes update contiguous memory locations in-place, and thread coordination is achieved via Atomics without structured cloning, achieving zero garbage collection overhead and sub-microsecond latency.
```typescript
import { Worker } from 'bun';

// PRODUCTION INVARIANT: Shared pre-allocated memory layout with Atomics synchronization.
const CAPACITY = 65536;
const HEADER_BYTES = 16;
const RECORD_SIZE = 16; // 8 bytes id (BigInt64), 4 bytes timestamp (Int32), 4 bytes value (Float32)
const TOTAL_BYTES = HEADER_BYTES + (CAPACITY * RECORD_SIZE);

const sharedBuffer = new SharedArrayBuffer(TOTAL_BYTES);
const controlView = new Int32Array(sharedBuffer, 0, 4); // [0]: writeIndex, [1]: readIndex, [2]: lock, [3]: signal

const worker = new Worker(new URL('./compute.worker.ts', import.meta.url).href);
// Bootstrap worker by sending SharedArrayBuffer reference exactly once
worker.postMessage({ type: 'BOOTSTRAP', buffer: sharedBuffer });

export function writeRecord(id: bigint, timestamp: number, value: number): boolean {
  const writeIdx = Atomics.load(controlView, 0);
  const readIdx = Atomics.load(controlView, 1);
  const nextWrite = (writeIdx + 1) % CAPACITY;

  if (nextWrite === readIdx) {
    return false; // Ring buffer full: zero allocation backpressure
  }

  const offset = HEADER_BYTES + (writeIdx * RECORD_SIZE);
  const dataView = new DataView(sharedBuffer, offset, RECORD_SIZE);
  dataView.setBigInt64(0, id, true);
  dataView.setInt32(8, timestamp, true);
  dataView.setFloat32(12, value, true);

  Atomics.store(controlView, 0, nextWrite);
  Atomics.notify(controlView, 3, 1); // Wake worker zero-copy
  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 Worker SharedArrayBuffer Zero-Copy Serialization Standard

Bun 1.2 Worker SharedArrayBuffer Zero-Copy Serialization Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-copy inter-worker communication across Bun 1.2 microservices by eliminating the structured clone algorithm on hot execution paths. Concurrency domains must operate over pre-allocated SharedArrayBuffer instances synchronized via Atomics primitives, eliminating heap fragmentation, CPU serialization overhead, and garbage collection thrashing in high-throughput workloads. 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: Structured Clone Heap Deserialization Bottlenecks in High-Volume Worker Pipelines 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 DriftStructured Clone Heap Deserialization Bottlenecks in High-Volume Worker PipelinesCritical
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 Workers by transferring a single, pre-allocated SharedArrayBuffer during bootstrap instead of transmitting message payloads on every execution cycle.

Engineers MUST ALWAYS initialize Workers by transferring a single, pre-allocated SharedArrayBuffer during bootstrap instead of transmitting message payloads on every execution cycle.

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 `postMessage(data)` with dynamic JavaScript objects, arrays, or JSON-serializable payloads on hot data paths (greater than 100 ops/sec).

Engineers MUST NOT invoke `postMessage(data)` with dynamic JavaScript objects, arrays, or JSON-serializable payloads on hot data paths (greater than 100 ops/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.
3

Services MUST synchronize state across thread boundaries using `Atomics.wait`, `Atomics.notify`, `Atomics.load`, and `Atomics.store` over shared Int32Array control blocks.

Services MUST synchronize state across thread boundaries using `Atomics.wait`, `Atomics.notify`, `Atomics.load`, and `Atomics.store` over shared Int32Array control blocks.

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

Code SHOULD enforce ring-buffer or disruptor memory patterns with contiguous byte alignments (64-byte cache line alignment preferred) inside the SharedArrayBuffer.

Code SHOULD enforce ring-buffer or disruptor memory patterns with contiguous byte alignments (64-byte cache line alignment preferred) inside the SharedArrayBuffer.

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 reallocate or mutate the underlying SharedArrayBuffer capacity at runtime

Components NEVER reallocate or mutate the underlying SharedArrayBuffer capacity at runtime; capacity must be bounded and validated at service startup.

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

Engineers MUST explicitly verify that cross-origin isolation flags (`Cross-Origin-Opener-Policy

Engineers MUST explicitly verify that cross-origin isolation flags (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`) are satisfied if workers interface with web-adjacent 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.
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 Serialization Standard critical for AI coding assistants?

Enforces zero-copy inter-worker communication across Bun 1.2 microservices by eliminating the structured clone algorithm on hot execution paths. Concurrency domains must operate over pre-allocated SharedArrayBuffer instances synchronized via Atomics primitives, eliminating heap fragmentation, CPU serialization overhead, and garbage collection thrashing in high-throughput workloads. 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 (Structured Clone Heap Deserialization Bottlenecks in High-Volume Worker Pipelines) 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