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

Bun 1.2 Cluster Worker Zero-Loss TCP Socket Handoff Invariant

Enforces atomic file descriptor synchronization and kernel-level socket queue draining across Bun 1.2 multi-worker lifecycles. Eliminates truncated TLS handshakes and connection resets (ECONNRESET) during continuous rolling deployments by orchestrating SO_REUSEPORT binding with phased IPC readiness and graceful listener unbinding.

Prohibited Anti-Pattern: Uncoordinated worker termination and naive process cycling causing dropped SYN queues and truncated TLS handshakes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Cluster Worker Zero-Loss TCP Socket Handoff Invariant - Enforces atomic file descriptor synchronization and kernel-level socket queue draining across Bun 1.2 multi-worker lifecycles. Eliminates truncated TLS handshakes and connection resets (ECONNRESET) during continuous rolling deployments by orchestrating SO_REUSEPORT binding with phased IPC readiness and graceful listener unbinding.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}, cluster/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-cluster-worker-zero-loss-socket-handoff"
---

# Bun 1.2 Cluster Worker Zero-Loss TCP Socket Handoff Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated worker termination and naive process cycling causing dropped SYN queues and truncated TLS handshakes.

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-loss TCP socket handoff invariants in Bun 1.2 cluster architectures. You must mandate kernel socket reuse flags, phased worker health assertions via IPC before retirement, and non-forceful server listener draining to guarantee zero dropped TCP connections or truncated TLS negotiations during deploys.

## Strict Guidelines
- Engineers MUST ALWAYS configure `reusePort: true` in `Bun.serve` to enable the Linux/BSD kernel SO_REUSEPORT load balancing across worker instances.
- Engineers MUST NOT invoke `process.exit()` immediately upon receiving termination signals (`SIGTERM`, `SIGINT`) in worker processes.
- Code MUST unbind the listening TCP socket using `server.stop(false)` to cease accepting new connections while permitting existing in-flight HTTP requests and TLS handshakes to complete.
- Services MUST coordinate sequential worker rotation via parent-child IPC channels, ensuring the replacement worker confirms socket binding readiness before retiring the predecessor.
- Components NEVER drop in-flight TLS negotiations; rolling reload timeout envelopes MUST allocate a minimum bounded grace period (default 15s) for full TLS handshakes to resolve.

## Bad vs Good Implementations
### Naive Worker Recycling vs. Coordinated Zero-Loss Socket Handoff

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to set `reusePort: true` causes port conflict errors during concurrent worker spin-up. Calling `process.exit(0)` on `SIGTERM` kills active TCP connections, drops kernel SYN backlog queues, and corrupts pending TLS handshakes.
```typescript
import { serve } from 'bun';

// ANTI-PATTERN: Naive worker initialization without reusePort
// Immediate termination causes active TLS handshakes and TCP backlog drops
const server = serve({
  port: 3000,
  fetch(req) {
    return new Response('OK');
  },
});

process.on('SIGTERM', () => {
  // Abrupt exit tears down TCP sockets immediately, emitting ECONNRESET to clients
  process.exit(0);
});
```

#### Production Standard (Correct)
> **Standard**: Setting `reusePort: true` permits multiple processes to safely bind to the same TCP port. Using `server.stop(false)` stops listening for new connections while leaving existing connections to drain cleanly without dropping in-flight TLS handshakes.
```typescript
import { serve, type Server } from 'bun';

const DRAIN_TIMEOUT_MS = 15000;

// PRODUCTION FIX: Enable kernel-level SO_REUSEPORT distribution
const server: Server = serve({
  port: 3000,
  reusePort: true,
  fetch(req) {
    return new Response('OK');
  },
});

// Signal IPC readiness to the cluster orchestrator
if (process.send) {
  process.send({ type: 'ready', pid: process.pid });
}

async function handleGracefulShutdown(signal: string): Promise<void> {
  // Stop accepting new TCP connections; allow in-flight connections & TLS handshakes to drain
  server.stop(false);

  const forceExitTimer = setTimeout(() => {
    console.error(`Forcefully terminating worker ${process.pid} after drain timeout.`);
    process.exit(1);
  }, DRAIN_TIMEOUT_MS);
  forceExitTimer.unref();

  // Await active connection clearance (Bun drains existing requests with server.stop(false))
  while (server.pendingRequests > 0 || server.pendingWebSockets > 0) {
    await Bun.sleep(100);
  }

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

process.on('SIGTERM', () => void handleGracefulShutdown('SIGTERM'));
```

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 Cluster Worker Zero-Loss TCP Socket Handoff Invariant

Bun 1.2 Cluster Worker Zero-Loss TCP Socket Handoff Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces atomic file descriptor synchronization and kernel-level socket queue draining across Bun 1.2 multi-worker lifecycles. Eliminates truncated TLS handshakes and connection resets (ECONNRESET) during continuous rolling deployments by orchestrating SO_REUSEPORT binding with phased IPC readiness and graceful listener unbinding. 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: Uncoordinated worker termination and naive process cycling causing dropped SYN queues and truncated TLS handshakes. 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 DriftUncoordinated worker termination and naive process cycling causing dropped SYN queues and truncated TLS handshakes.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

Engineers MUST ALWAYS configure `reusePort

Engineers MUST ALWAYS configure `reusePort: true` in `Bun.serve` to enable the Linux/BSD kernel SO_REUSEPORT load balancing across worker 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.
2

Engineers MUST NOT invoke `process.exit()` immediately upon receiving termination signals (`SIGTERM`, `SIGINT`) in worker processes.

Engineers MUST NOT invoke `process.exit()` immediately upon receiving termination signals (`SIGTERM`, `SIGINT`) in worker processes.

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 unbind the listening TCP socket using `server.stop(false)` to cease accepting new connections while permitting existing in-flight HTTP requests and TLS handshakes to complete.

Code MUST unbind the listening TCP socket using `server.stop(false)` to cease accepting new connections while permitting existing in-flight HTTP requests and TLS handshakes to complete.

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 coordinate sequential worker rotation via parent-child IPC channels, ensuring the replacement worker confirms socket binding readiness before retiring the predecessor.

Services MUST coordinate sequential worker rotation via parent-child IPC channels, ensuring the replacement worker confirms socket binding readiness before retiring the predecessor.

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 drop in-flight TLS negotiations

Components NEVER drop in-flight TLS negotiations; rolling reload timeout envelopes MUST allocate a minimum bounded grace period (default 15s) for full TLS handshakes to resolve.

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 Cluster Worker Zero-Loss TCP Socket Handoff Invariant critical for AI coding assistants?

Enforces atomic file descriptor synchronization and kernel-level socket queue draining across Bun 1.2 multi-worker lifecycles. Eliminates truncated TLS handshakes and connection resets (ECONNRESET) during continuous rolling deployments by orchestrating SO_REUSEPORT binding with phased IPC readiness and graceful listener unbinding. 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 (Uncoordinated worker termination and naive process cycling causing dropped SYN queues and truncated TLS handshakes.) 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