This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-native-cluster-zero-downtime-reloading

Bun 1.2 Native Cluster Zero-Downtime Hot Reloading and FD Passing

Enforces strict master-worker IPC handshakes, listening socket migration, and atomic connection draining for Bun 1.2 runtimes. Prevents dropped TCP connections and port collisions during rolling zero-downtime deployments by decoupling process lifecycles via Unix domain socket file descriptor passing and graceful HTTP/WebSocket drain signals.

Prohibited Anti-Pattern: Hard-killing Bun worker processes or binding shared SO_REUSEPORT sockets without an atomic IPC drain handshake

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Cluster Zero-Downtime Hot Reloading and FD Passing - Enforces strict master-worker IPC handshakes, listening socket migration, and atomic connection draining for Bun 1.2 runtimes. Prevents dropped TCP connections and port collisions during rolling zero-downtime deployments by decoupling process lifecycles via Unix domain socket file descriptor passing and graceful HTTP/WebSocket drain signals.
globs: src/cluster/**/*.{ts,js}, src/server/**/*.{ts,js}, src/index.ts, cluster.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-cluster-zero-downtime-reloading"
---

# Bun 1.2 Native Cluster Zero-Downtime Hot Reloading and FD Passing

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Hard-killing Bun worker processes or binding shared SO_REUSEPORT sockets without an atomic IPC drain handshake

## System Constraints
You are a Principal Systems Engineer enforcing Bun 1.2 native cluster architecture standards. You must mandate atomic master-worker IPC protocols, socket file descriptor inheritance/passing, explicit dual-phase health checks (READY/DRAINING/DEAD), and hard-limited connection draining via Bun.serve({ closeOnEmpty: true }). Never allow process.kill or abrupt worker termination without confirming zero active in-flight requests.

## Strict Guidelines
- Engineers MUST ALWAYS implement a two-phase commit IPC protocol ('drain' -> 'drained' -> 'exit') between the master process and Bun workers.
- Engineers MUST NEVER abruptly terminate a Bun worker via SIGKILL or direct process.exit() without invoking Bun.serve().stop(true) to drain existing connections.
- Services MUST pass pre-bound listening sockets from master to newly spawned workers or initialize workers through Bun's Worker API using explicit IPC message channels.
- Workers MUST report an atomic 'ready' status over the IPC channel only after all route handlers, caches, and database pools are verified alive.
- Master processes MUST enforce a strict timeout guardrail on draining workers, escalating from graceful close to SIGTERM and finally SIGKILL only after grace periods expire.
- Code SHOULD leverage Bun.serve({ idleTimeout }) and active request counters to eliminate zombie keep-alive connections during hot reloads.

## Bad vs Good Implementations
### Master Process: Unsafe Process Replacement vs. Atomic Worker Handshake

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly sending SIGTERM or killing the worker process without IPC synchronization causes dropped active TCP connections, mid-flight HTTP request truncation, and transient 502 Bad Gateway responses.
```typescript
import { spawn } from 'child_process';

// ANTI-PATTERN: Abrupt worker kill during reload causes TCP drop (ECONNRESET)
let currentWorker = spawn('bun', ['src/worker.ts'], { stdio: 'inherit' });

process.on('SIGUSR2', () => {
  console.log('Reloading worker...');
  currentWorker.kill('SIGTERM'); // Drops all in-flight TCP requests immediately
  currentWorker = spawn('bun', ['src/worker.ts'], { stdio: 'inherit' });
});
```

#### Production Standard (Correct)
> **Standard**: Implements an atomic swap: the new worker must signal 'READY' before receiving traffic, and the old worker enters an explicit 'DRAIN' phase via typed IPC messages, eliminating connection loss.
```typescript
import { Worker } from 'worker_threads';

interface ClusterState {
  active: Worker | null;
  draining: Set<Worker>;
}

const cluster: ClusterState = { active: null, draining: new Set() };

function spawnWorker(): Promise<Worker> {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL('./worker.ts', import.meta.url).href);
    
    const timeout = setTimeout(() => {
      worker.terminate();
      reject(new Error('Worker startup timeout'));
    }, 10_000);

    worker.on('message', (msg: { type: string }) => {
      if (msg.type === 'READY') {
        clearTimeout(timeout);
        resolve(worker);
      } else if (msg.type === 'DRAINED') {
        worker.terminate();
        cluster.draining.delete(worker);
      }
    });

    worker.on('error', (err) => console.error('Worker error:', err));
  });
}

async function reload(): Promise<void> {
  const oldWorker = cluster.active;
  const newWorker = await spawnWorker();
  cluster.active = newWorker;

  if (oldWorker) {
    cluster.draining.add(oldWorker);
    oldWorker.postMessage({ type: 'DRAIN', gracePeriodMs: 15_000 });
  }
}

process.on('SIGUSR2', () => reload());
await reload();
```

