This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-serve-zero-copy-socket-buffer-ownership-invariant

Bun 1.2 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant

Bun's high-throughput I/O engine relies on native C++ socket ring buffers for HTTP/1.1, HTTP/2, and HTTP/3 streaming payloads. When consuming chunked streams via Bun.serve(), references to zero-copy Uint8Array views must not outlive the native reader lifecycle without explicit memory ownership transfer. Retaining or queueing raw borrowed views across microtask turns results in silent memory corruption or native use-after-free crashes.

Prohibited Anti-Pattern: Retaining borrowed native socket views across asynchronous boundaries without explicit buffer detachment or memory copying.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant - Bun's high-throughput I/O engine relies on native C++ socket ring buffers for HTTP/1.1, HTTP/2, and HTTP/3 streaming payloads. When consuming chunked streams via Bun.serve(), references to zero-copy Uint8Array views must not outlive the native reader lifecycle without explicit memory ownership transfer. Retaining or queueing raw borrowed views across microtask turns results in silent memory corruption or native use-after-free crashes.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-serve-zero-copy-socket-buffer-ownership-invariant"
---

# Bun 1.2 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining borrowed native socket views across asynchronous boundaries without explicit buffer detachment or memory copying.

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant. Mandate strict transfer-of-ownership semantics on native C++ socket buffers to prevent use-after-free corruption during high-throughput HTTP/3 streaming payloads in JavaScript runtimes. Every stream chunk yielded from Bun native readers aliases unmanaged C++ memory; any persistence across asynchronous yields requires explicit decoupling.

## Strict Guidelines
- Engineers MUST ALWAYS decouple stream chunks via Uint8Array.prototype.slice() before retaining them across any asynchronous boundary (e.g., await, microtask queue, or channel push).
- Engineers MUST NOT push raw Uint8Array views directly yielded from req.body.getReader().read() into long-lived memory structures, caches, or persistent queues.
- Code SHOULD utilize req.bytes() or req.arrayBuffer() when the entire payload is needed upfront, delegating lifecycle management to Bun's native runtime.
- Services MUST explicitly transfer underlying ArrayBuffers using Transferable Objects when offloading streaming socket payloads to Web Workers.
- Components NEVER mutate or perform direct byte-level aliasing on zero-copy chunks during an ongoing read loop without creating an independent copy.

## Bad vs Good Implementations
### Decoupling Borrowed Native Socket Buffers in Streaming Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The 'value' Uint8Array aliases native C++ socket ring-buffer memory. Holding this view across the 'await flushBatch(value)' yield point allows Bun to recycle or free the underlying buffer on subsequent native reads, corrupting the queued payload.
```typescript
import { serve } from "bun";

const pendingBatches: Uint8Array[] = [];

async function flushBatch(chunk: Uint8Array): Promise<void> {
  await Bun.sleep(10);
  console.log(`Flushed ${chunk.byteLength} bytes`);
}

serve({
  port: 3000,
  async fetch(req) {
    if (!req.body) return new Response("No body", { status: 400 });
    const reader = req.body.getReader();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      // VULNERABILITY: 'value' aliases the native C++ socket ring buffer.
      // Passing it across an async boundary or queuing it causes use-after-free
      // and data corruption as the ring buffer advances in subsequent read loops.
      pendingBatches.push(value);
      await flushBatch(value);
    }

    return new Response("Processed");
  },
});
```

#### Production Standard (Correct)
> **Standard**: Invoking .slice() allocates a newly owned JavaScriptCore ArrayBuffer, detaching the payload from the native C++ socket ring buffer and eliminating the risk of use-after-free corruption across asynchronous ticks.
```typescript
import { serve } from "bun";

const pendingBatches: Uint8Array[] = [];

async function flushBatch(chunk: Uint8Array): Promise<void> {
  await Bun.sleep(10);
  console.log(`Flushed ${chunk.byteLength} bytes`);
}

serve({
  port: 3000,
  async fetch(req) {
    if (!req.body) return new Response("No body", { status: 400 });
    const reader = req.body.getReader();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      // INVARIANT: Explicitly clone the native memory view via .slice().
      // This transfers ownership to a safe, runtime-managed JavaScriptCore ArrayBuffer.
      const detachedChunk = value.slice();
      pendingBatches.push(detachedChunk);
      await flushBatch(detachedChunk);
    }

    return new Response("Processed");
  },
});
```

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 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant

Bun 1.2 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant defines an industrial-grade behavioral standard for backend engineering. Bun's high-throughput I/O engine relies on native C++ socket ring buffers for HTTP/1.1, HTTP/2, and HTTP/3 streaming payloads. When consuming chunked streams via Bun.serve(), references to zero-copy Uint8Array views must not outlive the native reader lifecycle without explicit memory ownership transfer. Retaining or queueing raw borrowed views across microtask turns results in silent memory corruption or native use-after-free crashes. 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: Retaining borrowed native socket views across asynchronous boundaries without explicit buffer detachment or memory copying. 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 DriftRetaining borrowed native socket views across asynchronous boundaries without explicit buffer detachment or memory copying.Critical
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 decouple stream chunks via Uint8Array.prototype.slice() before retaining them across any asynchronous boundary (e.g., await, microtask queue, or channel push).

Engineers MUST ALWAYS decouple stream chunks via Uint8Array.prototype.slice() before retaining them across any asynchronous boundary (e.g., await, microtask queue, or channel push).

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 push raw Uint8Array views directly yielded from req.body.getReader().read() into long-lived memory structures, caches, or persistent queues.

Engineers MUST NOT push raw Uint8Array views directly yielded from req.body.getReader().read() into long-lived memory structures, caches, or persistent queues.

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 utilize req.bytes() or req.arrayBuffer() when the entire payload is needed upfront, delegating lifecycle management to Bun's native runtime.

Code SHOULD utilize req.bytes() or req.arrayBuffer() when the entire payload is needed upfront, delegating lifecycle management to Bun's native 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.
4

Services MUST explicitly transfer underlying ArrayBuffers using Transferable Objects when offloading streaming socket payloads to Web Workers.

Services MUST explicitly transfer underlying ArrayBuffers using Transferable Objects when offloading streaming socket payloads to Web Workers.

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 mutate or perform direct byte-level aliasing on zero-copy chunks during an ongoing read loop without creating an independent copy.

Components NEVER mutate or perform direct byte-level aliasing on zero-copy chunks during an ongoing read loop without creating an independent copy.

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 Bun.serve() Zero-Copy Socket Buffer Ownership Invariant critical for AI coding assistants?

Bun's high-throughput I/O engine relies on native C++ socket ring buffers for HTTP/1.1, HTTP/2, and HTTP/3 streaming payloads. When consuming chunked streams via Bun.serve(), references to zero-copy Uint8Array views must not outlive the native reader lifecycle without explicit memory ownership transfer. Retaining or queueing raw borrowed views across microtask turns results in silent memory corruption or native use-after-free crashes. 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 (Retaining borrowed native socket views across asynchronous boundaries without explicit buffer detachment or memory copying.) 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