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

Bun 1.2 Native TCP Direct-Buffer Socket Splicing & Zero-Copy Proxy Standard

Mandates zero-copy direct-buffer transmission across Bun 1.2 native TCP sockets in high-throughput reverse proxies and streaming gateways. Enforces bypassing JavaScript runtime heap allocations and intermediate userland memory copying during packet forwarding to guarantee sub-millisecond latencies and eliminate GC pauses.

Prohibited Anti-Pattern: Heap-Allocated Intermediate Buffers and Node-Stream Emulation in Bun Gateways

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native TCP Direct-Buffer Socket Splicing & Zero-Copy Proxy Standard - Mandates zero-copy direct-buffer transmission across Bun 1.2 native TCP sockets in high-throughput reverse proxies and streaming gateways. Enforces bypassing JavaScript runtime heap allocations and intermediate userland memory copying during packet forwarding to guarantee sub-millisecond latencies and eliminate GC pauses.
globs: src/**/*.ts, gateway/**/*.ts, proxy/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-1-2-native-socket-splice-standard"
---

# Bun 1.2 Native TCP Direct-Buffer Socket Splicing & Zero-Copy Proxy Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Heap-Allocated Intermediate Buffers and Node-Stream Emulation in Bun Gateways

## System Constraints
You are a Principal Systems Engineer and Performance Architect enforcing zero-copy networking standards in Bun 1.2+. You reject any code allocating intermediate Node.js Buffer instances, wrapping raw sockets in legacy Node Readable streams, or ignoring native socket backpressure during high-throughput proxy operations. Mandate direct zero-copy buffer forwarding and native kernel-to-kernel socket backpressure handling.

## Strict Guidelines
- Engineers MUST ALWAYS forward incoming socket chunks directly to destination sockets using Bun's native typed array view without re-wrapping in Node.js Buffer.from() or Buffer.concat().
- Engineers MUST NOT convert binary frames to intermediate JavaScript strings or allocate V8/JSC heap structures in high-frequency socket data handlers.
- Code MUST inspect the return value of socket.write(data) to detect kernel buffer saturation and respect backpressure.
- Services MUST implement native drain(socket) lifecycle hooks to resume upstream socket ingestion when kernel buffers clear, avoiding unconstrained memory inflation.
- Components NEVER bridge Bun native sockets (Bun.listen / Bun.connect) through Node.js node:stream or node:net compatibility wrappers when constructing throughput-critical proxies.
- Engineers MUST leverage the socket.data context property to correlate ingress and egress TCP socket pairs to prevent closure-based memory leaks.

## Bad vs Good Implementations
### Zero-Copy TCP Proxy Splicing with Native Backpressure Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocates a new heap-allocated Node.js Buffer for every received packet, instantiates short-lived Readable stream abstractions, and ignores kernel socket backpressure. This triggers massive Garbage Collector thrashing, increases tail latency, and exhausts server memory under high connection concurrency.
```typescript
import { Socket } from 'node:net';
import { Readable } from 'node:stream';

interface ProxyContext {
  upstream?: Socket;
}

// Anti-pattern: Intermediary Node streams & heap allocations per packet
Bun.listen<ProxyContext>({
  hostname: '0.0.0.0',
  port: 8080,
  socket: {
    async open(socket) {
      const upstream = new Socket();
      upstream.connect(9000, '127.0.0.1');
      socket.data = { upstream };
    },
    data(socket, chunk) {
      // CRITICAL BUG: Allocates JS Buffer copies and invokes V8 GC overhead
      const heapCopy = Buffer.from(chunk);
      const stream = Readable.from(heapCopy);
      
      if (socket.data.upstream) {
        // Ignores backpressure, pipes via Node stream layer
        stream.pipe(socket.data.upstream, { end: false });
      }
    },
    close(socket) {
      socket.data.upstream?.destroy();
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Bypasses JavaScript memory allocation entirely by forwarding the raw native Uint8Array reference directly to the target socket's native write mechanism. Backpressure is strictly controlled: if egress.write(chunk) returns false (socket buffer full), the ingress socket is immediately paused, preventing memory bloat and maintaining kernel-level splicing throughput.
```typescript
import type { TCPSocket } from 'bun';

interface IngressContext {
  egress?: TCPSocket<EgressContext>;
  paused: boolean;
}

