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

Bun 1.2 TCP Zero-Copy Backpressure and Socket Drain Lifecycle Enforcement

Mandates strict handling of TCP socket backpressure in Bun 1.2+ runtimes by evaluating socket.write() return codes and synchronizing with the asynchronous drain lifecycle. Bypassing backpressure checks during high-throughput streams causes unmanaged native heap accumulation in Bun worker runtimes, leading to silent latency degradation and resident set size (RSS) out-of-memory crashes.

Prohibited Anti-Pattern: Unchecked Fire-and-Forget Streaming Over TCP Sockets Without Drain Lifecycle Flow Control

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 TCP Zero-Copy Backpressure and Socket Drain Lifecycle Enforcement - Mandates strict handling of TCP socket backpressure in Bun 1.2+ runtimes by evaluating socket.write() return codes and synchronizing with the asynchronous drain lifecycle. Bypassing backpressure checks during high-throughput streams causes unmanaged native heap accumulation in Bun worker runtimes, leading to silent latency degradation and resident set size (RSS) out-of-memory crashes.
globs: src/**/*.ts, server/**/*.ts, workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-tcp-backpressure-drain-invariants"
---

# Bun 1.2 TCP Zero-Copy Backpressure and Socket Drain Lifecycle Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Fire-and-Forget Streaming Over TCP Sockets Without Drain Lifecycle Flow Control

## System Constraints
You are a Principal Software Architect enforcing Bun 1.2 TCP networking invariants. In high-throughput TCP streaming scenarios, Bun utilizes zero-copy native buffers. You must mandate that every TCP write checks buffer saturation via socket.write() return values, suspends upstream ingestion upon backpressure saturation, and re-engages streaming strictly through the socket's drain handler.

## Strict Guidelines
- Engineers MUST ALWAYS inspect the return value of `socket.write(chunk)` to verify whether the entire payload was consumed by the underlying OS kernel buffer.
- Engineers MUST pause upstream async iterators, file reads, or message consumers immediately when `socket.write()` indicates that data has been queued internally (i.e. returns false or partial byte length).
- Code MUST bind the socket's `drain(socket)` lifecycle callback to resume paused streaming pipelines or resolve pending backpressure promises.
- Services MUST clean up pending drain resolvers and drop buffered references when the socket triggers `close(socket)` or `error(socket, err)` to prevent orphaned promise leaks.
- Engineers MUST NOT continuously write binary chunks inside an unthrottled `for-await` loop without awaiting drain release, as native memory queues will expand without triggering JavaScript garbage collection.
- Components NEVER instantiate unbounded in-memory array buffers as ad-hoc write queues when Bun's native write buffer signals saturation.

## Bad vs Good Implementations
### TCP Stream Ingestion with Drain Flow Control

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating through chunks and directly calling `socket.write(chunk)` ignores whether the TCP send buffer is full. In high-throughput scenarios or over slow client links, Bun buffers data in native memory outside the JS garbage collector, causing process memory to balloon uncontrollably until the runtime crashes.
```typescript
import { listen, type TCPSocket } from "bun";

interface StreamContext {
  fileStream: AsyncIterable<Uint8Array>;
}

Bun.listen<StreamContext>({
  hostname: "0.0.0.0",
  port: 4000,
  socket: {
    async open(socket: TCPSocket<StreamContext>) {
      // VIOLATION: Rapid iteration without checking backpressure.
      // Unconsumed bytes queue invisibly in native memory, spiking RSS.
      for await (const chunk of socket.data.fileStream) {
        socket.write(chunk);
      }
      socket.end();
    },
    data(socket, data) {},
  },
});
```

