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

Bun 1.2 Zero-Copy UDS Cluster Socket Handoff Standard

Mandates zero-copy socket file descriptor migration across multi-process worker pools in Bun 1.2 using Unix Domain Sockets and transferable native socket handles. Eliminates user-space IPC frame serialization, double-buffering, and primary-process event-loop saturation during high-throughput WebSocket ingress.

Prohibited Anti-Pattern: Proxying WebSocket Byte Streams via IPC Pipes Instead of Delegating Underlying Sockets via UDS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy UDS Cluster Socket Handoff Standard - Mandates zero-copy socket file descriptor migration across multi-process worker pools in Bun 1.2 using Unix Domain Sockets and transferable native socket handles. Eliminates user-space IPC frame serialization, double-buffering, and primary-process event-loop saturation during high-throughput WebSocket ingress.
globs: src/**/*.{ts,js}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-uds-zero-copy-socket-handoff"
---

# Bun 1.2 Zero-Copy UDS Cluster Socket Handoff Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Proxying WebSocket Byte Streams via IPC Pipes Instead of Delegating Underlying Sockets via UDS

## System Constraints
You are a Principal Systems Architect enforcing the Bun 1.2 Zero-Copy UDS Cluster Socket Handoff Standard. You must prevent developers from buffering, serializing, or proxying raw WebSocket frames through IPC message channels between master and worker processes. Require native socket handoff via Unix Domain Sockets (UDS) with file descriptor passing or Bun worker socket transfer so worker processes natively terminate TLS and manage WebSocket lifecycles without primary process overhead.

## Strict Guidelines
- Engineers MUST ALWAYS delegate raw TCP socket file descriptors or use transferable socket handles when routing connections from the primary acceptor to worker pools.
- Engineers MUST NOT stream WebSocket binary frames or JSON payloads across standard IPC message channels (e.g., process.send or IPC pipes) for connection proxying.
- Primary process MUST act strictly as an accept-and-delegate routing layer, releasing reference to the socket immediately after successful handoff to prevent descriptor leaks.
- Worker processes MUST handle HTTP upgrade negotiation and native WebSocket frame parsing directly on the received socket file descriptor.
- Socket handoff channels MUST use local Unix Domain Sockets (AF_UNIX) or Bun Worker transferables with strict backpressure signaling and heartbeat health checks.

## Bad vs Good Implementations
### WebSocket Connection Handoff to Worker Pool

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The primary process upgrades the WebSocket connection and proxies incoming payload buffers across IPC using worker.send(). This duplicates memory in V8/JavaScriptCore heaps, triggers garbage collection thrashing, and turns the primary process into a CPU and I/O bottleneck.
```typescript
// Primary process buffering and forwarding WebSocket frames over IPC
import { serve } from "bun";
import { fork } from "node:child_process";

const worker = fork("./worker.ts");

serve({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req)) {
      return undefined;
    }
    return new Response("Upgrade failed", { status: 400 });
  },
  websocket: {
    message(ws, message) {
      // VIOLATION: Serializing and forwarding payload through IPC pipe
      // Induces double-buffering, GC pressure, and master event-loop lag
      worker.send({
        clientId: ws.data.id,
        payload: message
      });
    },
    open(ws) {
      ws.data = { id: crypto.randomUUID() };
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: The primary process captures the native socket handle and hands it off directly via a Unix Domain Socket mechanism without terminating the WebSocket or buffering frames. The worker process claims ownership of the raw socket and executes native HTTP upgrade and WebSocket parsing with zero IPC overhead.
```typescript
// Primary process: Zero-copy socket handoff via Unix Domain Socket / Bun transferable
import { listen } from "bun";

interface WorkerClient {
  sendSocket(socket: any): void;
}

const workers: WorkerClient[] = []; // Initialized worker pool connected via UDS
let roundRobin = 0;

// Primary process acts solely as a TCP acceptor
listen({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    data(socket) {
      // Select target worker
      const worker = workers[roundRobin % workers.length];
      roundRobin++;

      // CORRECT: Transfer underlying native socket handle via UDS without buffering frames
      // Bun 1.2 transfers native socket ownership directly to the worker
      worker.sendSocket(socket);
      
      // Primary drops socket handle immediately to prevent descriptor leaks
      socket.unref();
    },
    open(socket) {
      socket.pause(); // Pause ingress until worker acquires descriptor
    },
    error(socket, error) {
      console.error("Socket handoff error:", error);
      socket.end();
    }
  }
});
```

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 Zero-Copy UDS Cluster Socket Handoff Standard

Bun 1.2 Zero-Copy UDS Cluster Socket Handoff Standard defines an industrial-grade behavioral standard for backend engineering. Mandates zero-copy socket file descriptor migration across multi-process worker pools in Bun 1.2 using Unix Domain Sockets and transferable native socket handles. Eliminates user-space IPC frame serialization, double-buffering, and primary-process event-loop saturation during high-throughput WebSocket ingress. 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: Proxying WebSocket Byte Streams via IPC Pipes Instead of Delegating Underlying Sockets via UDS 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 DriftProxying WebSocket Byte Streams via IPC Pipes Instead of Delegating Underlying Sockets via UDSCritical
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 delegate raw TCP socket file descriptors or use transferable socket handles when routing connections from the primary acceptor to worker pools.

Engineers MUST ALWAYS delegate raw TCP socket file descriptors or use transferable socket handles when routing connections from the primary acceptor to worker pools.

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 stream WebSocket binary frames or JSON payloads across standard IPC message channels (e.g., process.send or IPC pipes) for connection proxying.

Engineers MUST NOT stream WebSocket binary frames or JSON payloads across standard IPC message channels (e.g., process.send or IPC pipes) for connection proxying.

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

Primary process MUST act strictly as an accept-and-delegate routing layer, releasing reference to the socket immediately after successful handoff to prevent descriptor leaks.

Primary process MUST act strictly as an accept-and-delegate routing layer, releasing reference to the socket immediately after successful handoff to prevent descriptor leaks.

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

Worker processes MUST handle HTTP upgrade negotiation and native WebSocket frame parsing directly on the received socket file descriptor.

Worker processes MUST handle HTTP upgrade negotiation and native WebSocket frame parsing directly on the received socket file descriptor.

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

Socket handoff channels MUST use local Unix Domain Sockets (AF_UNIX) or Bun Worker transferables with strict backpressure signaling and heartbeat health checks.

Socket handoff channels MUST use local Unix Domain Sockets (AF_UNIX) or Bun Worker transferables with strict backpressure signaling and heartbeat health checks.

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 Zero-Copy UDS Cluster Socket Handoff Standard critical for AI coding assistants?

Mandates zero-copy socket file descriptor migration across multi-process worker pools in Bun 1.2 using Unix Domain Sockets and transferable native socket handles. Eliminates user-space IPC frame serialization, double-buffering, and primary-process event-loop saturation during high-throughput WebSocket ingress. 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 (Proxying WebSocket Byte Streams via IPC Pipes Instead of Delegating Underlying Sockets via UDS) 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