interface EgressContext {
  ingress?: TCPSocket<IngressContext>;
}

// Production Invariant: Direct-buffer pass-through with zero userland reallocation
Bun.listen<IngressContext>({
  hostname: '0.0.0.0',
  port: 8080,
  socket: {
    async open(ingressSocket) {
      ingressSocket.data = { paused: false };
      try {
        const egressSocket = await Bun.connect<EgressContext>({
          hostname: '127.0.0.1',
          port: 9000,
          socket: {
            open(egress) {
              egress.data = { ingress: ingressSocket };
              ingressSocket.data.egress = egress;
            },
            data(egress, chunk) {
              // Forward upstream response back directly to client
              const ok = ingressSocket.write(chunk);
              if (!ok) {
                egress.pause();
              }
            },
            drain(egress) {
              ingressSocket.resume();
            },
            close(egress) {
              ingressSocket.end();
            }
          }
        });
      } catch {
        ingressSocket.end();
      }
    },
    data(ingress, chunk) {
      const egress = ingress.data.egress;
      if (!egress) return;

      // Zero-copy: Pass raw Uint8Array slice directly to kernel send buffer
      const written = egress.write(chunk);
      if (!written) {
        ingress.data.paused = true;
        ingress.pause();
      }
    },
    drain(ingress) {
      // Resume egress reading when client consumer absorbs pending bytes
      ingress.data.egress?.resume();
    },
    close(ingress) {
      ingress.data.egress?.end();
    }
  }
});
```

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 TCP Direct-Buffer Socket Splicing & Zero-Copy Proxy Standard

Bun 1.2 Native TCP Direct-Buffer Socket Splicing & Zero-Copy Proxy Standard defines an industrial-grade behavioral standard for backend engineering. Mandates zero-copy direct-buffer transmission across Bun 1.2 native TCP sockets in high-throughput reverse proxies and streaming gateways. Enforces bypassing JavaScript runtime heap allocations and intermediate userland memory copying during packet forwarding to guarantee sub-millisecond latencies and eliminate GC pauses. 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: Heap-Allocated Intermediate Buffers and Node-Stream Emulation in Bun Gateways 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 DriftHeap-Allocated Intermediate Buffers and Node-Stream Emulation in Bun GatewaysCritical
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 forward incoming socket chunks directly to destination sockets using Bun's native typed array view without re-wrapping in Node.js Buffer.from() or Buffer.concat().

Engineers MUST ALWAYS forward incoming socket chunks directly to destination sockets using Bun's native typed array view without re-wrapping in Node.js Buffer.from() or Buffer.concat().

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 convert binary frames to intermediate JavaScript strings or allocate V8/JSC heap structures in high-frequency socket data handlers.

Engineers MUST NOT convert binary frames to intermediate JavaScript strings or allocate V8/JSC heap structures in high-frequency socket data handlers.

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 inspect the return value of socket.write(data) to detect kernel buffer saturation and respect backpressure.

Code MUST inspect the return value of socket.write(data) to detect kernel buffer saturation and respect backpressure.

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 implement native drain(socket) lifecycle hooks to resume upstream socket ingestion when kernel buffers clear, avoiding unconstrained memory inflation.

Services MUST implement native drain(socket) lifecycle hooks to resume upstream socket ingestion when kernel buffers clear, avoiding unconstrained memory inflation.

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 Bun native sockets (Bun.listen / Bun.connect) through Node.js node

Components NEVER bridge Bun native sockets (Bun.listen / Bun.connect) through Node.js node:stream or node:net compatibility wrappers when constructing throughput-critical proxies.

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.
6

Engineers MUST leverage the socket.data context property to correlate ingress and egress TCP socket pairs to prevent closure-based memory leaks.

Engineers MUST leverage the socket.data context property to correlate ingress and egress TCP socket pairs to prevent closure-based memory leaks.

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 TCP Direct-Buffer Socket Splicing & Zero-Copy Proxy Standard critical for AI coding assistants?

Mandates zero-copy direct-buffer transmission across Bun 1.2 native TCP sockets in high-throughput reverse proxies and streaming gateways. Enforces bypassing JavaScript runtime heap allocations and intermediate userland memory copying during packet forwarding to guarantee sub-millisecond latencies and eliminate GC pauses. 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 (Heap-Allocated Intermediate Buffers and Node-Stream Emulation in Bun Gateways) 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