This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-v12-chunked-zero-alloc-backpressure

Bun 1.2 Chunked Transfer Zero-Allocation Backpressure Standard

Enforces synchronous socket backpressure propagation to upstream streaming producers across Bun 1.2 HTTP servers and TCP/TLS sockets. Mandates non-allocating chunk emission patterns, consumption of direct ArrayBuffer views via Native ReadableStream controllers, and absolute avoidance of unbounded async push queues during gigabyte-scale transfers.

Prohibited Anti-Pattern: Unbounded Push-Style Streaming Causing Silent Heap Bloat and Process OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Chunked Transfer Zero-Allocation Backpressure Standard - Enforces synchronous socket backpressure propagation to upstream streaming producers across Bun 1.2 HTTP servers and TCP/TLS sockets. Mandates non-allocating chunk emission patterns, consumption of direct ArrayBuffer views via Native ReadableStream controllers, and absolute avoidance of unbounded async push queues during gigabyte-scale transfers.
globs: src/**/*.ts, server/**/*.ts, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-v12-chunked-zero-alloc-backpressure"
---

# Bun 1.2 Chunked Transfer Zero-Allocation Backpressure Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Push-Style Streaming Causing Silent Heap Bloat and Process OOM

## System Constraints
You are a Principal Backend Systems Architect enforcing strict Bun 1.2 zero-allocation backpressure rules. Bun's native HTTP server and socket pipelines bypass Node's stream abstractions; you must enforce pull-based ReadableStream implementations or handle socket.write() return values synchronously. Never allow unthrottled loop emission into controller.enqueue() or socket writes without awaiting drain events, ensuring process memory remains flat (O(chunk_size)) regardless of payload scale.

## Strict Guidelines
- Engineers MUST ALWAYS implement pull-based Web Streams via `pull(controller)` rather than pushing unthrottled chunks inside a fire-and-forget `start(controller)` block.
- Engineers MUST verify the boolean return value of `socket.write()` or inspect `controller.desiredSize`; if negative or false, execution MUST halt until the corresponding `drain` event resolves.
- Engineers MUST NOT allocate new typed arrays or intermediate strings per chunk; reuse static buffers or transfer ownership using `ArrayBuffer.prototype.slice()` / `subarray()` on pre-allocated pools.
- Services MUST leverage `Bun.file().stream()` or direct file descriptor piping where possible instead of manual user-space piping for disk-to-network operations.
- Engineers MUST NEVER convert raw Uint8Array byte payloads into UTF-8 strings intermediate to network dispatch, as this triggers garbage collection thrashing and breaks zero-copy optimizations.

## Bad vs Good Implementations
### Unbounded Async Push Loop vs Pull-Driven Flow Control in HTTP Response

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating through an upstream source inside start() without inspecting controller.desiredSize causes Bun to buffer every emitted chunk in native memory when the client has a slow connection, resulting in unbounded RSS growth and OOM crash.
```typescript
import { serve } from 'bun';

serve({
  port: 3000,
  fetch(req) {
    // ANTI-PATTERN: Fire-and-forget stream generation causes memory runaway.
    // controller.enqueue() buffers indefinitely if the client network is slow.
    const stream = new ReadableStream({
      async start(controller) {
        const source = getGigabyteDataIterator();
        for await (const chunk of source) {
          // Incurs massive V8/JSC buffer allocations
          controller.enqueue(new Uint8Array(chunk));
        }
        controller.close();
      }
    });

    return new Response(stream, {
      headers: { 'Content-Type': 'application/octet-stream' }
    });
  }
});
```

#### Production Standard (Correct)
> **Standard**: Using pull() shifts control to consumer demand (highWaterMark: 1). Bun calls pull() strictly when the OS socket buffer drains, keeping overall process memory pinned strictly to the size of a single chunk.
```typescript
import { serve } from 'bun';

serve({
  port: 3000,
  fetch(req) {
    const source = getGigabyteDataIterator();
    
    // PRODUCTION FIX: Pull-based backpressure propagation.
    // Bun's native HTTP engine invokes pull() only when the kernel socket egress buffer clears.
    const stream = new ReadableStream({
      async pull(controller) {
        const { value, done } = await source.next();
        if (done) {
          controller.close();
          return;
        }
        // Enqueue zero-copy buffer view; execution suspends until client drains
        controller.enqueue(value);
      },
      cancel(reason) {
        source.return?.();
      }
    }, { highWaterMark: 1 });

    return new Response(stream, {
      headers: {
        'Content-Type': 'application/octet-stream',
        'Transfer-Encoding': 'chunked'
      }
    });
  }
});
```

