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

Bun 1.2 Zero-Copy Buffer Transfer and SharedArrayBuffer IPC Invariants

Enforces strict zero-copy memory semantics during Inter-Process Communication (IPC) and Worker thread synchronization under Bun 1.2. Mandates explicit transfer list specifications for ArrayBuffer ownership transfers or coordinated SharedArrayBuffer regions to eliminate Structured Clone allocations, prevent garbage collection pauses, and avoid severe heap fragmentation under high throughput.

Prohibited Anti-Pattern: Implicit Structured Cloning of Large Binary Payloads across Worker Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy Buffer Transfer and SharedArrayBuffer IPC Invariants - Enforces strict zero-copy memory semantics during Inter-Process Communication (IPC) and Worker thread synchronization under Bun 1.2. Mandates explicit transfer list specifications for ArrayBuffer ownership transfers or coordinated SharedArrayBuffer regions to eliminate Structured Clone allocations, prevent garbage collection pauses, and avoid severe heap fragmentation under high throughput.
globs: src/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-sab-ipc-transfer-invariants"
---

# Bun 1.2 Zero-Copy Buffer Transfer and SharedArrayBuffer IPC Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Structured Cloning of Large Binary Payloads across Worker Threads

## System Constraints
You are a Principal Software Architect enforcing zero-copy IPC and deterministic memory management in Bun 1.2 backend runtimes. You must prevent default structured cloning of buffers across worker boundaries by mandating explicit transfer lists or synchronized SharedArrayBuffers.

## Strict Guidelines
- Engineers MUST ALWAYS pass the underlying `ArrayBuffer` in the transfer list array as the second argument to `worker.postMessage()` when transferring ownership.
- Engineers MUST NOT send Node.js `Buffer` or `Uint8Array` views directly to `postMessage()` without explicitly passing `view.buffer` in the transferables array or referencing a `SharedArrayBuffer`.
- Engineers MUST treat transferred `ArrayBuffer` instances as instantly detached and inaccessible on the sending thread, adding explicit post-transfer detachment validations.
- Services handling high-frequency circular ring-buffers or streaming telemetry MUST utilize `SharedArrayBuffer` with `Atomics` primitives rather than discrete message serialization.
- Components NEVER deep-clone binary payloads across threads via message channels or IPC queues; all pipeline stages must respect single-ownership transfer semantics.

## Bad vs Good Implementations
### Zero-Copy ArrayBuffer Transfer vs. Structured Clone Serialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the transfer list forces Bun to deep-copy the binary payload via Structured Clone. For continuous high-throughput streams, this causes severe memory fragmentation, GC spikes, and duplicate memory consumption.
```typescript
import { Worker } from 'worker_threads';

// Anti-pattern: Sending Uint8Array/Buffer without transfer list
// Forces Bun's JavaScriptCore runtime to perform a full structured clone of the buffer.
export function dispatchChunk(worker: Worker, chunk: Uint8Array): void {
  worker.postMessage({
    type: 'INGEST_CHUNK',
    payload: chunk,
    byteLength: chunk.byteLength,
  });
  // Memory remains allocated on caller thread; double-allocation induces GC pressure.
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passing `rawBuffer` in the transfer list detaches the memory from the sender thread and attaches it directly to the worker thread without memory allocation or GC penalties.
```typescript
import { Worker } from 'worker_threads';

export function dispatchChunk(worker: Worker, chunk: Uint8Array): void {
  // Invariant: Extract the exact underlying ArrayBuffer
  const rawBuffer = chunk.buffer;

  // Transfer ownership: rawBuffer becomes detached in this thread (byteLength -> 0)
  worker.postMessage(
    {
      type: 'INGEST_CHUNK',
      payload: rawBuffer,
      byteOffset: chunk.byteOffset,
      byteLength: chunk.byteLength,
    },
    [rawBuffer]
  );

  // Guard assertion verifying detachment
  if (rawBuffer.byteLength !== 0) {
    throw new Error('Fatal: ArrayBuffer ownership was not successfully transferred.');
  }
}
```

### Coordinated In-Memory Streaming with SharedArrayBuffer and Atomics

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: High-frequency IPC using discrete transient message cloning floods the event loop and GC nursery, leading to unbounded latency degradation in real-time microservices.
```typescript
import { Worker } from 'worker_threads';

