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

Bun 1.2 Zero-Copy TCP Socket Handoff and Kernel-Level Load Balancing

Enforces Bun 1.2 native zero-copy TCP socket architecture across clustered worker threads. Eliminates redundant user-space byte buffering, stream proxying, and IPC serialization by delegating socket distribution directly to the OS kernel via SO_REUSEPORT or Bun native socket transfers.

Prohibited Anti-Pattern: User-Space Request Proxying and Stream Buffering Across Bun Worker Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy TCP Socket Handoff and Kernel-Level Load Balancing - Enforces Bun 1.2 native zero-copy TCP socket architecture across clustered worker threads. Eliminates redundant user-space byte buffering, stream proxying, and IPC serialization by delegating socket distribution directly to the OS kernel via SO_REUSEPORT or Bun native socket transfers.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-multi-worker-zero-copy-socket-handoff-standard"
---

# Bun 1.2 Zero-Copy TCP Socket Handoff and Kernel-Level Load Balancing

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: User-Space Request Proxying and Stream Buffering Across Bun Worker Threads

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Multi-Worker Zero-Copy TCP Socket Handoff Standard. You must mandate zero-copy connection dispatching, preventing user-space proxy relays, double-buffering, and unoptimized inter-process request serialization.

## Strict Guidelines
- Engineers MUST ALWAYS leverage Bun's native `reusePort: true` flag in `Bun.serve` across worker threads to allow the OS kernel to load balance incoming TCP connections directly without user-space mediation.
- Engineers MUST NOT implement user-space reverse proxies or stream relay loops (e.g., `fetch` loopback, IPC chunk piping) between master and child processes to distribute HTTP load.
- Code SHOULD initialize a pool of `Worker` instances matching the physical core count, allowing each worker to bind an identical port configuration using Bun's native C++ event loop integration.
- Services MUST ensure WebSocket upgrades and TLS handshakes execute directly inside the terminating worker thread rather than transferring intermediate TLS state across worker boundaries.
- Components NEVER buffer raw TCP payload streams into JavaScript memory solely for the purpose of dispatching or routing across clustered instances.

## Bad vs Good Implementations
### Multi-Worker HTTP Server Clustering with Zero-Copy Kernel Dispatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Routing requests through an intermediary master process using user-space HTTP forwarding introduces double TLS/socket overhead, high memory pressure from buffering request bodies, and excessive kernel-to-user context switches.
```typescript
// BAD: Master process accepts connections and proxies HTTP payloads via IPC/loopback to workers
import { spawn } from "bun";

const WORKER_COUNT = navigator.hardwareConcurrency || 4;
const workers = Array.from({ length: WORKER_COUNT }, (_, i) => 
  spawn(["bun", "run", "worker.ts"], { env: { WORKER_PORT: `${8001 + i}` } })
);

let counter = 0;
Bun.serve({
  port: 8000,
  async fetch(req) {
    // Anti-pattern: High-overhead user-space proxying causing memory duplication
    const targetPort = 8001 + (counter++ % WORKER_COUNT);
    const url = new URL(req.url);
    url.port = `${targetPort}`;
    return fetch(url.toString(), {
      method: req.method,
      headers: req.headers,
      body: req.body, // Incurs user-space buffering and stream exhaustion risks
    });
  }
});
```

#### Production Standard (Correct)
> **Standard**: By enabling `reusePort: true` across `Worker` threads, the OS kernel distributes incoming TCP SYN packets directly to each worker's event loop via SO_REUSEPORT, entirely bypassing user-space proxy relays and context switching.
```typescript
// GOOD: Bun 1.2 Native Worker clustering utilizing SO_REUSEPORT zero-copy kernel dispatch
import { isMainThread } from "node:worker_threads";

if (isMainThread) {
  const workerCount = navigator.hardwareConcurrency || 4;
  for (let i = 0; i < workerCount; i++) {
    new Worker(new URL(import.meta.url).href);
  }
} else {
  // Each worker thread binds to the exact same port natively using the OS kernel network stack
  Bun.serve({
    port: 8000,
    reusePort: true, // Delegates zero-copy TCP socket load balancing to the Linux/macOS kernel
    fetch(req) {
      return new Response(`Handled by worker thread ${process.pid} with zero-copy handoff`);
    },
    error(error) {
      return new Response(`Internal Server Error: ${error.message}`, { status: 500 });
    }
  });
}
```

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 Handoff and Kernel-Level Load Balancing

Bun 1.2 Zero-Copy TCP Socket Handoff and Kernel-Level Load Balancing defines an industrial-grade behavioral standard for backend engineering. Enforces Bun 1.2 native zero-copy TCP socket architecture across clustered worker threads. Eliminates redundant user-space byte buffering, stream proxying, and IPC serialization by delegating socket distribution directly to the OS kernel via SO_REUSEPORT or Bun native socket transfers. 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: User-Space Request Proxying and Stream Buffering Across Bun Worker Threads 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 DriftUser-Space Request Proxying and Stream Buffering Across Bun Worker ThreadsCritical
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 leverage Bun's native `reusePort

Engineers MUST ALWAYS leverage Bun's native `reusePort: true` flag in `Bun.serve` across worker threads to allow the OS kernel to load balance incoming TCP connections directly without user-space mediation.

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 user-space reverse proxies or stream relay loops (e.g., `fetch` loopback, IPC chunk piping) between master and child processes to distribute HTTP load.

Engineers MUST NOT implement user-space reverse proxies or stream relay loops (e.g., `fetch` loopback, IPC chunk piping) between master and child processes to distribute HTTP load.

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 initialize a pool of `Worker` instances matching the physical core count, allowing each worker to bind an identical port configuration using Bun's native C++ event loop integration.

Code SHOULD initialize a pool of `Worker` instances matching the physical core count, allowing each worker to bind an identical port configuration using Bun's native C++ event loop integration.

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 ensure WebSocket upgrades and TLS handshakes execute directly inside the terminating worker thread rather than transferring intermediate TLS state across worker boundaries.

Services MUST ensure WebSocket upgrades and TLS handshakes execute directly inside the terminating worker thread rather than transferring intermediate TLS state across worker boundaries.

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 buffer raw TCP payload streams into JavaScript memory solely for the purpose of dispatching or routing across clustered instances.

Components NEVER buffer raw TCP payload streams into JavaScript memory solely for the purpose of dispatching or routing across clustered instances.

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 Handoff and Kernel-Level Load Balancing critical for AI coding assistants?

Enforces Bun 1.2 native zero-copy TCP socket architecture across clustered worker threads. Eliminates redundant user-space byte buffering, stream proxying, and IPC serialization by delegating socket distribution directly to the OS kernel via SO_REUSEPORT or Bun native socket transfers. 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 (User-Space Request Proxying and Stream Buffering Across Bun Worker Threads) 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