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

Bun 1.2 SO_REUSEPORT Cluster Socket Handoff & Zero-Downtime Handoff Standard

Enforces deterministic Linux SO_REUSEPORT socket sharing and atomic worker handoff across Bun cluster workers under high-throughput TCP and HTTP workloads. Guarantees zero-packet drops (SYN drop avoidance) during blue-green worker recycling by synchronizing kernel listen queues, drain states, and parent-worker IPC handoffs.

Prohibited Anti-Pattern: Naive SIGTERM Cluster Recycling Causing Silent TCP SYN/RST Drops and Kernel Listen Queue Corruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 SO_REUSEPORT Cluster Socket Handoff & Zero-Downtime Handoff Standard - Enforces deterministic Linux SO_REUSEPORT socket sharing and atomic worker handoff across Bun cluster workers under high-throughput TCP and HTTP workloads. Guarantees zero-packet drops (SYN drop avoidance) during blue-green worker recycling by synchronizing kernel listen queues, drain states, and parent-worker IPC handoffs.
globs: src/server/**/*.{ts,js}, src/cluster/**/*.{ts,js}, src/index.ts, cluster.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-so-reuseport-cluster-handoff-standard"
---

# Bun 1.2 SO_REUSEPORT Cluster Socket Handoff & Zero-Downtime Handoff Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Naive SIGTERM Cluster Recycling Causing Silent TCP SYN/RST Drops and Kernel Listen Queue Corruption

## System Constraints
You are a Principal Systems Architect enforcing the Bun 1.2 SO_REUSEPORT Cluster Socket Handoff Standard. Mandate explicit socket reuse semantics, prevent non-deterministic multi-process port contention, and enforce coordinated drain-and-stop sequencing to eliminate connection resets and unhandled in-flight requests during process lifecycle mutations.

## Strict Guidelines
- Engineers MUST ALWAYS explicitly configure `reusePort: true` in `Bun.serve` when binding multiple processes or clustered workers to the same listening port on Linux kernel 3.9+ environments.
- Engineers MUST NOT rely on synchronous parent-process worker termination or uncoordinated `process.exit()` without initiating `server.stop(false)` and tracking connection drain completion via an atomic drain barrier.
- Code SHOULD leverage Bun's native IPC channel (`worker.postMessage` / `process.send`) to orchestrate a staged rolling cycle: bootstrap new worker -> verify socket bind -> notify old worker -> drain existing keep-alive connections -> terminate.
- Services MUST implement explicit timeouts on drain operations (e.g., `server.stop(false)` followed by a forced `server.stop(true)` after 15–30 seconds) to prevent stale persistent HTTP/1.1 or WebSocket connections from deadlocking the deployment cycle.
- Components NEVER close the master orchestrator socket before all forked child processes have completed handoff acknowledge handshakes and closed their shared file descriptors.

## Bad vs Good Implementations
### Uncoordinated Clustered Server with Naive Worker Teardown (SYN/RST Dropping)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting `reusePort: true` causes unpredictable port binding races across Bun processes. Terminating workers via unhandled SIGTERM drops existing in-flight TCP connections and fails to inform the Linux kernel to reroute incoming SYN packets away from the dying process's listen queue.
```typescript
import { spawn } from "bun";
import os from "node:os";

// ANTI-PATTERN: Spawning workers without reusePort or graceful IPC handshakes.
// Abrupt SIGTERM triggers connection resets (ECONNRESET) on in-flight requests.
if (process.env.IS_WORKER) {
  Bun.serve({
    port: 3000,
    // Missing reusePort: causes EADDRINUSE on older runtimes or uncoordinated binding
    fetch(req) {
      return new Response("Worker response");
    }
  });

  process.on("SIGTERM", () => {
    // Abrupt termination closes active file descriptors immediately
    process.exit(0);
  });
} else {
  const cpus = os.cpus().length;
  for (let i = 0; i < cpus; i++) {
    spawn([process.argv0, import.meta.file], {
      env: { ...process.env, IS_WORKER: "true" }
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly sets `reusePort: true` for OS kernel balance across processes. Implements a two-phase graceful shutdown: first stops new SYN accepts via `server.stop(false)`, prompts HTTP/1.1 connection closure, monitors `pendingRequests`, and enforces a deterministic fallback timeout before hard exit.
```typescript
import { type Server } from "bun";

// PRODUCTION FIX: Explicit reusePort binding with graceful drain phase
const DRAIN_TIMEOUT_MS = 15_000;

