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

Bun 1.2 Native Socket Zero-Copy Pipe Lifetime Guardrail

Enforces strict buffer lifecycle ownership and backpressure synchronization when using Bun 1.2 native TCP sockets with zero-copy stream transformations. Eliminates use-after-free conditions and memory corruption caused by referencing internal socket slab buffers after async ticks or uncoordinated pipe drains.

Prohibited Anti-Pattern: Retaining or Mutating Kernel-Mapped Slab Buffers Across Microtask Boundaries During Native Pipe Transfers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Socket Zero-Copy Pipe Lifetime Guardrail - Enforces strict buffer lifecycle ownership and backpressure synchronization when using Bun 1.2 native TCP sockets with zero-copy stream transformations. Eliminates use-after-free conditions and memory corruption caused by referencing internal socket slab buffers after async ticks or uncoordinated pipe drains.
globs: src/**/*.ts, server/**/*.ts, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-socket-zero-copy-lifetime-guardrail"
---

# Bun 1.2 Native Socket Zero-Copy Pipe Lifetime Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining or Mutating Kernel-Mapped Slab Buffers Across Microtask Boundaries During Native Pipe Transfers

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Native Socket Zero-Copy Pipe Lifetime Guardrail. Mandate strict memory ownership boundaries during native TCP socket data piping, transform streaming, and backpressure handling. Prevent buffer reuse collisions, stale slab references, and uncoordinated socket write queue bloat.

## Strict Guidelines
- Engineers MUST ALWAYS clone or slice-copy incoming socket Uint8Array buffers if processing spans across asynchronous boundaries or microtask ticks.
- Engineers MUST NOT retain direct references to socket `data(socket, data)` buffers once the synchronous callback execution returns.
- Code MUST strictly monitor `socket.write()` return codes and defer subsequent zero-copy piping until the `drain(socket)` lifecycle hook fires when write buffers are full.
- Services MUST explicitly unpipe and terminate transform stream pipelines using `socket.ref()` and `socket.unref()` lifecycle bindings to avoid dangling native handles.
- Components NEVER assume socket-provided Uint8Array memory addresses remain immutable across successive read events on the same TCP connection.

## Bad vs Good Implementations
### Preventing Use-After-Free in Bun Native Socket Data Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Bun reuses native slab memory for sequential socket read events. Passing `data` directly into an asynchronous context (`queueMicrotask`, `async/await`, or event loops) results in race conditions where subsequent network packets overwrite the buffer contents before processing completes, causing silent data corruption and use-after-free memory traps.
```typescript
import { listen } from "bun";

listen({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    data(socket, data) {
      // CRITICAL BUG: `data` points to Bun's reusable internal slab buffer.
      // Holding reference across async boundary leads to data corruption or use-after-free.
      queueMicrotask(async () => {
        await processPayload(data);
        socket.write(data);
      });
    },
  },
});

async function processPayload(buf: Uint8Array) {
  // Processing asynchronously while Bun reclaims the underlying native memory
  await Bun.sleep(10);
}
```

#### Production Standard (Correct)
> **Standard**: The invariant is satisfied by copying the data payload into an isolated `Uint8Array` before scheduling asynchronous work. Furthermore, backpressure is formally tracked via the `drain` lifecycle hook to avoid kernel buffer exhaustion when writing transformed streams back into the native socket.
```typescript
import { listen, type Socket } from "bun";

interface SocketState {
  isDraining: boolean;
  pendingWrites: Uint8Array[];
}

listen<SocketState>({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    open(socket) {
      socket.data = { isDraining: false, pendingWrites: [] };
    },
    data(socket, data) {
      // INVARIANT: Synchronously duplicate native buffer if escaping the callback lifetime
      const ownedBuffer = new Uint8Array(data.byteLength);
      ownedBuffer.set(data);

      void handlePacket(socket, ownedBuffer);
    },
    drain(socket) {
      socket.data.isDraining = false;
      while (socket.data.pendingWrites.length > 0) {
        const chunk = socket.data.pendingWrites.shift()!;
        const flushed = socket.write(chunk);
        if (!flushed) {
          socket.data.isDraining = true;
          break;
        }
      }
    },
  },
});

async function handlePacket(socket: Socket<SocketState>, chunk: Uint8Array): Promise<void> {
  const transformed = await applyTransform(chunk);
  
  if (socket.data.isDraining) {
    socket.data.pendingWrites.push(transformed);
    return;
  }

  const flushed = socket.write(transformed);
  if (!flushed) {
    socket.data.isDraining = true;
  }
}

async function applyTransform(chunk: Uint8Array): Promise<Uint8Array> {
  // Safe asynchronous operations on exclusively owned buffer
  await Bun.sleep(1);
  return chunk;
}
```

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 Native Socket Zero-Copy Pipe Lifetime Guardrail

Bun 1.2 Native Socket Zero-Copy Pipe Lifetime Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict buffer lifecycle ownership and backpressure synchronization when using Bun 1.2 native TCP sockets with zero-copy stream transformations. Eliminates use-after-free conditions and memory corruption caused by referencing internal socket slab buffers after async ticks or uncoordinated pipe drains. 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 or Mutating Kernel-Mapped Slab Buffers Across Microtask Boundaries During Native Pipe Transfers 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 or Mutating Kernel-Mapped Slab Buffers Across Microtask Boundaries During Native Pipe TransfersCritical
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 clone or slice-copy incoming socket Uint8Array buffers if processing spans across asynchronous boundaries or microtask ticks.

Engineers MUST ALWAYS clone or slice-copy incoming socket Uint8Array buffers if processing spans across asynchronous boundaries or microtask ticks.

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 retain direct references to socket `data(socket, data)` buffers once the synchronous callback execution returns.

Engineers MUST NOT retain direct references to socket `data(socket, data)` buffers once the synchronous callback execution returns.

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 strictly monitor `socket.write()` return codes and defer subsequent zero-copy piping until the `drain(socket)` lifecycle hook fires when write buffers are full.

Code MUST strictly monitor `socket.write()` return codes and defer subsequent zero-copy piping until the `drain(socket)` lifecycle hook fires when write buffers are full.

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 unpipe and terminate transform stream pipelines using `socket.ref()` and `socket.unref()` lifecycle bindings to avoid dangling native handles.

Services MUST explicitly unpipe and terminate transform stream pipelines using `socket.ref()` and `socket.unref()` lifecycle bindings to avoid dangling native handles.

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 assume socket-provided Uint8Array memory addresses remain immutable across successive read events on the same TCP connection.

Components NEVER assume socket-provided Uint8Array memory addresses remain immutable across successive read events on the same TCP connection.

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 Socket Zero-Copy Pipe Lifetime Guardrail critical for AI coding assistants?

Enforces strict buffer lifecycle ownership and backpressure synchronization when using Bun 1.2 native TCP sockets with zero-copy stream transformations. Eliminates use-after-free conditions and memory corruption caused by referencing internal socket slab buffers after async ticks or uncoordinated pipe drains. 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 or Mutating Kernel-Mapped Slab Buffers Across Microtask Boundaries During Native Pipe Transfers) 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