This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-multi-worker-zero-copy-http-invariants

Bun 1.2 Multi-Worker Clustering and Zero-Copy HTTP Invariants

Enforces Linux SO_REUSEPORT kernel socket load balancing and strict zero-copy ArrayBuffer transfer semantics across Bun workers. Eliminates single-threaded event-loop starvation, V8/JSC structured-clone serialization overhead, and garbage collection pauses under multi-gigabit HTTP throughput.

Prohibited Anti-Pattern: Monolithic Event-Loop Saturation via Single-Process Bun.serve and IPC JSON Serialization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Worker Clustering and Zero-Copy HTTP Invariants - Enforces Linux SO_REUSEPORT kernel socket load balancing and strict zero-copy ArrayBuffer transfer semantics across Bun workers. Eliminates single-threaded event-loop starvation, V8/JSC structured-clone serialization overhead, and garbage collection pauses under multi-gigabit HTTP throughput.
globs: src/**/*.{ts,tsx}, server/**/*.{ts,tsx}, workers/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-multi-worker-zero-copy-http-invariants"
---

# Bun 1.2 Multi-Worker Clustering and Zero-Copy HTTP Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Monolithic Event-Loop Saturation via Single-Process Bun.serve and IPC JSON Serialization

## System Constraints
You are a Principal Systems Architect enforcing Bun 1.2 enterprise clustering standards. You mandate kernel-level socket sharding via reusePort, zero-copy transferable memory across worker threads, and strict zero-allocation response streaming to prevent event-loop thread contention and GC latency spikes.

## Strict Guidelines
- Engineers MUST ALWAYS enable 'reusePort: true' in Bun.serve() options across worker instances to leverage Linux kernel SO_REUSEPORT distributed socket accept queues.
- Engineers MUST ALWAYS spawn dedicated worker processes or Worker threads matching available physical or logical cores using 'navigator.hardwareConcurrency' or 'os.availableParallelism()'.
- Engineers MUST NOT pass complex objects or JSON-serialized strings through worker 'postMessage' boundaries; transferable 'ArrayBuffer' objects MUST be passed explicitly in the transfer list.
- Engineers MUST use 'Bun.file()' or typed array views on pre-allocated buffers when streaming large payloads to trigger zero-copy kernel sendfile/splice semantics.
- Services MUST implement graceful worker shutdown handling 'SIGTERM' and 'SIGINT' by closing the Bun server listener before draining ongoing in-flight requests.
- Components NEVER instantiate shared state via process-level global variables across clustered workers; workers must remain isolated share-nothing actors synchronized exclusively via SharedArrayBuffer/Atomics or external tiered cache.

## Bad vs Good Implementations
### Multi-Worker Socket Clustering via SO_REUSEPORT and Zero-Copy Transfer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: A single Bun process fails to saturate multi-core hardware. Spawning workers per-request destroys throughput, and JSON serialization over worker IPC causes massive heap allocations and GC pressure.
```typescript
import { serve } from "bun";

// ANTI-PATTERN: Single process Bun.serve creates an event-loop bottleneck on high core-count servers.
// Workers communicate via JSON string serialization, triggering GC spikes and CPU thrashing.
const server = serve({
  port: 8080,
  async fetch(req) {
    const data = await req.json();
    const worker = new Worker("./compute-worker.ts");
    // Inefficient: Structured clone / JSON deep copy across threads
    worker.postMessage(JSON.stringify(data));
    return new Promise((resolve) => {
      worker.onmessage = (event) => {
        resolve(new Response(event.data));
      };
    });
  }
});
console.log(`Listening on ${server.port}`);
```

