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-standard

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

Enforces strict transfer list semantics and zero-copy ArrayBuffer ownership handoffs across Bun 1.2 multi-threaded Web Worker isolates. Eliminates multi-gigabyte memory fragmentation, heap cloning thrash, and garbage collection stop-the-world pauses in high-throughput data processing pipelines. Mandates explicit transfer list registration, post-transfer neutered checks, and typed buffer lifecycle management.

Prohibited Anti-Pattern: Implicit Structured Cloning of Large TypedArrays and Shared Memory Leaks Across Worker Isolate Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Threaded Worker Zero-Copy Buffer Ownership Standard - Enforces strict transfer list semantics and zero-copy ArrayBuffer ownership handoffs across Bun 1.2 multi-threaded Web Worker isolates. Eliminates multi-gigabyte memory fragmentation, heap cloning thrash, and garbage collection stop-the-world pauses in high-throughput data processing pipelines. Mandates explicit transfer list registration, post-transfer neutered checks, and typed buffer lifecycle management.
globs: src/**/*.{ts,tsx}, workers/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-zero-copy-transfer-standard"
---

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

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Structured Cloning of Large TypedArrays and Shared Memory Leaks Across Worker Isolate Boundaries

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Multi-Threaded Worker Zero-Copy Buffer Ownership Standard. Mandate explicit transfer lists in all postMessage operations across Web Workers to prevent structured cloning of ArrayBuffers. Disallow referencing transferred buffers in sending contexts once dispatched. Require strict validation of buffer detachment (byteLength === 0) on the sender side and typed envelope encapsulation on the receiver side. Ensure workers operate under isolated execution contexts without shared mutable heap references unless explicitly mediated by SharedArrayBuffer and Atomics.

## Strict Guidelines
- Engineers MUST ALWAYS pass underlying ArrayBuffer instances inside the transfer list array (the second argument of postMessage) when dispatching binary payloads across worker boundaries.
- Engineers MUST NOT access, read, or write to an ArrayBuffer or its TypedArray views after it has been passed to a transfer list, treating post-transfer buffers as detached/neutered immediately.
- Code SHOULD verify buffer detachment post-dispatch using runtime assertions (e.g., verifying `buffer.byteLength === 0`) to safeguard against accidental retention in the sender isolate.
- Services MUST wrap worker message protocols in typed discriminant envelopes that clearly separate transferable raw buffers from JSON-serializable metadata.
- Components NEVER pass TypedArray views (e.g., Uint8Array) directly in the transfer array; engineers MUST explicitly pass `uint8Array.buffer`.

## Bad vs Good Implementations
### Dispatching Binary Buffers Across Worker Boundaries

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the transfer list parameter in postMessage forces Bun's JavaScriptCore engine to perform an expensive structured clone of the TypedArray, doubling memory usage and causing significant latency and GC pauses at high throughput.
```typescript
import { Worker } from 'bun';

interface TaskMessage {
  id: string;
  data: Uint8Array;
}

export function dispatchChunk(worker: Worker, chunkId: string, payload: Uint8Array): void {
  // Anti-pattern: Missing transfer list triggers structured clone algorithm.
  // Duplicates the entire byte payload across isolates, causing high heap churn and GC spikes.
  worker.postMessage({
    id: chunkId,
    data: payload
  });

  // Stale access can silently read stale memory or fail unpredictably
  console.log(`Dispatched payload of size: ${payload.byteLength}`);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passing `rawBuffer` in the transfer list transfers memory ownership without copying bytes. The runtime assertion confirms the sender buffer has been neutered, preventing stale reads and memory leaks.
```typescript
import { Worker } from 'bun';

export interface WorkerEnvelope {
  id: string;
  buffer: ArrayBuffer;
  byteOffset: number;
  byteLength: number;
}

export function dispatchChunkZeroCopy(worker: Worker, chunkId: string, payload: Uint8Array): void {
  const rawBuffer = payload.buffer;
  const byteOffset = payload.byteOffset;
  const byteLength = payload.byteLength;

  const message: WorkerEnvelope = {
    id: chunkId,
    buffer: rawBuffer,
    byteOffset,
    byteLength
  };

  // Production invariant: Explicitly transfer underlying ArrayBuffer ownership
  worker.postMessage(message, [rawBuffer]);

  // Invariant verification: Verify buffer is neutered in sender isolate
  if (rawBuffer.byteLength !== 0) {
    throw new Error(`CRITICAL: ArrayBuffer for chunk ${chunkId} was not detached post-transfer.`);
  }
}
```

### Receiving and Ingesting Transferred ArrayBuffers in Worker Scope

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker receives cloned data, allocates an unpooled typed array, and posts it back without a transfer list, compounding GC pressure in both the worker and main isolate threads.
```typescript
// worker.ts
declare const self: Worker;

