This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-tcp-zerocopy-direct-io-guardrail

Bun 1.2 TCP Zero-Copy Direct I/O and Backpressure Guardrail

Enforces zero-copy binary forwarding and rigorous backpressure control across Bun 1.2 TCP/TLS sockets. Eliminates JavaScriptCore heap allocation churn, native-to-runtime buffer duplication, and runaway memory inflation during sustained high-throughput microservice proxying.

Prohibited Anti-Pattern: Heap-allocating intermediate buffers and bypassing TCP backpressure drainage in Bun proxy pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 TCP Zero-Copy Direct I/O and Backpressure Guardrail - Enforces zero-copy binary forwarding and rigorous backpressure control across Bun 1.2 TCP/TLS sockets. Eliminates JavaScriptCore heap allocation churn, native-to-runtime buffer duplication, and runaway memory inflation during sustained high-throughput microservice proxying.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-tcp-zerocopy-direct-io-guardrail"
---

# Bun 1.2 TCP Zero-Copy Direct I/O and Backpressure Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Heap-allocating intermediate buffers and bypassing TCP backpressure drainage in Bun proxy pipelines

## System Constraints
You are a Principal Software Architect enforcing production invariants for high-throughput Bun 1.2 TCP networking. Mandate direct zero-copy buffer forwarding, strict TCP backpressure handling using socket.pause() / socket.resume() / drain(), and zero intermediate heap allocations across all proxy pass-through conduits.

## Strict Guidelines
- Engineers MUST ALWAYS forward incoming raw Uint8Array socket chunks directly to the outbound socket without invoking Buffer.from(), Uint8Array.prototype.slice(), or string conversions.
- Engineers MUST evaluate the return value of socket.write(data); if written bytes are fewer than data.byteLength, the source socket MUST immediately be suspended via socket.pause().
- Engineers MUST implement the socket.drain callback on target sockets to invoke socket.resume() on paused source sockets when native ring buffers become writable.
- Engineers MUST NOT bridge Bun's low-level TCP APIs through Node.js node:net abstractions or node:stream Transform instances in latency-critical proxy paths.
- Code SHOULD wrap batch transfers with socket.cork() and socket.uncork() to coalesce multiple application frames into single MTU kernel packets.
- Services MUST cleanly propagate connection closure, bidirectional teardown, and unhandled socket errors across paired TCP channels to prevent socket descriptor leaks.

## Bad vs Good Implementations
### Bun 1.2 TCP Proxying: Anti-Pattern vs Zero-Copy Backpressured Forwarding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Converting raw TCP binary frames to strings and allocating intermediate Buffer objects copies data across the native-to-JS boundary, thrashing the garbage collector. Additionally, ignoring socket.write() return bytes leads to unbounded buffer accumulation and OOM crashes when upstream consumption is slower than downstream arrival.
```typescript
import { listen, type TCPSocket } from "bun";

// ANTI-PATTERN: Heap allocation, string decoding, and unhandled TCP backpressure
Bun.listen({
  port: 4000,
  socket: {
    data(clientSocket, data) {
      // Allocates JSC heap strings and copies memory from Zig/C++ native buffer
      const str = data.toString();
      const intermediateBuffer = Buffer.from(str);

      // Ignores backpressure return value; causes native memory queue exhaustion
      const proxyTarget = (clientSocket as any).targetSocket;
      if (proxyTarget) {
        proxyTarget.write(intermediateBuffer);
      }
    },
    error(socket, error) {
      console.error("Socket error", error);
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Forwards raw Uint8Array frames directly to Bun's native write mechanism without intermediate allocations. It precisely inspects write progress, pauses the upstream ingress source when native TCP send buffers saturate, and resumes source ingestion inside the drain callback once the kernel pipeline is clear.
```typescript
import { listen, type TCPSocket } from "bun";

interface ProxyContext {
  peer?: TCPSocket<ProxyContext>;
}

// PRODUCTION STANDARD: Zero-copy direct forwarding with explicit flow control
Bun.listen<ProxyContext>({
  port: 4000,
  socket: {
    data(source, data) {
      const target = source.data.peer;
      if (!target) return;

      // Zero-copy: data (Uint8Array) is passed directly to native write buffer
      const written = target.write(data);

      // Check backpressure: if full, pause ingestion from source
      if (written < data.byteLength) {
        source.pause();
      }
    },
    drain(target) {
      // Resume reading from source once downstream socket drains
      target.data.peer?.resume();
    },
    close(socket) {
      // Enforce bidirectional connection closure
      const peer = socket.data.peer;
      if (peer) {
        peer.data.peer = undefined;
        peer.end();
      }
    },
    error(socket, error) {
      socket.data.peer?.end();
      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 TCP Zero-Copy Direct I/O and Backpressure Guardrail

Bun 1.2 TCP Zero-Copy Direct I/O and Backpressure Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces zero-copy binary forwarding and rigorous backpressure control across Bun 1.2 TCP/TLS sockets. Eliminates JavaScriptCore heap allocation churn, native-to-runtime buffer duplication, and runaway memory inflation during sustained high-throughput microservice proxying. 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: Heap-allocating intermediate buffers and bypassing TCP backpressure drainage in Bun proxy pipelines 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 DriftHeap-allocating intermediate buffers and bypassing TCP backpressure drainage in Bun proxy pipelinesCritical
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 forward incoming raw Uint8Array socket chunks directly to the outbound socket without invoking Buffer.from(), Uint8Array.prototype.slice(), or string conversions.

Engineers MUST ALWAYS forward incoming raw Uint8Array socket chunks directly to the outbound socket without invoking Buffer.from(), Uint8Array.prototype.slice(), or string conversions.

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 evaluate the return value of socket.write(data)

Engineers MUST evaluate the return value of socket.write(data); if written bytes are fewer than data.byteLength, the source socket MUST immediately be suspended via socket.pause().

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 implement the socket.drain callback on target sockets to invoke socket.resume() on paused source sockets when native ring buffers become writable.

Engineers MUST implement the socket.drain callback on target sockets to invoke socket.resume() on paused source sockets when native ring buffers become writable.

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 NOT bridge Bun's low-level TCP APIs through Node.js node

Engineers MUST NOT bridge Bun's low-level TCP APIs through Node.js node:net abstractions or node:stream Transform instances in latency-critical proxy paths.

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

Code SHOULD wrap batch transfers with socket.cork() and socket.uncork() to coalesce multiple application frames into single MTU kernel packets.

Code SHOULD wrap batch transfers with socket.cork() and socket.uncork() to coalesce multiple application frames into single MTU kernel packets.

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

Services MUST cleanly propagate connection closure, bidirectional teardown, and unhandled socket errors across paired TCP channels to prevent socket descriptor leaks.

Services MUST cleanly propagate connection closure, bidirectional teardown, and unhandled socket errors across paired TCP channels to prevent socket 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.
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 TCP Zero-Copy Direct I/O and Backpressure Guardrail critical for AI coding assistants?

Enforces zero-copy binary forwarding and rigorous backpressure control across Bun 1.2 TCP/TLS sockets. Eliminates JavaScriptCore heap allocation churn, native-to-runtime buffer duplication, and runaway memory inflation during sustained high-throughput microservice proxying. 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 (Heap-allocating intermediate buffers and bypassing TCP backpressure drainage in Bun proxy pipelines) 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