This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-socket-kernel-backpressure-drain-standard

Bun 1.2 Kernel Socket Zero-Copy Backpressure Drainage Standard

Enforces strict TCP backpressure drainage and zero-copy memory preservation when dispatching high-throughput data via Bun 1.2 native socket primitives. Prevents unbounded internal C++/JSC write-queue allocation and kernel socket buffer saturation that leads to catastrophic process out-of-memory (OOM) termination under multi-gigabit workloads.

Prohibited Anti-Pattern: Fire-and-forget socket.write() calls ignoring partial writes and missing drain event synchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Kernel Socket Zero-Copy Backpressure Drainage Standard - Enforces strict TCP backpressure drainage and zero-copy memory preservation when dispatching high-throughput data via Bun 1.2 native socket primitives. Prevents unbounded internal C++/JSC write-queue allocation and kernel socket buffer saturation that leads to catastrophic process out-of-memory (OOM) termination under multi-gigabit workloads.
globs: src/**/*.ts, server/**/*.ts, net/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-socket-kernel-backpressure-drain-standard"
---

# Bun 1.2 Kernel Socket Zero-Copy Backpressure Drainage Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Fire-and-forget socket.write() calls ignoring partial writes and missing drain event synchronization

## System Constraints
You are a Principal Software Architect enforcing the Bun 1.2 Kernel Socket Zero-Copy Backpressure Drainage Standard. You must reject any raw socket write operations that fail to check byte write status, omit the `drain` event lifecycle handler, or create redundant buffer copies. Mandate strict backpressure state machines and non-copying slice offsets (`Uint8Array.prototype.subarray`) for all multi-gigabit Bun TCP/TLS socket streaming pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the integer return value of `socket.write(data)` to verify the exact number of bytes accepted by the OS kernel buffer.
- Engineers MUST IMMEDIATELY pause upstream producers (e.g., file streams, incoming socket feeds, or async iterators) whenever `socket.write()` returns fewer bytes than the buffer length.
- Engineers MUST retain unwritten buffer tails using zero-copy `data.subarray(written)` instead of allocating new buffers with `slice()` or concatenation.
- Services MUST register a `drain(socket)` handler on all Bun TCP listeners (`Bun.listen`) to resume paused producers and flush pending tail buffers.
- Components NEVER execute tight synchronous loops over `socket.write()` without yielding execution to the event loop and awaiting socket drain signals.

## Bad vs Good Implementations
### Bun TCP Server Socket Streaming With Backpressure Drainage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring the return value of `socket.write()` causes data corruption on partial writes and fails to signal backpressure to the upstream client. Bun's underlying kernel queue fills, leading to unbounded C++ heap buffering and an inevitable OOM crash under multi-gigabit saturated traffic.
```typescript
import { listen } from "bun";

// ANTI-PATTERN: Fire-and-forget socket writes causing unbounded heap growth
Bun.listen({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    data(socket, data) {
      // Sinks incoming high-speed data directly to downstream without backpressure check
      // socket.write returns the number of bytes written, which may be less than data.byteLength
      // Under multi-gigabit load, internal un-drained buffers trigger OOM
      socket.write(data);
    },
    open(socket) {
      console.log("Client connected");
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Tracks byte-level kernel socket saturation, utilizes zero-copy slicing (`subarray`), halts reading via `socket.pause()`, and guarantees safe resumption only when the OS kernel triggers the `drain(socket)` event.
```typescript
import { listen, type TCPSocket } from "bun";

interface SocketState {
  pendingChunk: Uint8Array | null;
  isPaused: boolean;
}

const socketStates = new WeakMap<TCPSocket<SocketState>, SocketState>();

Bun.listen<SocketState>({
  hostname: "0.0.0.0",
  port: 8080,
  socket: {
    open(socket) {
      socketStates.set(socket, { pendingChunk: null, isPaused: false });
    },
    data(socket, data) {
      const state = socketStates.get(socket);
      if (!state) return;

      // If an existing pending chunk is queued, enforce backpressure and pause
      if (state.pendingChunk !== null) {
        socket.pause();
        state.isPaused = true;
        return;
      }

      const written = socket.write(data);
      if (written < data.byteLength) {
        // Kernel buffer full: retain tail zero-copy and pause upstream flow
        state.pendingChunk = data.subarray(written);
        socket.pause();
        state.isPaused = true;
      }
    },
    drain(socket) {
      const state = socketStates.get(socket);
      if (!state || state.pendingChunk === null) return;

      const written = socket.write(state.pendingChunk);
      if (written === state.pendingChunk.byteLength) {
        state.pendingChunk = null;
        if (state.isPaused) {
          state.isPaused = false;
          socket.resume();
        }
      } else {
        // Socket still throttled; slice tail without allocating new buffer
        state.pendingChunk = state.pendingChunk.subarray(written);
      }
    },
    close(socket) {
      socketStates.delete(socket);
    }
  }
});
```

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 Kernel Socket Zero-Copy Backpressure Drainage Standard

Bun 1.2 Kernel Socket Zero-Copy Backpressure Drainage Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict TCP backpressure drainage and zero-copy memory preservation when dispatching high-throughput data via Bun 1.2 native socket primitives. Prevents unbounded internal C++/JSC write-queue allocation and kernel socket buffer saturation that leads to catastrophic process out-of-memory (OOM) termination under multi-gigabit workloads. 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: Fire-and-forget socket.write() calls ignoring partial writes and missing drain event synchronization 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 DriftFire-and-forget socket.write() calls ignoring partial writes and missing drain event synchronizationCritical
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 inspect the integer return value of `socket.write(data)` to verify the exact number of bytes accepted by the OS kernel buffer.

Engineers MUST ALWAYS inspect the integer return value of `socket.write(data)` to verify the exact number of bytes accepted by the OS kernel buffer.

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 IMMEDIATELY pause upstream producers (e.g., file streams, incoming socket feeds, or async iterators) whenever `socket.write()` returns fewer bytes than the buffer length.

Engineers MUST IMMEDIATELY pause upstream producers (e.g., file streams, incoming socket feeds, or async iterators) whenever `socket.write()` returns fewer bytes than the buffer length.

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 retain unwritten buffer tails using zero-copy `data.subarray(written)` instead of allocating new buffers with `slice()` or concatenation.

Engineers MUST retain unwritten buffer tails using zero-copy `data.subarray(written)` instead of allocating new buffers with `slice()` or concatenation.

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 register a `drain(socket)` handler on all Bun TCP listeners (`Bun.listen`) to resume paused producers and flush pending tail buffers.

Services MUST register a `drain(socket)` handler on all Bun TCP listeners (`Bun.listen`) to resume paused producers and flush pending tail buffers.

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 execute tight synchronous loops over `socket.write()` without yielding execution to the event loop and awaiting socket drain signals.

Components NEVER execute tight synchronous loops over `socket.write()` without yielding execution to the event loop and awaiting socket drain signals.

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 Kernel Socket Zero-Copy Backpressure Drainage Standard critical for AI coding assistants?

Enforces strict TCP backpressure drainage and zero-copy memory preservation when dispatching high-throughput data via Bun 1.2 native socket primitives. Prevents unbounded internal C++/JSC write-queue allocation and kernel socket buffer saturation that leads to catastrophic process out-of-memory (OOM) termination under multi-gigabit workloads. 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 (Fire-and-forget socket.write() calls ignoring partial writes and missing drain event synchronization) 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