### Worker Process: Abrupt Shutdown vs. Bun.serve Atomic Graceful Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling process.exit directly aborts Bun's event loop and internal socket buffers, sending TCP RST packets to clients awaiting responses.
```typescript
import { serve } from 'bun';

// ANTI-PATTERN: Native exit listeners closing server without draining active requests
const server = serve({
  port: 3000,
  fetch(req) {
    return new Response('Processed');
  }
});

process.on('message', (msg) => {
  if (msg === 'reload') {
    process.exit(0); // In-flight TCP requests are instantly terminated
  }
});
```

#### Production Standard (Correct)
> **Standard**: Uses Bun's native server.stop(true) to reject new connections while allowing existing requests to complete, continuously checking server.pendingRequests before signaling 'DRAINED' to master.
```typescript
import { serve, type Server } from 'bun';
import { parentPort } from 'worker_threads';

let server: Server | null = null;

server = serve({
  port: 3000,
  reusePort: true,
  idleTimeout: 10,
  fetch(req) {
    return new Response('OK', { status: 200 });
  }
});

// Signal ready state to master
parentPort?.postMessage({ type: 'READY' });

parentPort?.on('message', async (msg: { type: string; gracePeriodMs?: number }) => {
  if (msg.type === 'DRAIN') {
    // Stop accepting new connections, gracefully drain existing in-flight connections
    server?.stop(true);
    
    const graceMs = msg.gracePeriodMs ?? 10_000;
    const deadline = Date.now() + graceMs;
    
    const checkDrain = setInterval(() => {
      if (!server || server.pendingRequests === 0 || Date.now() > deadline) {
        clearInterval(checkDrain);
        parentPort?.postMessage({ type: 'DRAINED' });
      }
    }, 50);
  }
});
```

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 Cluster Zero-Downtime Hot Reloading and FD Passing

Bun 1.2 Native Cluster Zero-Downtime Hot Reloading and FD Passing defines an industrial-grade behavioral standard for backend engineering. Enforces strict master-worker IPC handshakes, listening socket migration, and atomic connection draining for Bun 1.2 runtimes. Prevents dropped TCP connections and port collisions during rolling zero-downtime deployments by decoupling process lifecycles via Unix domain socket file descriptor passing and graceful HTTP/WebSocket drain signals. 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: Hard-killing Bun worker processes or binding shared SO_REUSEPORT sockets without an atomic IPC drain handshake 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 DriftHard-killing Bun worker processes or binding shared SO_REUSEPORT sockets without an atomic IPC drain handshakeCritical
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 implement a two-phase commit IPC protocol ('drain' -> 'drained' -> 'exit') between the master process and Bun workers.

Engineers MUST ALWAYS implement a two-phase commit IPC protocol ('drain' -> 'drained' -> 'exit') between the master process and Bun workers.

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 NEVER abruptly terminate a Bun worker via SIGKILL or direct process.exit() without invoking Bun.serve().stop(true) to drain existing connections.

Engineers MUST NEVER abruptly terminate a Bun worker via SIGKILL or direct process.exit() without invoking Bun.serve().stop(true) to drain existing connections.

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 pass pre-bound listening sockets from master to newly spawned workers or initialize workers through Bun's Worker API using explicit IPC message channels.

Services MUST pass pre-bound listening sockets from master to newly spawned workers or initialize workers through Bun's Worker API using explicit IPC message channels.

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

Workers MUST report an atomic 'ready' status over the IPC channel only after all route handlers, caches, and database pools are verified alive.

Workers MUST report an atomic 'ready' status over the IPC channel only after all route handlers, caches, and database pools are verified alive.

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

Master processes MUST enforce a strict timeout guardrail on draining workers, escalating from graceful close to SIGTERM and finally SIGKILL only after grace periods expire.

Master processes MUST enforce a strict timeout guardrail on draining workers, escalating from graceful close to SIGTERM and finally SIGKILL only after grace periods expire.

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

Code SHOULD leverage Bun.serve({ idleTimeout }) and active request counters to eliminate zombie keep-alive connections during hot reloads.

Code SHOULD leverage Bun.serve({ idleTimeout }) and active request counters to eliminate zombie keep-alive connections during hot reloads.

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 Cluster Zero-Downtime Hot Reloading and FD Passing critical for AI coding assistants?

Enforces strict master-worker IPC handshakes, listening socket migration, and atomic connection draining for Bun 1.2 runtimes. Prevents dropped TCP connections and port collisions during rolling zero-downtime deployments by decoupling process lifecycles via Unix domain socket file descriptor passing and graceful HTTP/WebSocket drain signals. 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 (Hard-killing Bun worker processes or binding shared SO_REUSEPORT sockets without an atomic IPC drain handshake) 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