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

Bun 1.2 Zero-Copy TCP Socket Re-Binding and SO_REUSEPORT Handoff Standard

Mandates kernel-level SO_REUSEPORT socket configuration and zero-copy TCP buffer lifecycles in Bun 1.2 microservices during rolling deployments. Prevents TCP reset (RST) spikes, port-binding contention, and in-flight zero-copy buffer eviction during blue/green process replacements. Enforces non-destructive socket drainage and strict dual-process overlap until health-probe convergence.

Prohibited Anti-Pattern: EADDRINUSE collisions and abruptly dropped TCP connections from premature teardown without SO_REUSEPORT socket handoffs.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy TCP Socket Re-Binding and SO_REUSEPORT Handoff Standard - Mandates kernel-level SO_REUSEPORT socket configuration and zero-copy TCP buffer lifecycles in Bun 1.2 microservices during rolling deployments. Prevents TCP reset (RST) spikes, port-binding contention, and in-flight zero-copy buffer eviction during blue/green process replacements. Enforces non-destructive socket drainage and strict dual-process overlap until health-probe convergence.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-tcp-reuseport-handoff-standard"
---

# Bun 1.2 Zero-Copy TCP Socket Re-Binding and SO_REUSEPORT Handoff Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: EADDRINUSE collisions and abruptly dropped TCP connections from premature teardown without SO_REUSEPORT socket handoffs.

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 Native Zero-Copy TCP Socket Re-Binding Standard. You must strictly require SO_REUSEPORT kernel socket binding, zero-copy socket buffer draining, and zero-downtime graceful signal handoffs across all Bun microservices.

## Strict Guidelines
- Services MUST explicitly pass `reusePort: true` inside `Bun.listen()` or `Bun.serve()` configurations to enable kernel-level `SO_REUSEPORT` load balancing and seamless process replacement.
- Engineers MUST NOT issue unconditional `process.exit()` calls before checking active connection drain states and zero-copy socket buffer flushes.
- Services MUST implement a phased shutdown lifecycle triggered by `SIGTERM`: first stop accepting new TCP connections (`server.stop(false)` or `server.pause()`), second drain pending zero-copy writes via `socket.flush()`, and finally terminate the process after existing sockets are closed or a hard deadline expires.
- Code MUST NEVER unbind or close the primary listening socket before the replacement worker process signals successful bind and health verification.
- Engineers MUST configure kernel-level backlogs explicitly (`backlog: 1024` or higher) alongside `reusePort: true` to prevent SYN packet dropouts during burst handoffs.
- Services handling streaming zero-copy workloads MUST monitor `socket.data` reference lifecycles and ensure all slice references are consumed or copied prior to socket close.

## Bad vs Good Implementations
### Bun 1.2 Zero-Downtime SO_REUSEPORT TCP Listener Handoff

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting `reusePort: true` leads to `EADDRINUSE` failures when starting a concurrent replacement process. Terminating abruptly on `SIGTERM` via `process.exit(0)` discards kernel socket buffers and truncates in-flight TCP connections without graceful drainage.
```typescript
import { listen } from 'bun';

// ANTI-PATTERN: Default listen does not enable SO_REUSEPORT.
// Deploying a new instance will throw EADDRINUSE or force terminating
// the old process before the new one is warm, causing connection drops.
const server = listen({
  hostname: '0.0.0.0',
  port: 8080,
  socket: {
    data(socket, data) {
      socket.write(data);
    },
    open(socket) {},
    close(socket) {},
    error(socket, error) {}
  }
});

process.on('SIGTERM', () => {
  // Abrupt unbinding and hard exit cuts off in-flight zero-copy TCP writes
  server.stop();
  process.exit(0);
});
```