self.onmessage = (event: MessageEvent) => {
  // Anti-pattern: Implicitly assuming safe mutation or leaking copies back
  const { id, data } = event.data;
  
  // Re-allocating and echoing clone without transferring
  const processed = new Uint8Array(data.length);
  for (let i = 0; i < data.length; i++) {
    processed[i] = data[i] ^ 0xAA;
  }

  self.postMessage({ id, result: processed });
};
```

#### Production Standard (Correct)
> **Standard**: Re-constructs the TypedArray on top of the transferred ArrayBuffer and transfers ownership back to the coordinator thread using zero-copy semantics, maintaining zero heap-cloning overhead.
```typescript
// worker.ts
import type { WorkerEnvelope } from './types';
declare const self: Worker;

self.onmessage = (event: MessageEvent<WorkerEnvelope>) => {
  const { id, buffer, byteOffset, byteLength } = event.data;

  // Invariant: Wrap detached memory view without reallocating
  const view = new Uint8Array(buffer, byteOffset, byteLength);

  for (let i = 0; i < view.byteLength; i++) {
    view[i] ^= 0xAA;
  }

  // Transfer zero-copy buffer back to parent coordinator
  const response: WorkerEnvelope = {
    id,
    buffer: view.buffer,
    byteOffset: view.byteOffset,
    byteLength: view.byteLength
  };

  self.postMessage(response, [view.buffer]);
};
```

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 Buffer Ownership Standard

Bun 1.2 Multi-Threaded Worker Zero-Copy Buffer Ownership Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict transfer list semantics and zero-copy ArrayBuffer ownership handoffs across Bun 1.2 multi-threaded Web Worker isolates. Eliminates multi-gigabyte memory fragmentation, heap cloning thrash, and garbage collection stop-the-world pauses in high-throughput data processing pipelines. Mandates explicit transfer list registration, post-transfer neutered checks, and typed buffer lifecycle management. 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 TypedArrays and Shared Memory Leaks Across Worker Isolate Boundaries 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 TypedArrays and Shared Memory Leaks Across Worker Isolate BoundariesCritical
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 underlying ArrayBuffer instances inside the transfer list array (the second argument of postMessage) when dispatching binary payloads across worker boundaries.

Engineers MUST ALWAYS pass underlying ArrayBuffer instances inside the transfer list array (the second argument of postMessage) when dispatching binary payloads across worker boundaries.

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 access, read, or write to an ArrayBuffer or its TypedArray views after it has been passed to a transfer list, treating post-transfer buffers as detached/neutered immediately.

Engineers MUST NOT access, read, or write to an ArrayBuffer or its TypedArray views after it has been passed to a transfer list, treating post-transfer buffers as detached/neutered immediately.

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 verify buffer detachment post-dispatch using runtime assertions (e.g., verifying `buffer.byteLength === 0`) to safeguard against accidental retention in the sender isolate.

Code SHOULD verify buffer detachment post-dispatch using runtime assertions (e.g., verifying `buffer.byteLength === 0`) to safeguard against accidental retention in the sender isolate.

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 wrap worker message protocols in typed discriminant envelopes that clearly separate transferable raw buffers from JSON-serializable metadata.

Services MUST wrap worker message protocols in typed discriminant envelopes that clearly separate transferable raw buffers from JSON-serializable metadata.

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 pass TypedArray views (e.g., Uint8Array) directly in the transfer array

Components NEVER pass TypedArray views (e.g., Uint8Array) directly in the transfer array; engineers MUST explicitly pass `uint8Array.buffer`.

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 Buffer Ownership Standard critical for AI coding assistants?

Enforces strict transfer list semantics and zero-copy ArrayBuffer ownership handoffs across Bun 1.2 multi-threaded Web Worker isolates. Eliminates multi-gigabyte memory fragmentation, heap cloning thrash, and garbage collection stop-the-world pauses in high-throughput data processing pipelines. Mandates explicit transfer list registration, post-transfer neutered checks, and typed buffer lifecycle management. 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 TypedArrays and Shared Memory Leaks Across Worker Isolate Boundaries) 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