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

Bun 1.2 Worker MessagePort Zero-Copy Structured-Cloning Transfer Invariant

Enforces strict zero-copy memory transfers across Bun 1.2 multi-threaded Worker contexts via MessagePort and Web Worker APIs. Guarantees linear memory ownership transfer using Transferable ArrayBuffer instances, preventing severe serialization latency, GC pressure, and race conditions on detached memory buffers.

Prohibited Anti-Pattern: Implicit Structured-Clone Payload Duplication and Post-Transfer Mutation of Detached Buffers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker MessagePort Zero-Copy Structured-Cloning Transfer Invariant - Enforces strict zero-copy memory transfers across Bun 1.2 multi-threaded Worker contexts via MessagePort and Web Worker APIs. Guarantees linear memory ownership transfer using Transferable ArrayBuffer instances, preventing severe serialization latency, GC pressure, and race conditions on detached memory buffers.
globs: src/**/*.{ts,tsx}, workers/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-messageport-transfer-invariant"
---

# Bun 1.2 Worker MessagePort Zero-Copy Structured-Cloning Transfer Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Structured-Clone Payload Duplication and Post-Transfer Mutation of Detached Buffers

## System Constraints
You are a Principal Backend Systems Architect enforcing the Bun 1.2 Worker and MessagePort Transfer Invariant. Mandate zero-copy, race-free memory transfers across multi-threaded isolated runtime instances. Ensure all high-throughput parallel compute tasks transfer underlying ArrayBuffers via explicit transfer lists, never pass TypedArray views directly in transfer lists, immediately invalidate detached buffers, and safely manage MessagePort lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS pass the raw underlying ArrayBuffer (e.g., `uint8Array.buffer`) in the transfer list parameter of `worker.postMessage` or `port.postMessage` for binary payloads.
- Engineers MUST NOT pass TypedArray view instances (e.g., `Uint8Array`, `Float32Array`) directly within the transfer list array; transfer lists accept only Transferable primitives (`ArrayBuffer`, `MessagePort`, `ReadableStream`, `WritableStream`).
- Code MUST treat transferred buffers as detached immediately post-dispatch; any read/write access to detached memory (`byteLength === 0` or `.detached === true`) MUST be prohibited and treated as a fatal invariant violation.
- Services MUST explicitly manage `MessagePort` lifecycles by executing `port.close()` and Worker `worker.terminate()` upon task completion or error states to avoid thread handles and memory descriptor leaks in Bun's runtime.
- Components NEVER fall back to JSON serialization or deep structured-cloning over Worker boundaries for compute payloads exceeding 64 KiB.

## Bad vs Good Implementations
### Zero-Copy ArrayBuffer Transfer over MessagePort in Bun 1.2

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the transfer list forces Bun to recursively clone the Uint8Array across thread heaps, introducing multi-millisecond serialization latency and massive GC overhead. Furthermore, mutating the buffer post-dispatch leads to race conditions or desynchronized state between the main thread and worker.
```typescript
import { Worker } from "bun";

interface ComputePayload {
  data: Uint8Array;
}

export function dispatchTask(worker: Worker, data: Uint8Array): void {
  // ANTI-PATTERN: Passing Uint8Array without transfer list causes a full memory copy via structured clone.
  // Passing the TypedArray in the transfer list throws a TypeError: Value is not transferable.
  worker.postMessage({ data });

  // DANGEROUS: Accessing or mutating data after dispatch assuming shared memory
  data[0] = 255; 
}
```

#### Production Standard (Correct)
> **Standard**: Extracts the underlying `ArrayBuffer` and supplies it to the second argument of `postMessage` (`[underlyingBuffer]`). This performs an instantaneous pointer handoff in Bun 1.2 without memory copying, immediately detaches the buffer on the sender thread, and asserts that local access is severed.
```typescript
import { Worker } from "bun";

interface TransferPayload {
  byteOffset: number;
  byteLength: number;
  buffer: ArrayBuffer;
}

export function dispatchTask(worker: Worker, view: Uint8Array): void {
  const underlyingBuffer = view.buffer;

  // Enforce Transferable contract: pass raw ArrayBuffer in the transfer list
  const payload: TransferPayload = {
    byteOffset: view.byteOffset,
    byteLength: view.byteLength,
    buffer: underlyingBuffer
  };

  // Zero-copy transfer: ownership moves entirely to the worker
  worker.postMessage(payload, [underlyingBuffer]);

  // INVARIANT CHECK: In Bun/V8/JSC, transferred buffer becomes detached
  if (underlyingBuffer.byteLength !== 0 && !(underlyingBuffer as { detached?: boolean }).detached) {
    throw new Error("Invariant Violation: Memory was not properly detached during zero-copy transfer");
  }
}
```

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 MessagePort Zero-Copy Structured-Cloning Transfer Invariant

Bun 1.2 Worker MessagePort Zero-Copy Structured-Cloning Transfer Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict zero-copy memory transfers across Bun 1.2 multi-threaded Worker contexts via MessagePort and Web Worker APIs. Guarantees linear memory ownership transfer using Transferable ArrayBuffer instances, preventing severe serialization latency, GC pressure, and race conditions on detached memory buffers. 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-Clone Payload Duplication and Post-Transfer Mutation of Detached Buffers 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-Clone Payload Duplication and Post-Transfer Mutation of Detached BuffersCritical
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 raw underlying ArrayBuffer (e.g., `uint8Array.buffer`) in the transfer list parameter of `worker.postMessage` or `port.postMessage` for binary payloads.

Engineers MUST ALWAYS pass the raw underlying ArrayBuffer (e.g., `uint8Array.buffer`) in the transfer list parameter of `worker.postMessage` or `port.postMessage` for binary payloads.

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 TypedArray view instances (e.g., `Uint8Array`, `Float32Array`) directly within the transfer list array

Engineers MUST NOT pass TypedArray view instances (e.g., `Uint8Array`, `Float32Array`) directly within the transfer list array; transfer lists accept only Transferable primitives (`ArrayBuffer`, `MessagePort`, `ReadableStream`, `WritableStream`).

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 treat transferred buffers as detached immediately post-dispatch

Code MUST treat transferred buffers as detached immediately post-dispatch; any read/write access to detached memory (`byteLength === 0` or `.detached === true`) MUST be prohibited and treated as a fatal invariant violation.

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 explicitly manage `MessagePort` lifecycles by executing `port.close()` and Worker `worker.terminate()` upon task completion or error states to avoid thread handles and memory descriptor leaks in Bun's runtime.

Services MUST explicitly manage `MessagePort` lifecycles by executing `port.close()` and Worker `worker.terminate()` upon task completion or error states to avoid thread handles and memory descriptor leaks in Bun's runtime.

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 fall back to JSON serialization or deep structured-cloning over Worker boundaries for compute payloads exceeding 64 KiB.

Components NEVER fall back to JSON serialization or deep structured-cloning over Worker boundaries for compute payloads exceeding 64 KiB.

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 MessagePort Zero-Copy Structured-Cloning Transfer Invariant critical for AI coding assistants?

Enforces strict zero-copy memory transfers across Bun 1.2 multi-threaded Worker contexts via MessagePort and Web Worker APIs. Guarantees linear memory ownership transfer using Transferable ArrayBuffer instances, preventing severe serialization latency, GC pressure, and race conditions on detached memory buffers. 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-Clone Payload Duplication and Post-Transfer Mutation of Detached Buffers) 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