#### Production Standard (Correct)
> **Standard**: The pump function verifies that `socket.write(value)` fully absorbed the data into the kernel buffer. If incomplete, it suspends upstream iteration until Bun triggers the native `drain(socket)` event, keeping resident memory flat and strictly bound.
```typescript
import { listen, type TCPSocket } from "bun";

interface SocketState {
  drainResolver: (() => void) | null;
  stream: AsyncIterator<Uint8Array>;
}

Bun.listen<SocketState>({
  hostname: "0.0.0.0",
  port: 4000,
  socket: {
    open(socket: TCPSocket<SocketState>) {
      // Pumping mechanism respecting Bun 1.2 backpressure
      void pumpStream(socket);
    },
    drain(socket: TCPSocket<SocketState>) {
      if (socket.data.drainResolver) {
        const resolve = socket.data.drainResolver;
        socket.data.drainResolver = null;
        resolve();
      }
    },
    close(socket: TCPSocket<SocketState>) {
      if (socket.data.drainResolver) {
        socket.data.drainResolver();
        socket.data.drainResolver = null;
      }
    },
    error(socket: TCPSocket<SocketState>, error: Error) {
      if (socket.data.drainResolver) {
        socket.data.drainResolver();
        socket.data.drainResolver = null;
      }
    },
    data(socket, data) {}
  },
});

async function pumpStream(socket: TCPSocket<SocketState>): Promise<void> {
  while (true) {
    const { value, done } = await socket.data.stream.next();
    if (done || !value) {
      socket.end();
      break;
    }

    const written = socket.write(value);
    // In Bun 1.2, socket.write() returns the number of bytes written.
    // If written < value.byteLength, backpressure has been applied.
    if (written < value.byteLength) {
      await new Promise<void>((resolve) => {
        socket.data.drainResolver = resolve;
      });
    }
  }
}
```

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 Backpressure and Socket Drain Lifecycle Enforcement

Bun 1.2 TCP Zero-Copy Backpressure and Socket Drain Lifecycle Enforcement defines an industrial-grade behavioral standard for backend engineering. Mandates strict handling of TCP socket backpressure in Bun 1.2+ runtimes by evaluating socket.write() return codes and synchronizing with the asynchronous drain lifecycle. Bypassing backpressure checks during high-throughput streams causes unmanaged native heap accumulation in Bun worker runtimes, leading to silent latency degradation and resident set size (RSS) out-of-memory crashes. 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: Unchecked Fire-and-Forget Streaming Over TCP Sockets Without Drain Lifecycle Flow Control 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 DriftUnchecked Fire-and-Forget Streaming Over TCP Sockets Without Drain Lifecycle Flow ControlCritical
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 return value of `socket.write(chunk)` to verify whether the entire payload was consumed by the underlying OS kernel buffer.

Engineers MUST ALWAYS inspect the return value of `socket.write(chunk)` to verify whether the entire payload was consumed by the underlying 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 pause upstream async iterators, file reads, or message consumers immediately when `socket.write()` indicates that data has been queued internally (i.e. returns false or partial byte length).

Engineers MUST pause upstream async iterators, file reads, or message consumers immediately when `socket.write()` indicates that data has been queued internally (i.e. returns false or partial byte 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

Code MUST bind the socket's `drain(socket)` lifecycle callback to resume paused streaming pipelines or resolve pending backpressure promises.

Code MUST bind the socket's `drain(socket)` lifecycle callback to resume paused streaming pipelines or resolve pending backpressure promises.

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 clean up pending drain resolvers and drop buffered references when the socket triggers `close(socket)` or `error(socket, err)` to prevent orphaned promise leaks.

Services MUST clean up pending drain resolvers and drop buffered references when the socket triggers `close(socket)` or `error(socket, err)` to prevent orphaned promise 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.
5

Engineers MUST NOT continuously write binary chunks inside an unthrottled `for-await` loop without awaiting drain release, as native memory queues will expand without triggering JavaScript garbage collection.

Engineers MUST NOT continuously write binary chunks inside an unthrottled `for-await` loop without awaiting drain release, as native memory queues will expand without triggering JavaScript garbage collection.

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 unbounded in-memory array buffers as ad-hoc write queues when Bun's native write buffer signals saturation.

Components NEVER instantiate unbounded in-memory array buffers as ad-hoc write queues when Bun's native write buffer signals saturation.

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 Backpressure and Socket Drain Lifecycle Enforcement critical for AI coding assistants?

Mandates strict handling of TCP socket backpressure in Bun 1.2+ runtimes by evaluating socket.write() return codes and synchronizing with the asynchronous drain lifecycle. Bypassing backpressure checks during high-throughput streams causes unmanaged native heap accumulation in Bun worker runtimes, leading to silent latency degradation and resident set size (RSS) out-of-memory crashes. 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 (Unchecked Fire-and-Forget Streaming Over TCP Sockets Without Drain Lifecycle Flow Control) 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