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

Bun 1.2 Native Worker Zero-Copy ArrayBuffer Transfer Protocol

Mandates strict zero-copy ownership transfer of high-volume binary payloads between Bun native threads via ArrayBuffer transfer lists. Eliminates structured clone serialization overhead and memory duplication in compute-heavy background tasks. Requires immediate post-transfer validation to guard against use-after-transfer detached buffer access.

Prohibited Anti-Pattern: Implicit Structured Cloning of TypedArrays Across Bun Worker Boundaries Causing Latency Spikes and Double-Memory Footprints

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Worker Zero-Copy ArrayBuffer Transfer Protocol - Mandates strict zero-copy ownership transfer of high-volume binary payloads between Bun native threads via ArrayBuffer transfer lists. Eliminates structured clone serialization overhead and memory duplication in compute-heavy background tasks. Requires immediate post-transfer validation to guard against use-after-transfer detached buffer access.
globs: src/**/*.ts, workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-zero-copy-transfer-protocol"
---

# Bun 1.2 Native Worker Zero-Copy ArrayBuffer Transfer Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Structured Cloning of TypedArrays Across Bun Worker Boundaries Causing Latency Spikes and Double-Memory Footprints

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Native Worker Zero-Copy ArrayBuffer Transfer Protocol. Mandate invariants that strictly forbid structured cloning of high-throughput binary buffers between Bun threads. Enforce ownership transfers using the transfer list parameter in postMessage, guarantee caller memory detachment verification, and ensure worker pipelines reconstruct typed views without allocations.

## Strict Guidelines
- Engineers MUST ALWAYS pass the underlying ArrayBuffer (`typedArray.buffer`) in the transfer list array parameter of `worker.postMessage(message, [transferable])`.
- Engineers MUST NOT pass TypedArrays directly within payload objects without transferring their underlying ArrayBuffer, which triggers expensive structured clone serialization.
- Code MUST assert that the sender's ArrayBuffer has been detached (`buffer.byteLength === 0`) immediately following `postMessage` to prevent use-after-transfer race conditions.
- Worker scripts MUST transfer result buffers back to the parent thread via `self.postMessage({ result: buffer }, [buffer])` instead of returning cloned data.
- Components NEVER attempt to read or mutate a transferred ArrayBuffer in the sending thread once ownership has been yielded.

## Bad vs Good Implementations
### Passing TypedArray via Structured Clone vs Explicit Zero-Copy ArrayBuffer Transfer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to pass largePayload.buffer in the transfer list forces Bun's V8/JSC engine to duplicate the entire 80MB memory block via structured serialization. This doubles memory usage, stalls the event loop during serialization, and creates an illusion of shared state.
```typescript
import { Worker } from 'bun';

const worker = new Worker(new URL('./compute-worker.ts', import.meta.url));
const largePayload = new Float64Array(10_000_000); // ~80MB allocation

// ANTI-PATTERN: Passing TypedArray directly without transfer list.
// Bun executes an implicit structured clone, copying all 80MB of memory,
// doubling process RSS and causing garbage collection spikes.
worker.postMessage({
  type: 'ANALYZE',
  data: largePayload
});

// largePayload is still accessible here, encouraging unsafe concurrency bugs
console.log(largePayload.length);
```

#### Production Standard (Correct)
> **Standard**: By supplying rawBuffer in the second argument of postMessage, ownership is transferred instantly with zero allocation overhead. The sending thread's buffer is immediately detached (byteLength becomes 0), eliminating use-after-transfer bugs and serialization delays.
```typescript
import { Worker } from 'bun';

const worker = new Worker(new URL('./compute-worker.ts', import.meta.url));
const largePayload = new Float64Array(10_000_000); // ~80MB allocation
const rawBuffer = largePayload.buffer;

// PRODUCTION INVARIANT: Transfer underlying ArrayBuffer ownership directly.
worker.postMessage(
  {
    type: 'ANALYZE',
    buffer: rawBuffer,
    byteOffset: largePayload.byteOffset,
    length: largePayload.length
  },
  [rawBuffer] // Zero-copy transfer list
);

// Defensive Verification: The sender's buffer MUST be detached
if (rawBuffer.byteLength !== 0) {
  throw new Error('Fatal: ArrayBuffer ownership was not transferred. Memory leak risk.');
}
```

