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

Bun 1.2 Zero-Copy Kernel-Space TCP Streaming Standard

Mandates direct kernel-space streaming transfers for high-volume binary payloads using Bun.listen and Bun.connect. Enforces strict zero-copy descriptor offloading (via sendfile/copy_file_range) to bypass JavaScriptCore heap allocation and eliminate garbage collection thrashing under 100k+ concurrent connections.

Prohibited Anti-Pattern: Userland Heap Buffering and Intermediate ArrayBuffer Allocations in High-Throughput TCP Sockets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy Kernel-Space TCP Streaming Standard - Mandates direct kernel-space streaming transfers for high-volume binary payloads using Bun.listen and Bun.connect. Enforces strict zero-copy descriptor offloading (via sendfile/copy_file_range) to bypass JavaScriptCore heap allocation and eliminate garbage collection thrashing under 100k+ concurrent connections.
globs: src/**/*.ts, server/**/*.ts, lib/net/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-tcp-pipeline-production-standard"
---

# Bun 1.2 Zero-Copy Kernel-Space TCP Streaming Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Userland Heap Buffering and Intermediate ArrayBuffer Allocations in High-Throughput TCP Sockets

## System Constraints
You are a Principal Software Architect enforcing Bun 1.2 zero-copy networking invariants. Reject any socket implementations that convert high-volume payloads into JavaScript heap allocations (such as ArrayBuffer, Uint8Array, or node:buffer instances) on the data path. Mandate zero-copy file-to-socket transfers using BunFile handles, strict backpressure handling via drain hooks, and direct kernel-space descriptor piping.

## Strict Guidelines
- Engineers MUST ALWAYS pass `BunFile` handles directly to `socket.write()` or use `socket.pipe()` to trigger OS-level `sendfile(2)` and bypass the JavaScriptCore heap entirely.
- Engineers MUST NOT call `.arrayBuffer()`, `.bytes()`, or `.text()` on file handles or streams before writing to a `TCPSocket` in high-throughput hot paths.
- Code MUST evaluate the byte count returned by `socket.write()` to detect kernel send-buffer saturation and register `drain` socket handlers for deferred backpressure resolution.
- Services MUST enable socket pooling, set appropriate receive/send buffer sizes (`SO_RCVBUF`/`SO_SNDBUF`), and verify non-blocking write semantics under 100k+ concurrent connection limits.
- Components NEVER store pending payload chunks in intermediate JavaScript array buffers or string accumulators during backpressure.

## Bad vs Good Implementations
### Zero-Copy TCP File Transmission vs JSC Heap Materialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Materializing binary data via file.arrayBuffer() and Buffer.from() forces kernel data into userland JSC memory. Under 100k concurrent connections, concurrent allocations saturate the JavaScriptCore GC, causing stop-the-world pauses and eventual OOM crashes.
```typescript
import { listen } from "bun";

listen({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    async data(socket) {
      const file = Bun.file("/var/data/payload.bin");
      // CRITICAL: Pulls massive binary file into JSC heap memory
      const buffer = await file.arrayBuffer();
      const chunk = Buffer.from(buffer);
      // Redundant userland copy causes extreme GC thrashing under 100k conns
      socket.write(chunk);
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Passing Bun.file directly to socket.write() enables Bun 1.2 to execute a direct kernel-to-socket transfer via sendfile(2). Zero bytes are allocated on the JavaScript heap, memory usage remains flat, and backpressure is safely coordinated through the drain hook.
```typescript
import { listen, type TCPSocket } from "bun";

interface SocketState {
  pendingFile?: ReturnType<typeof Bun.file>;
}

listen<SocketState>({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    data(socket: TCPSocket<SocketState>) {
      const file = Bun.file("/var/data/payload.bin");
      // Zero-copy: Bun offloads transmission directly to the OS kernel via sendfile(2)
      const written = socket.write(file);

      // Backpressure invariant: Handle partial writes without allocating heap buffers
      if (written < file.size) {
        socket.data = { pendingFile: file };
      }
    },
    drain(socket: TCPSocket<SocketState>) {
      if (socket.data?.pendingFile) {
        const written = socket.write(socket.data.pendingFile);
        if (written >= socket.data.pendingFile.size) {
          socket.data.pendingFile = undefined;
        }
      }
    },
    error(socket: TCPSocket<SocketState>, error: Error) {
      socket.data = {};
      socket.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 Zero-Copy Kernel-Space TCP Streaming Standard

Bun 1.2 Zero-Copy Kernel-Space TCP Streaming Standard defines an industrial-grade behavioral standard for backend engineering. Mandates direct kernel-space streaming transfers for high-volume binary payloads using Bun.listen and Bun.connect. Enforces strict zero-copy descriptor offloading (via sendfile/copy_file_range) to bypass JavaScriptCore heap allocation and eliminate garbage collection thrashing under 100k+ concurrent connections. 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: Userland Heap Buffering and Intermediate ArrayBuffer Allocations in High-Throughput TCP Sockets 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 DriftUserland Heap Buffering and Intermediate ArrayBuffer Allocations in High-Throughput TCP SocketsCritical
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 `BunFile` handles directly to `socket.write()` or use `socket.pipe()` to trigger OS-level `sendfile(2)` and bypass the JavaScriptCore heap entirely.

Engineers MUST ALWAYS pass `BunFile` handles directly to `socket.write()` or use `socket.pipe()` to trigger OS-level `sendfile(2)` and bypass the JavaScriptCore heap entirely.

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 call `.arrayBuffer()`, `.bytes()`, or `.text()` on file handles or streams before writing to a `TCPSocket` in high-throughput hot paths.

Engineers MUST NOT call `.arrayBuffer()`, `.bytes()`, or `.text()` on file handles or streams before writing to a `TCPSocket` in high-throughput hot paths.

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 evaluate the byte count returned by `socket.write()` to detect kernel send-buffer saturation and register `drain` socket handlers for deferred backpressure resolution.

Code MUST evaluate the byte count returned by `socket.write()` to detect kernel send-buffer saturation and register `drain` socket handlers for deferred backpressure resolution.

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 enable socket pooling, set appropriate receive/send buffer sizes (`SO_RCVBUF`/`SO_SNDBUF`), and verify non-blocking write semantics under 100k+ concurrent connection limits.

Services MUST enable socket pooling, set appropriate receive/send buffer sizes (`SO_RCVBUF`/`SO_SNDBUF`), and verify non-blocking write semantics under 100k+ concurrent connection limits.

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 store pending payload chunks in intermediate JavaScript array buffers or string accumulators during backpressure.

Components NEVER store pending payload chunks in intermediate JavaScript array buffers or string accumulators during 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.
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 Kernel-Space TCP Streaming Standard critical for AI coding assistants?

Mandates direct kernel-space streaming transfers for high-volume binary payloads using Bun.listen and Bun.connect. Enforces strict zero-copy descriptor offloading (via sendfile/copy_file_range) to bypass JavaScriptCore heap allocation and eliminate garbage collection thrashing under 100k+ concurrent connections. 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 (Userland Heap Buffering and Intermediate ArrayBuffer Allocations in High-Throughput TCP Sockets) 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