#### Production Standard (Correct)
> **Standard**: Demonstrates native kernel load-balancing using 'reusePort: true' across OS processes spawned per core. Request parsing uses raw ArrayBuffers, avoiding JSON deserialization and structured-clone GC overhead.
```typescript
import { availableParallelism } from "node:os";

// PRODUCTION INVARIANT: Cluster orchestrator with SO_REUSEPORT and Transferable ArrayBuffer semantics
const isPrimary = !process.env.BUN_WORKER_ID;

if (isPrimary) {
  const numCores = availableParallelism();
  for (let i = 0; i < numCores; i++) {
    Bun.spawn([process.execPath, import.meta.path], {
      env: { ...process.env, BUN_WORKER_ID: String(i) },
      stdio: ["inherit", "inherit", "inherit"]
    });
  }
} else {
  const workerId = process.env.BUN_WORKER_ID;
  const server = Bun.serve({
    port: 8080,
    reusePort: true, // Kernel-level load distribution across independent workers
    async fetch(req) {
      if (req.method === "POST") {
        const arrayBuffer = await req.arrayBuffer();
        // Zero-copy view manipulation without reallocation
        const view = new Uint8Array(arrayBuffer);
        view[0] = 0xAA;
        return new Response(arrayBuffer, {
          headers: { "Content-Type": "application/octet-stream", "X-Worker-ID": workerId! }
        });
      }
      return new Response("OK", { status: 200 });
    }
  });

  process.on("SIGTERM", () => {
    server.stop(true);
    process.exit(0);
  });
}
```

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 Multi-Worker Clustering and Zero-Copy HTTP Invariants

Bun 1.2 Multi-Worker Clustering and Zero-Copy HTTP Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces Linux SO_REUSEPORT kernel socket load balancing and strict zero-copy ArrayBuffer transfer semantics across Bun workers. Eliminates single-threaded event-loop starvation, V8/JSC structured-clone serialization overhead, and garbage collection pauses under multi-gigabit HTTP throughput. 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: Monolithic Event-Loop Saturation via Single-Process Bun.serve and IPC JSON Serialization 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 DriftMonolithic Event-Loop Saturation via Single-Process Bun.serve and IPC JSON SerializationCritical
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' in Bun.serve() options across worker instances to leverage Linux kernel SO_REUSEPORT distributed socket accept queues.

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 ALWAYS spawn dedicated worker processes or Worker threads matching available physical or logical cores using 'navigator.hardwareConcurrency' or 'os.availableParallelism()'.

Engineers MUST ALWAYS spawn dedicated worker processes or Worker threads matching available physical or logical cores using 'navigator.hardwareConcurrency' or 'os.availableParallelism()'.

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 complex objects or JSON-serialized strings through worker 'postMessage' boundaries

Engineers MUST NOT pass complex objects or JSON-serialized strings through worker 'postMessage' boundaries; transferable 'ArrayBuffer' objects MUST be passed explicitly in the transfer list.

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

Engineers MUST use 'Bun.file()' or typed array views on pre-allocated buffers when streaming large payloads to trigger zero-copy kernel sendfile/splice semantics.

Engineers MUST use 'Bun.file()' or typed array views on pre-allocated buffers when streaming large payloads to trigger zero-copy kernel sendfile/splice semantics.

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 implement graceful worker shutdown handling 'SIGTERM' and 'SIGINT' by closing the Bun server listener before draining ongoing in-flight requests.

Services MUST implement graceful worker shutdown handling 'SIGTERM' and 'SIGINT' by closing the Bun server listener before draining ongoing in-flight requests.

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 instantiate shared state via process-level global variables across clustered workers

Components NEVER instantiate shared state via process-level global variables across clustered workers; workers must remain isolated share-nothing actors synchronized exclusively via SharedArrayBuffer/Atomics or external tiered cache.

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 Multi-Worker Clustering and Zero-Copy HTTP Invariants critical for AI coding assistants?

Enforces Linux SO_REUSEPORT kernel socket load balancing and strict zero-copy ArrayBuffer transfer semantics across Bun workers. Eliminates single-threaded event-loop starvation, V8/JSC structured-clone serialization overhead, and garbage collection pauses under multi-gigabit HTTP throughput. 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 (Monolithic Event-Loop Saturation via Single-Process Bun.serve and IPC JSON Serialization) 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