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

Bun 1.2 Isolated Multi-Worker SO_REUSEPORT Socket Invariant

Enforces isolated, multi-threaded server architecture in Bun 1.2+ utilizing native kernel SO_REUSEPORT socket load balancing across independent Worker threads. Eliminates event-loop starvation and cross-thread lock contention during TLS termination by guaranteeing zero shared state, per-worker socket instantiation, and CPU-pinned affinity.

Prohibited Anti-Pattern: Centralized Master-Accept Socket Proxying with Cross-Worker IPC Handoff

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Isolated Multi-Worker SO_REUSEPORT Socket Invariant - Enforces isolated, multi-threaded server architecture in Bun 1.2+ utilizing native kernel SO_REUSEPORT socket load balancing across independent Worker threads. Eliminates event-loop starvation and cross-thread lock contention during TLS termination by guaranteeing zero shared state, per-worker socket instantiation, and CPU-pinned affinity.
globs: src/server/**/*.{ts,js}, src/cluster/**/*.{ts,js}, src/network/**/*.{ts,js}, src/index.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-so-reuseport-worker-affinity-standard"
---

# Bun 1.2 Isolated Multi-Worker SO_REUSEPORT Socket Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Centralized Master-Accept Socket Proxying with Cross-Worker IPC Handoff

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-shared-state worker architecture under Bun 1.2. You mandate the use of independent Worker instances binding directly to the identical port via Bun.serve with reusePort: true. Prohibit Node-style cluster master-dispatch patterns, shared in-memory session caches across worker boundaries, and centralized TLS termination proxies within the JavaScript runtime.

## Strict Guidelines
- Engineers MUST ALWAYS enable 'reusePort: true' inside every individual worker's Bun.serve() options rather than delegating connections from a primary supervisor process.
- Engineers MUST instantiate exactly navigator.hardwareConcurrency (or a configured thread ceiling) independent Worker threads, running fully isolated entrypoint bundles.
- Engineers MUST NOT pass active net.Socket or Bun Socket handles over Worker postMessage channels; kernel-level SO_REUSEPORT socket distribution must be preserved.
- Code MUST isolate TLS handshakes to the worker thread executing the accept() call to prevent cross-core context switching and TLS session cache mutex locks.
- Services MUST utilize external lock-free or network-based storage (e.g., Redis, Dragonfly, or SharedArrayBuffer with Atomics) for distributed state; JavaScript global state must remain worker-local.
- Components NEVER attach shared event listeners or cross-worker EventEmitter topologies that synchronize synchronous blocking operations across the thread pool.

## Bad vs Good Implementations
### Worker Socket Architecture: Centralized Master Dispatch vs Isolated SO_REUSEPORT

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting reusePort: true binds the listening socket to a single event loop. In high-throughput TLS environments, cryptographic handshakes saturate the single JavaScript thread, creating extreme tail latency and starvation while adjacent CPU cores idle.
```typescript
import { cpus } from 'node:os';

// ANTI-PATTERN: Single master-accept process proxying connections or
// single-threaded Bun.serve() sharing CPU time across all TLS handshakes
const server = Bun.serve({
  port: 8443,
  reusePort: false,
  tls: {
    cert: Bun.file('./cert.pem'),
    key: Bun.file('./key.pem'),
  },
  fetch(req) {
    // Single JS event loop bottlenecks under high-volume TLS negotiations
    return new Response('Handled on single event loop');
  },
});

console.log(`Master listening on ${server.port}`);
```

#### Production Standard (Correct)
> **Standard**: Instantiating isolated Worker instances where each initiates Bun.serve() with reusePort: true instructs the Linux/Darwin kernel to distribute incoming SYN packets directly across all thread sockets via SO_REUSEPORT. TLS handshakes and event loops remain strictly parallel with zero cross-thread synchronization.
```typescript
// cluster.ts - Primary Process Supervisor
import { cpus } from 'node:os';

const workerCount = process.env.WORKER_COUNT 
  ? parseInt(process.env.WORKER_COUNT, 10) 
  : cpus().length;

for (let i = 0; i < workerCount; i++) {
  new Worker(new URL('./worker.ts', import.meta.url).href, {
    env: { ...process.env, WORKER_ID: String(i) },
  });
}

// worker.ts - Zero-Shared-State Independent Listener
const workerId = process.env.WORKER_ID ?? '0';

Bun.serve({
  port: 8443,
  reusePort: true, // Kernel-level SO_REUSEPORT load balancing across workers
  tls: {
    cert: Bun.file('./cert.pem'),
    key: Bun.file('./key.pem'),
  },
  fetch(req) {
    return new Response(`Handled by isolated worker ${workerId}`, {
      headers: { 'X-Worker-ID': workerId },
    });
  },
  error(err) {
    return new Response(`TLS/HTTP Error: ${err.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 Isolated Multi-Worker SO_REUSEPORT Socket Invariant

Bun 1.2 Isolated Multi-Worker SO_REUSEPORT Socket Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces isolated, multi-threaded server architecture in Bun 1.2+ utilizing native kernel SO_REUSEPORT socket load balancing across independent Worker threads. Eliminates event-loop starvation and cross-thread lock contention during TLS termination by guaranteeing zero shared state, per-worker socket instantiation, and CPU-pinned affinity. 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: Centralized Master-Accept Socket Proxying with Cross-Worker IPC Handoff 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 DriftCentralized Master-Accept Socket Proxying with Cross-Worker IPC HandoffCritical
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 enable 'reusePort

Engineers MUST ALWAYS enable 'reusePort: true' inside every individual worker's Bun.serve() options rather than delegating connections from a primary supervisor process.

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 instantiate exactly navigator.hardwareConcurrency (or a configured thread ceiling) independent Worker threads, running fully isolated entrypoint bundles.

Engineers MUST instantiate exactly navigator.hardwareConcurrency (or a configured thread ceiling) independent Worker threads, running fully isolated entrypoint bundles.

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

Engineers MUST NOT pass active net.Socket or Bun Socket handles over Worker postMessage channels

Engineers MUST NOT pass active net.Socket or Bun Socket handles over Worker postMessage channels; kernel-level SO_REUSEPORT socket distribution must be preserved.

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 isolate TLS handshakes to the worker thread executing the accept() call to prevent cross-core context switching and TLS session cache mutex locks.

Code MUST isolate TLS handshakes to the worker thread executing the accept() call to prevent cross-core context switching and TLS session cache mutex locks.

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

Services MUST utilize external lock-free or network-based storage (e.g., Redis, Dragonfly, or SharedArrayBuffer with Atomics) for distributed state

Services MUST utilize external lock-free or network-based storage (e.g., Redis, Dragonfly, or SharedArrayBuffer with Atomics) for distributed state; JavaScript global state must remain worker-local.

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

Components NEVER attach shared event listeners or cross-worker EventEmitter topologies that synchronize synchronous blocking operations across the thread pool.

Components NEVER attach shared event listeners or cross-worker EventEmitter topologies that synchronize synchronous blocking operations across the thread pool.

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 Isolated Multi-Worker SO_REUSEPORT Socket Invariant critical for AI coding assistants?

Enforces isolated, multi-threaded server architecture in Bun 1.2+ utilizing native kernel SO_REUSEPORT socket load balancing across independent Worker threads. Eliminates event-loop starvation and cross-thread lock contention during TLS termination by guaranteeing zero shared state, per-worker socket instantiation, and CPU-pinned affinity. 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 (Centralized Master-Accept Socket Proxying with Cross-Worker IPC Handoff) 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