### Bun Native TCP Socket Backpressure Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Ignoring the return code of socket.write() results in internal Bun queuing of outbound payloads, defeating kernel backpressure and causing high latency and memory saturation.
```typescript
import { listen } from 'bun';

listen({
  hostname: '0.0.0.0',
  port: 8080,
  socket: {
    open(socket) {
      // ANTI-PATTERN: Blindly writing into socket ignores kernel TCP window capacity
      for (let i = 0; i < 1_000_000; i++) {
        socket.write(new Uint8Array(65536));
      }
    },
    data(socket, data) {},
    drain(socket) {}
  }
});
```

#### Production Standard (Correct)
> **Standard**: Reuses a single Uint8Array across writes and suspends generation immediately if socket.write indicates backpressure, resuming only on the socket drain callback.
```typescript
import { listen, type Socket } from 'bun';

interface ClientState {
  chunksSent: number;
  totalChunks: number;
  buffer: Uint8Array;
}

listen<ClientState>({
  hostname: '0.0.0.0',
  port: 8080,
  data(socket, data) {},
  socket: {
    open(socket) {
      socket.data = {
        chunksSent: 0,
        totalChunks: 1_000_000,
        buffer: new Uint8Array(65536) // Single reused buffer allocation
      };
      pump(socket);
    },
    drain(socket) {
      // Resume writing strictly when kernel socket buffer has emptied
      pump(socket);
    }
  }
});

function pump(socket: Socket<ClientState>): void {
  const state = socket.data;
  while (state.chunksSent < state.totalChunks) {
    // socket.write returns the number of bytes written or 0/false when backed up
    const written = socket.write(state.buffer);
    state.chunksSent++;
    if (written < state.buffer.byteLength) {
      // TCP send buffer is full; back off and await native drain event
      return;
    }
  }
  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 Chunked Transfer Zero-Allocation Backpressure Standard

Bun 1.2 Chunked Transfer Zero-Allocation Backpressure Standard defines an industrial-grade behavioral standard for backend engineering. Enforces synchronous socket backpressure propagation to upstream streaming producers across Bun 1.2 HTTP servers and TCP/TLS sockets. Mandates non-allocating chunk emission patterns, consumption of direct ArrayBuffer views via Native ReadableStream controllers, and absolute avoidance of unbounded async push queues during gigabyte-scale transfers. 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: Unbounded Push-Style Streaming Causing Silent Heap Bloat and Process OOM 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 DriftUnbounded Push-Style Streaming Causing Silent Heap Bloat and Process OOMCritical
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 implement pull-based Web Streams via `pull(controller)` rather than pushing unthrottled chunks inside a fire-and-forget `start(controller)` block.

Engineers MUST ALWAYS implement pull-based Web Streams via `pull(controller)` rather than pushing unthrottled chunks inside a fire-and-forget `start(controller)` block.

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 verify the boolean return value of `socket.write()` or inspect `controller.desiredSize`

Engineers MUST verify the boolean return value of `socket.write()` or inspect `controller.desiredSize`; if negative or false, execution MUST halt until the corresponding `drain` event resolves.

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 allocate new typed arrays or intermediate strings per chunk

Engineers MUST NOT allocate new typed arrays or intermediate strings per chunk; reuse static buffers or transfer ownership using `ArrayBuffer.prototype.slice()` / `subarray()` on pre-allocated 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.
4

Services MUST leverage `Bun.file().stream()` or direct file descriptor piping where possible instead of manual user-space piping for disk-to-network operations.

Services MUST leverage `Bun.file().stream()` or direct file descriptor piping where possible instead of manual user-space piping for disk-to-network operations.

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 NEVER convert raw Uint8Array byte payloads into UTF-8 strings intermediate to network dispatch, as this triggers garbage collection thrashing and breaks zero-copy optimizations.

Engineers MUST NEVER convert raw Uint8Array byte payloads into UTF-8 strings intermediate to network dispatch, as this triggers garbage collection thrashing and breaks zero-copy optimizations.

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 Chunked Transfer Zero-Allocation Backpressure Standard critical for AI coding assistants?

Enforces synchronous socket backpressure propagation to upstream streaming producers across Bun 1.2 HTTP servers and TCP/TLS sockets. Mandates non-allocating chunk emission patterns, consumption of direct ArrayBuffer views via Native ReadableStream controllers, and absolute avoidance of unbounded async push queues during gigabyte-scale transfers. 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 (Unbounded Push-Style Streaming Causing Silent Heap Bloat and Process OOM) 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