// Anti-pattern: High-frequency ping-pong messaging with transient buffers
export class FrameDispatcher {
  constructor(private worker: Worker) {}

  pushMetric(metricId: number, value: number): void {
    // Allocates and clones small buffer wrappers thousands of times per second
    const data = new Float64Array([metricId, value, Date.now()]);
    this.worker.postMessage({ frame: data });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Pre-allocating a SharedArrayBuffer and using Atomics eliminates heap allocations and IPC serialization overhead entirely, enabling microsecond synchronization.
```typescript
import { Worker } from 'worker_threads';

export class FrameDispatcher {
  private readonly sab: SharedArrayBuffer;
  private readonly stateView: Int32Array;
  private readonly dataView: Float64Array;

  constructor(private worker: Worker) {
    // Invariant: Allocate shared ring-buffer once
    this.sab = new SharedArrayBuffer(1024 * 1024);
    this.stateView = new Int32Array(this.sab, 0, 1); // Mutex / sequence flag
    this.dataView = new Float64Array(this.sab, 8);

    // Send reference to worker once during initialization
    this.worker.postMessage({ type: 'INIT_RING_BUFFER', buffer: this.sab });
  }

  pushMetric(metricId: number, value: number): void {
    // Acquire lock or spinlock via Atomics
    while (Atomics.compareExchange(this.stateView, 0, 0, 1) !== 0) {
      // Synchronized contention handling
    }

    this.dataView[0] = metricId;
    this.dataView[1] = value;
    this.dataView[2] = Date.now();

    // Release lock and notify waiting worker
    Atomics.store(this.stateView, 0, 0);
    Atomics.notify(this.stateView, 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 Zero-Copy Buffer Transfer and SharedArrayBuffer IPC Invariants

Bun 1.2 Zero-Copy Buffer Transfer and SharedArrayBuffer IPC Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict zero-copy memory semantics during Inter-Process Communication (IPC) and Worker thread synchronization under Bun 1.2. Mandates explicit transfer list specifications for ArrayBuffer ownership transfers or coordinated SharedArrayBuffer regions to eliminate Structured Clone allocations, prevent garbage collection pauses, and avoid severe heap fragmentation under high throughput. 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: Implicit Structured Cloning of Large Binary Payloads 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 DriftImplicit Structured Cloning of Large Binary Payloads 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 ALWAYS pass the underlying `ArrayBuffer` in the transfer list array as the second argument to `worker.postMessage()` when transferring ownership.

Engineers MUST ALWAYS pass the underlying `ArrayBuffer` in the transfer list array as the second argument to `worker.postMessage()` when transferring ownership.

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 send Node.js `Buffer` or `Uint8Array` views directly to `postMessage()` without explicitly passing `view.buffer` in the transferables array or referencing a `SharedArrayBuffer`.

Engineers MUST NOT send Node.js `Buffer` or `Uint8Array` views directly to `postMessage()` without explicitly passing `view.buffer` in the transferables array or referencing a `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.
3

Engineers MUST treat transferred `ArrayBuffer` instances as instantly detached and inaccessible on the sending thread, adding explicit post-transfer detachment validations.

Engineers MUST treat transferred `ArrayBuffer` instances as instantly detached and inaccessible on the sending thread, adding explicit post-transfer detachment validations.

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 handling high-frequency circular ring-buffers or streaming telemetry MUST utilize `SharedArrayBuffer` with `Atomics` primitives rather than discrete message serialization.

Services handling high-frequency circular ring-buffers or streaming telemetry MUST utilize `SharedArrayBuffer` with `Atomics` primitives rather than discrete message serialization.

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 deep-clone binary payloads across threads via message channels or IPC queues

Components NEVER deep-clone binary payloads across threads via message channels or IPC queues; all pipeline stages must respect single-ownership transfer semantics.

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 Zero-Copy Buffer Transfer and SharedArrayBuffer IPC Invariants critical for AI coding assistants?

Enforces strict zero-copy memory semantics during Inter-Process Communication (IPC) and Worker thread synchronization under Bun 1.2. Mandates explicit transfer list specifications for ArrayBuffer ownership transfers or coordinated SharedArrayBuffer regions to eliminate Structured Clone allocations, prevent garbage collection pauses, and avoid severe heap fragmentation under high throughput. 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 (Implicit Structured Cloning of Large Binary Payloads 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