### Worker Side Invariant: Reconstructing TypedArray and Zero-Copy Reply

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker receives cloned data and sends back another cloned TypedArray. For pipelines processing hundreds of frames or audio slices per second, this results in continuous GC thrashing and excessive latency.
```typescript
declare var self: Worker;

self.onmessage = (event: MessageEvent) => {
  // ANTI-PATTERN: Assumes data is already typed without handling buffer alignment,
  // and clones result back to the host.
  const data: Float64Array = event.data.data;
  
  const result = new Float64Array(data.length);
  for (let i = 0; i < data.length; i++) {
    result[i] = Math.sqrt(data[i]);
  }

  // Structured clone back to parent thread - double clone penalty
  self.postMessage({ result });
};
```

#### Production Standard (Correct)
> **Standard**: Reconstructs the typed view directly over the transferred ArrayBuffer and mutates in place (or into an allocated output buffer), then transfers ownership back using the postMessage transfer list, preserving zero-copy throughput end-to-end.
```typescript
declare var self: Worker;

interface WorkerRequest {
  type: 'ANALYZE';
  buffer: ArrayBuffer;
  byteOffset: number;
  length: number;
}

self.onmessage = (event: MessageEvent<WorkerRequest>) => {
  const { buffer, byteOffset, length } = event.data;
  
  // Zero-copy view instantiation on transferred buffer
  const inputView = new Float64Array(buffer, byteOffset, length);
  
  // In-place processing or output buffer allocation
  for (let i = 0; i < inputView.length; i++) {
    inputView[i] = Math.sqrt(inputView[i]);
  }

  // Transfer buffer back to parent thread with zero memory cloning
  self.postMessage(
    {
      type: 'COMPLETE',
      buffer: inputView.buffer,
      byteOffset: inputView.byteOffset,
      length: inputView.length
    },
    [inputView.buffer]
  );
};
```

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 Native Worker Zero-Copy ArrayBuffer Transfer Protocol

Bun 1.2 Native Worker Zero-Copy ArrayBuffer Transfer Protocol defines an industrial-grade behavioral standard for backend engineering. Mandates strict zero-copy ownership transfer of high-volume binary payloads between Bun native threads via ArrayBuffer transfer lists. Eliminates structured clone serialization overhead and memory duplication in compute-heavy background tasks. Requires immediate post-transfer validation to guard against use-after-transfer detached buffer access. 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 TypedArrays Across Bun Worker Boundaries Causing Latency Spikes and Double-Memory Footprints 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 TypedArrays Across Bun Worker Boundaries Causing Latency Spikes and Double-Memory FootprintsCritical
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 (`typedArray.buffer`) in the transfer list array parameter of `worker.postMessage(message, [transferable])`.

Engineers MUST ALWAYS pass the underlying ArrayBuffer (`typedArray.buffer`) in the transfer list array parameter of `worker.postMessage(message, [transferable])`.

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 TypedArrays directly within payload objects without transferring their underlying ArrayBuffer, which triggers expensive structured clone serialization.

Engineers MUST NOT pass TypedArrays directly within payload objects without transferring their underlying ArrayBuffer, which triggers expensive structured clone 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.
3

Code MUST assert that the sender's ArrayBuffer has been detached (`buffer.byteLength === 0`) immediately following `postMessage` to prevent use-after-transfer race conditions.

Code MUST assert that the sender's ArrayBuffer has been detached (`buffer.byteLength === 0`) immediately following `postMessage` to prevent use-after-transfer race conditions.

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

Worker scripts MUST transfer result buffers back to the parent thread via `self.postMessage({ result

Worker scripts MUST transfer result buffers back to the parent thread via `self.postMessage({ result: buffer }, [buffer])` instead of returning cloned data.

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 attempt to read or mutate a transferred ArrayBuffer in the sending thread once ownership has been yielded.

Components NEVER attempt to read or mutate a transferred ArrayBuffer in the sending thread once ownership has been yielded.

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 Native Worker Zero-Copy ArrayBuffer Transfer Protocol critical for AI coding assistants?

Mandates strict zero-copy ownership transfer of high-volume binary payloads between Bun native threads via ArrayBuffer transfer lists. Eliminates structured clone serialization overhead and memory duplication in compute-heavy background tasks. Requires immediate post-transfer validation to guard against use-after-transfer detached buffer access. 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 TypedArrays Across Bun Worker Boundaries Causing Latency Spikes and Double-Memory Footprints) 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