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

Bun 1.2 Direct FileSystem Zero-Copy Async Streaming Guardrail

Enforces kernel-level zero-copy payload routing in Bun 1.2 runtime by passing native BunFile handles directly to HTTP responses. Bypasses intermediate JavaScriptCore (JSC) heap buffer allocations and leverages native sendfile/copy_file_range syscalls for ultra-high-throughput file serving. Prohibits reading binary files into user-space JavaScript memory buffers or manual stream chunk piping.

Prohibited Anti-Pattern: Buffering Disk Files into JSC Memory Heap via ArrayBuffer, Buffer.from, or Manual Stream Loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Direct FileSystem Zero-Copy Async Streaming Guardrail - Enforces kernel-level zero-copy payload routing in Bun 1.2 runtime by passing native BunFile handles directly to HTTP responses. Bypasses intermediate JavaScriptCore (JSC) heap buffer allocations and leverages native sendfile/copy_file_range syscalls for ultra-high-throughput file serving. Prohibits reading binary files into user-space JavaScript memory buffers or manual stream chunk piping.
globs: src/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-direct-fs-zero-copy-async-streaming"
---

# Bun 1.2 Direct FileSystem Zero-Copy Async Streaming Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Buffering Disk Files into JSC Memory Heap via ArrayBuffer, Buffer.from, or Manual Stream Loops

## System Constraints
You are a Principal Software Architect enforcing the Bun 1.2 Direct FileSystem Zero-Copy Async Streaming Guardrail. Your mandate is to prevent user-space memory exhaustion and CPU cache thrashing caused by unnecessary heap allocations during file I/O. Reject any pull request or code pattern that reads file bytes into memory via `arrayBuffer()`, `Buffer.from()`, `node:fs` read operations, or manual stream piping when delivering files through HTTP responses or socket sinks. Mandate the use of native `Bun.file(path)` instances directly mounted to `Response` constructors, allowing the underlying Zig runtime to execute kernel-level zero-copy socket transfers.

## Strict Guidelines
- Engineers MUST ALWAYS pass a `BunFile` instance (via `Bun.file(path)`) directly as the body of `new Response(file)` when serving filesystem assets over HTTP.
- Engineers MUST NOT call `.arrayBuffer()`, `.bytes()`, `.text()`, or `Buffer.from()` on files destined for network response egress.
- Engineers MUST NOT use Node.js legacy file APIs (`node:fs`, `node:fs/promises`, `createReadStream`) for high-throughput egress in Bun runtimes.
- Services MUST verify file existence asynchronously using `await file.exists()` before mounting the file handle to prevent silent 404/500 misattributions.
- Components NEVER re-stream `BunFile` instances through `ReadableStreamDefaultController` or manual transform streams unless cryptographic transform or runtime transcoding is strictly required.
- Engineers SHOULD set appropriate HTTP caching and content headers by reading metadata directly from `file.type` and `file.size` without triggering synchronous disk reads.

## Bad vs Good Implementations
### Static and Dynamic File Egress Routing in Bun.serve

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling node:fs/promises readFile allocates an intermediate Buffer in the JavaScriptCore heap. Under ultra-high concurrent throughput, this causes severe V8/JSC GC pressure, increased RSS memory usage, and CPU cache thrashing instead of letting the OS handle page-cache transfers.
```typescript
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";

Bun.serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    const filePath = resolve("./public", `.${url.pathname}`);
    
    // ANTI-PATTERN: Pulling entire file into JavaScriptCore heap memory
    try {
      const buffer = await readFile(filePath);
      return new Response(buffer, {
        headers: { "Content-Type": "application/octet-stream" },
      });
    } catch {
      return new Response("Not Found", { status: 404 });
    }
  },
});
```

#### Production Standard (Correct)
> **Standard**: Passing the native Bun.file instance directly into the Response body allows Bun 1.2 to bypass user-space memory entirely. The Zig network layer uses native sendfile/splice/copy_file_range syscalls, pinning file descriptors to the socket with zero intermediate heap allocations.
```typescript
import { resolve } from "node:path";

Bun.serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);
    const filePath = resolve("./public", `.${url.pathname}`);
    const file = Bun.file(filePath);

    // INVARIANT: Pre-flight existence check without heap allocation
    if (!(await file.exists())) {
      return new Response("Not Found", { status: 404 });
    }

    // Direct kernel-level zero-copy (sendfile) directly to socket
    return new Response(file, {
      headers: {
        "Content-Type": file.type,
        "Content-Length": String(file.size),
        "Cache-Control": "public, max-age=31536000, immutable",
      },
    });
  },
});
```

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 Direct FileSystem Zero-Copy Async Streaming Guardrail

Bun 1.2 Direct FileSystem Zero-Copy Async Streaming Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces kernel-level zero-copy payload routing in Bun 1.2 runtime by passing native BunFile handles directly to HTTP responses. Bypasses intermediate JavaScriptCore (JSC) heap buffer allocations and leverages native sendfile/copy_file_range syscalls for ultra-high-throughput file serving. Prohibits reading binary files into user-space JavaScript memory buffers or manual stream chunk piping. 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: Buffering Disk Files into JSC Memory Heap via ArrayBuffer, Buffer.from, or Manual Stream Loops 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 DriftBuffering Disk Files into JSC Memory Heap via ArrayBuffer, Buffer.from, or Manual Stream LoopsCritical
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 pass a `BunFile` instance (via `Bun.file(path)`) directly as the body of `new Response(file)` when serving filesystem assets over HTTP.

Engineers MUST ALWAYS pass a `BunFile` instance (via `Bun.file(path)`) directly as the body of `new Response(file)` when serving filesystem assets over HTTP.

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 call `.arrayBuffer()`, `.bytes()`, `.text()`, or `Buffer.from()` on files destined for network response egress.

Engineers MUST NOT call `.arrayBuffer()`, `.bytes()`, `.text()`, or `Buffer.from()` on files destined for network response egress.

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 use Node.js legacy file APIs (`node

Engineers MUST NOT use Node.js legacy file APIs (`node:fs`, `node:fs/promises`, `createReadStream`) for high-throughput egress in Bun runtimes.

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 verify file existence asynchronously using `await file.exists()` before mounting the file handle to prevent silent 404/500 misattributions.

Services MUST verify file existence asynchronously using `await file.exists()` before mounting the file handle to prevent silent 404/500 misattributions.

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 re-stream `BunFile` instances through `ReadableStreamDefaultController` or manual transform streams unless cryptographic transform or runtime transcoding is strictly required.

Components NEVER re-stream `BunFile` instances through `ReadableStreamDefaultController` or manual transform streams unless cryptographic transform or runtime transcoding is strictly required.

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

Engineers SHOULD set appropriate HTTP caching and content headers by reading metadata directly from `file.type` and `file.size` without triggering synchronous disk reads.

Engineers SHOULD set appropriate HTTP caching and content headers by reading metadata directly from `file.type` and `file.size` without triggering synchronous disk reads.

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 Direct FileSystem Zero-Copy Async Streaming Guardrail critical for AI coding assistants?

Enforces kernel-level zero-copy payload routing in Bun 1.2 runtime by passing native BunFile handles directly to HTTP responses. Bypasses intermediate JavaScriptCore (JSC) heap buffer allocations and leverages native sendfile/copy_file_range syscalls for ultra-high-throughput file serving. Prohibits reading binary files into user-space JavaScript memory buffers or manual stream chunk piping. 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 (Buffering Disk Files into JSC Memory Heap via ArrayBuffer, Buffer.from, or Manual Stream Loops) 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