#### Production Standard (Correct)
> **Standard**: Uses `reusePort: true` and an explicit backlog, allowing an updated process to bind to port 8080 concurrently without downtime. On `SIGTERM`, `server.stop(false)` ceases accepting new connections while active sockets drain their TCP buffers before process termination.
```typescript
import { listen, type TCPSocketListener, type TCPSocket } from 'bun';

interface SessionState {
  inFlightWrites: number;
}

const activeSockets = new Set<TCPSocket<SessionState>>();

// PRODUCTION FIX: Enable kernel-level SO_REUSEPORT and explicit backlog
const server: TCPSocketListener<SessionState> = listen<SessionState>({
  hostname: '0.0.0.0',
  port: 8080,
  socket: {
    data(socket, data) {
      socket.data.inFlightWrites++;
      const flushed = socket.write(data);
      if (flushed) {
        socket.data.inFlightWrites--;
      }
    },
    open(socket) {
      socket.data = { inFlightWrites: 0 };
      activeSockets.add(socket);
    },
    drain(socket) {
      socket.data.inFlightWrites = 0;
    },
    close(socket) {
      activeSockets.delete(socket);
    },
    error(socket, err) {
      console.error(`Socket error: ${err.message}`);
      activeSockets.delete(socket);
    }
  },
  // Kernel-level socket sharing across concurrent replacement processes
  reusePort: true,
  backlog: 2048
});

async function gracefulHandoff(): Promise<void> {
  // Stop receiving incoming TCP connections on this PID; replacement handles new SYNs
  server.stop(false);

  const deadline = Date.now() + 15000;
  const checkDrain = async (): Promise<void> => {
    for (const socket of activeSockets) {
      if (socket.data?.inFlightWrites === 0) {
        socket.end();
      }
    }

    if (activeSockets.size === 0 || Date.now() > deadline) {
      for (const socket of activeSockets) {
        socket.terminate();
      }
      process.exit(0);
    }
    setTimeout(checkDrain, 100);
  };

  await checkDrain();
}

process.on('SIGTERM', () => {
  void gracefulHandoff();
});
```

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 Re-Binding and SO_REUSEPORT Handoff Standard

Bun 1.2 Zero-Copy TCP Socket Re-Binding and SO_REUSEPORT Handoff Standard defines an industrial-grade behavioral standard for backend engineering. Mandates kernel-level SO_REUSEPORT socket configuration and zero-copy TCP buffer lifecycles in Bun 1.2 microservices during rolling deployments. Prevents TCP reset (RST) spikes, port-binding contention, and in-flight zero-copy buffer eviction during blue/green process replacements. Enforces non-destructive socket drainage and strict dual-process overlap until health-probe convergence. 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: EADDRINUSE collisions and abruptly dropped TCP connections from premature teardown without SO_REUSEPORT socket handoffs. 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 DriftEADDRINUSE collisions and abruptly dropped TCP connections from premature teardown without SO_REUSEPORT socket handoffs.Critical
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

Services MUST explicitly pass `reusePort

Services MUST explicitly pass `reusePort: true` inside `Bun.listen()` or `Bun.serve()` configurations to enable kernel-level `SO_REUSEPORT` load balancing and seamless process replacement.

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 issue unconditional `process.exit()` calls before checking active connection drain states and zero-copy socket buffer flushes.

Engineers MUST NOT issue unconditional `process.exit()` calls before checking active connection drain states and zero-copy socket buffer flushes.

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

Services MUST implement a phased shutdown lifecycle triggered by `SIGTERM`

Services MUST implement a phased shutdown lifecycle triggered by `SIGTERM`: first stop accepting new TCP connections (`server.stop(false)` or `server.pause()`), second drain pending zero-copy writes via `socket.flush()`, and finally terminate the process after existing sockets are closed or a hard deadline expires.

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

Code MUST NEVER unbind or close the primary listening socket before the replacement worker process signals successful bind and health verification.

Code MUST NEVER unbind or close the primary listening socket before the replacement worker process signals successful bind and health verification.

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

Engineers MUST configure kernel-level backlogs explicitly (`backlog

Engineers MUST configure kernel-level backlogs explicitly (`backlog: 1024` or higher) alongside `reusePort: true` to prevent SYN packet dropouts during burst handoffs.

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

Services handling streaming zero-copy workloads MUST monitor `socket.data` reference lifecycles and ensure all slice references are consumed or copied prior to socket close.

Services handling streaming zero-copy workloads MUST monitor `socket.data` reference lifecycles and ensure all slice references are consumed or copied prior to socket close.

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 Re-Binding and SO_REUSEPORT Handoff Standard critical for AI coding assistants?

Mandates kernel-level SO_REUSEPORT socket configuration and zero-copy TCP buffer lifecycles in Bun 1.2 microservices during rolling deployments. Prevents TCP reset (RST) spikes, port-binding contention, and in-flight zero-copy buffer eviction during blue/green process replacements. Enforces non-destructive socket drainage and strict dual-process overlap until health-probe convergence. 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 (EADDRINUSE collisions and abruptly dropped TCP connections from premature teardown without SO_REUSEPORT socket handoffs.) 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