export function startWorkerServer(): Server {
  let isShuttingDown = false;

  const server = Bun.serve({
    port: Number(process.env.PORT ?? 3000),
    reusePort: true, // Kernel-level round-robin via SO_REUSEPORT across Bun processes
    async fetch(req, srv) {
      if (isShuttingDown) {
        // Signal client to avoid connection reuse on draining worker
        return new Response("Draining", { 
          status: 503, 
          headers: { "Connection": "close" } 
        });
      }
      return new Response("Processed cleanly");
    }
  });

  async function gracefulDrain(signal: string): Promise<void> {
    if (isShuttingDown) return;
    isShuttingDown = true;

    // server.stop(false) stops accepting new connections but allows in-flight requests to complete
    server.stop(false);

    const forceKillTimer = setTimeout(() => {
      console.error(`[Worker ${process.pid}] Drain timeout expired. Forcing shutdown.`);
      server.stop(true);
      process.exit(1);
    }, DRAIN_TIMEOUT_MS);

    // Wait for in-flight requests to reach zero
    while (server.pendingRequests > 0 || server.pendingWebSockets > 0) {
      await Bun.sleep(100);
    }

    clearTimeout(forceKillTimer);
    process.exit(0);
  }

  process.on("SIGTERM", () => void gracefulDrain("SIGTERM"));
  process.on("SIGINT", () => void gracefulDrain("SIGINT"));

  return server;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 SO_REUSEPORT Cluster Socket Handoff & Zero-Downtime Handoff Standard

Bun 1.2 SO_REUSEPORT Cluster Socket Handoff & Zero-Downtime Handoff Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic Linux SO_REUSEPORT socket sharing and atomic worker handoff across Bun cluster workers under high-throughput TCP and HTTP workloads. Guarantees zero-packet drops (SYN drop avoidance) during blue-green worker recycling by synchronizing kernel listen queues, drain states, and parent-worker IPC handoffs. 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: Naive SIGTERM Cluster Recycling Causing Silent TCP SYN/RST Drops and Kernel Listen Queue Corruption 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 DriftNaive SIGTERM Cluster Recycling Causing Silent TCP SYN/RST Drops and Kernel Listen Queue CorruptionCritical
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 explicitly configure `reusePort

Engineers MUST ALWAYS explicitly configure `reusePort: true` in `Bun.serve` when binding multiple processes or clustered workers to the same listening port on Linux kernel 3.9+ environments.

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 rely on synchronous parent-process worker termination or uncoordinated `process.exit()` without initiating `server.stop(false)` and tracking connection drain completion via an atomic drain barrier.

Engineers MUST NOT rely on synchronous parent-process worker termination or uncoordinated `process.exit()` without initiating `server.stop(false)` and tracking connection drain completion via an atomic drain barrier.

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 leverage Bun's native IPC channel (`worker.postMessage` / `process.send`) to orchestrate a staged rolling cycle

Code SHOULD leverage Bun's native IPC channel (`worker.postMessage` / `process.send`) to orchestrate a staged rolling cycle: bootstrap new worker -> verify socket bind -> notify old worker -> drain existing keep-alive connections -> terminate.

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 explicit timeouts on drain operations (e.g., `server.stop(false)` followed by a forced `server.stop(true)` after 15–30 seconds) to prevent stale persistent HTTP/1.1 or WebSocket connections from deadlocking the deployment cycle.

Services MUST implement explicit timeouts on drain operations (e.g., `server.stop(false)` followed by a forced `server.stop(true)` after 15–30 seconds) to prevent stale persistent HTTP/1.1 or WebSocket connections from deadlocking the deployment cycle.

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 close the master orchestrator socket before all forked child processes have completed handoff acknowledge handshakes and closed their shared file descriptors.

Components NEVER close the master orchestrator socket before all forked child processes have completed handoff acknowledge handshakes and closed their shared file descriptors.

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 SO_REUSEPORT Cluster Socket Handoff & Zero-Downtime Handoff Standard critical for AI coding assistants?

Enforces deterministic Linux SO_REUSEPORT socket sharing and atomic worker handoff across Bun cluster workers under high-throughput TCP and HTTP workloads. Guarantees zero-packet drops (SYN drop avoidance) during blue-green worker recycling by synchronizing kernel listen queues, drain states, and parent-worker IPC handoffs. 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 (Naive SIGTERM Cluster Recycling Causing Silent TCP SYN/RST Drops and Kernel Listen Queue Corruption) 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