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

Bun 1.2 Zero-Copy TCP Socket Splice Pipeline Invariant

Mandates kernel-level zero-copy TCP socket piping in Bun edge proxy gateways to prevent userspace buffer allocations and JavaScript heap thrashing. Enforces direct socket pipe chaining over manual chunk aggregation in event listeners to maintain high-throughput kernel splicing.

Prohibited Anti-Pattern: Userspace Buffer Intermediation in Proxy Sockets Inducing High GC Pressure and Kernel Transition Overhead

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy TCP Socket Splice Pipeline Invariant - Mandates kernel-level zero-copy TCP socket piping in Bun edge proxy gateways to prevent userspace buffer allocations and JavaScript heap thrashing. Enforces direct socket pipe chaining over manual chunk aggregation in event listeners to maintain high-throughput kernel splicing.
globs: src/**/*.ts, gateway/**/*.ts, proxy/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-socket-splice-invariant"
---

# Bun 1.2 Zero-Copy TCP Socket Splice Pipeline Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Userspace Buffer Intermediation in Proxy Sockets Inducing High GC Pressure and Kernel Transition Overhead

## System Constraints
You are a Principal Systems Architect enforcing Bun 1.2 Zero-Copy TCP Socket Splice Pipeline Invariants. You must strictly forbid any manual data-buffering proxies in userspace and mandate native duplex socket piping to ensure OS kernel splice operations remain unbroken.

## Strict Guidelines
- Engineers MUST ALWAYS connect source and destination sockets using native `socket.pipe(destSocket)` to enable OS-level `splice(2)` or zero-copy ring buffers.
- Engineers MUST NOT implement `data(socket, chunk)` callbacks to manually re-emit bytes via `destination.write(chunk)` in proxy or gateway layers.
- Code SHOULD enforce bidirectional lifecycle termination handling by pairing `pipe()` with corresponding `close` and `error` tear-down handlers across both peers.
- Services MUST omit userspace byte-counting or payload inspection in streaming hot paths unless explicitly isolated to separate tracing channels.
- Components NEVER bridge raw TCP streams using intermediate Node.js `stream.PassThrough` or async iterator loops when running on the Bun runtime.

## Bad vs Good Implementations
### Raw TCP Proxy Socket Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring `data()` event handlers forces Bun to allocate `Uint8Array` objects in the JavaScript heap for every TCP chunk, context-switching between the kernel and userspace and completely disabling zero-copy kernel splicing (`splice(2)` on Linux).
```typescript
import { listen, connect, type Socket } from "bun";

interface ProxyState {
  upstream?: Socket<unknown>;
}

listen<ProxyState>({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    async open(client) {
      const upstream = await connect({
        hostname: "upstream.internal",
        port: 9000,
        socket: {
          data(up, buffer) {
            // Anti-pattern: forces userspace memory allocation and heap thrashing
            client.write(buffer);
          },
        },
      });
      client.data = { upstream };
    },
    data(client, buffer) {
      // Anti-pattern: roundtrips through JavaScript runtime context
      client.data.upstream?.write(buffer);
    },
    error(client, error) {
      console.error(error);
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: By explicitly chaining `client.pipe(up)` and `up.pipe(client)` and omitting the `data` callback, Bun delegates packet routing directly to the operating system's zero-copy pipeline, eliminating heap allocations, V8/JSC GC pauses, and userspace context switching.
```typescript
import { listen, connect, type Socket } from "bun";

interface ProxyContext {
  upstream?: Socket<unknown>;
}

listen<ProxyContext>({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    async open(client) {
      try {
        const upstream = await connect({
          hostname: "upstream.internal",
          port: 9000,
          socket: {
            open(up) {
              // Invariant: Direct pipe splicing enables zero-copy kernel forwarding
              client.pipe(up);
              up.pipe(client);
            },
            close(up) {
              client.end();
            },
            error(up, err) {
              client.terminate();
            },
          },
        });
        client.data = { upstream };
      } catch {
        client.terminate();
      }
    },
    // Invariant: Omit `data` handler entirely to bypass JS heap allocations
    close(client) {
      client.data?.upstream?.end();
    },
    error(client, err) {
      client.data?.upstream?.terminate();
    },
  },
});
```

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 Zero-Copy TCP Socket Splice Pipeline Invariant

Bun 1.2 Zero-Copy TCP Socket Splice Pipeline Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates kernel-level zero-copy TCP socket piping in Bun edge proxy gateways to prevent userspace buffer allocations and JavaScript heap thrashing. Enforces direct socket pipe chaining over manual chunk aggregation in event listeners to maintain high-throughput kernel splicing. 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: Userspace Buffer Intermediation in Proxy Sockets Inducing High GC Pressure and Kernel Transition Overhead 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 DriftUserspace Buffer Intermediation in Proxy Sockets Inducing High GC Pressure and Kernel Transition OverheadCritical
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 connect source and destination sockets using native `socket.pipe(destSocket)` to enable OS-level `splice(2)` or zero-copy ring buffers.

Engineers MUST ALWAYS connect source and destination sockets using native `socket.pipe(destSocket)` to enable OS-level `splice(2)` or zero-copy ring buffers.

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 implement `data(socket, chunk)` callbacks to manually re-emit bytes via `destination.write(chunk)` in proxy or gateway layers.

Engineers MUST NOT implement `data(socket, chunk)` callbacks to manually re-emit bytes via `destination.write(chunk)` in proxy or gateway layers.

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 enforce bidirectional lifecycle termination handling by pairing `pipe()` with corresponding `close` and `error` tear-down handlers across both peers.

Code SHOULD enforce bidirectional lifecycle termination handling by pairing `pipe()` with corresponding `close` and `error` tear-down handlers across both peers.

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 omit userspace byte-counting or payload inspection in streaming hot paths unless explicitly isolated to separate tracing channels.

Services MUST omit userspace byte-counting or payload inspection in streaming hot paths unless explicitly isolated to separate tracing channels.

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 bridge raw TCP streams using intermediate Node.js `stream.PassThrough` or async iterator loops when running on the Bun runtime.

Components NEVER bridge raw TCP streams using intermediate Node.js `stream.PassThrough` or async iterator loops when running on the Bun 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.
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 Zero-Copy TCP Socket Splice Pipeline Invariant critical for AI coding assistants?

Mandates kernel-level zero-copy TCP socket piping in Bun edge proxy gateways to prevent userspace buffer allocations and JavaScript heap thrashing. Enforces direct socket pipe chaining over manual chunk aggregation in event listeners to maintain high-throughput kernel splicing. 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 (Userspace Buffer Intermediation in Proxy Sockets Inducing High GC Pressure and Kernel Transition Overhead) 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