This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-native-socket-zero-copy-simd-deserialization

Bun 1.2 Native Socket Zero-Copy SIMD Deserialization & Buffer Lifecycle Invariant

Enforces strict native ArrayBuffer lifecycle pooling and deterministic zero-copy subarray slicing within Bun.listen TCP sockets. Prohibits implicit TypedArray and Node.js Buffer allocations in high-throughput hot paths to eliminate JavaScriptCore heap fragmentation and optimize SIMD-accelerated deserialization.

Prohibited Anti-Pattern: Transient Buffer Allocations, Escaping Chunk Slices, and Desynchronized Memory Lifecycles Under Native TCP Streaming

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Socket Zero-Copy SIMD Deserialization & Buffer Lifecycle Invariant - Enforces strict native ArrayBuffer lifecycle pooling and deterministic zero-copy subarray slicing within Bun.listen TCP sockets. Prohibits implicit TypedArray and Node.js Buffer allocations in high-throughput hot paths to eliminate JavaScriptCore heap fragmentation and optimize SIMD-accelerated deserialization.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-socket-zero-copy-simd-deserialization"
---

# Bun 1.2 Native Socket Zero-Copy SIMD Deserialization & Buffer Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Transient Buffer Allocations, Escaping Chunk Slices, and Desynchronized Memory Lifecycles Under Native TCP Streaming

## System Constraints
You are a Principal Systems Architect enforcing the Bun 1.2 Native Socket Zero-Copy SIMD Deserialization Invariant. Under high-throughput streaming workloads, you must reject any code allocating transient ArrayBuffers, cloning buffers via slice(), or leaking unpooled TypedArray references into asynchronous continuation scopes. Require pre-allocated memory slabs, strict Uint8Array.prototype.subarray indexing, zero-copy synchronous parsing, and deterministic buffer reuse to prevent JavaScriptCore GC thrashing and native heap fragmentation.

## Strict Guidelines
- Engineers MUST ALWAYS process Bun.listen socket data synchronously or copy payload slices into a deterministic pre-allocated ring-buffer slab before crossing async boundaries.
- Engineers MUST NOT invoke Buffer.from(data), data.slice(), or implicit copy constructors inside socket data handlers.
- Code SHOULD use Uint8Array.prototype.subarray() exclusively for frame delimitation to maintain a shared underlying ArrayBuffer pointer.
- Services MUST align binary deserialization offsets to 8-byte boundaries to enable Bun and JSC SIMD vectorized memory operations.
- Components NEVER store direct references to incoming socket data Buffers beyond the synchronous execution context of the data() callback.

## Bad vs Good Implementations
### TCP Inbound Chunk Processing & SIMD Frame Deserialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Buffer.from(data) wraps the native slice and creates unnecessary garbage. Calling buffer.slice() performs a full heap clone of the underlying memory. Awaiting within data() allows backpressure issues and unbounded GC allocations during packet bursts.
```typescript
import { listen } from "bun";

// ANTI-PATTERN: Spawns transient Buffers and ArrayBuffer clones per TCP chunk.
// Triggers JSC GC thrashing and escapes memory into unpooled async promises.
Bun.listen({
  port: 8080,
  socket: {
    async data(socket, data) {
      // Allocates a fresh Node.js Buffer wrapper around the native slice
      const chunk = Buffer.from(data);
      
      // Allocates a new ArrayBuffer copy
      const payload = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
      
      // Leaks transient ArrayBuffer across asynchronous boundary
      await parseFrameAsync(payload);
    },
  },
});

async function parseFrameAsync(buffer: ArrayBuffer) {
  const view = new DataView(buffer);
  const msgId = view.getUint32(0, true);
  return { msgId };
}
```

#### Production Standard (Correct)
> **Standard**: Avoids transient allocations by reading incoming socket chunks via Uint8Array views, writing directly into a pre-allocated native ArrayBuffer slab, and performing SIMD-aligned header parsing synchronously.
```typescript
import { listen, type TCPSocketListener } from "bun";

// PRODUCTION INVARIANT: Pinned slab ring buffer with zero-copy SIMD-aligned parsing.
const SLAB_SIZE = 4 * 1024 * 1024; // 4MB pinned slab
const slab = new ArrayBuffer(SLAB_SIZE);
let slabCursor = 0;

interface FrameHeader {
  readonly magic: number;
  readonly payloadLength: number;
}

// Synchronous zero-copy parser leveraging 8-byte aligned SIMD view
function tryReadFrameHeader(view: DataView, offset: number): FrameHeader | null {
  if (offset + 8 > view.byteLength) return null;
  return {
    magic: view.getUint32(offset, true),
    payloadLength: view.getUint32(offset + 4, true),
  };
}

export const server: TCPSocketListener = Bun.listen({
  port: 8080,
  socket: {
    data(socket, data) {
      // data is a zero-copy Uint8Array referencing Bun's internal socket buffer.
      const incomingBytes = data.byteLength;
      if (incomingBytes === 0) return;

      // Ensure continuous ring-buffer slab usage without reallocating
      if (slabCursor + incomingBytes > SLAB_SIZE) {
        slabCursor = 0; // Reset or rollover according to protocol compaction rules
      }

      const targetView = new Uint8Array(slab, slabCursor, incomingBytes);
      targetView.set(data); // Direct memory copy into pinned native pool

      const header = tryReadFrameHeader(new DataView(slab, slabCursor, incomingBytes), 0);
      if (header && header.magic === 0x42554e31) {
        // Zero-copy window to payload without ArrayBuffer duplication
        const payloadSubarray = targetView.subarray(8, 8 + header.payloadLength);
        processPayloadSynchronous(payloadSubarray);
      }

      slabCursor += incomingBytes;
    },
  },
});

function processPayloadSynchronous(payload: Uint8Array): void {
  // Invariant: consume payload synchronously or persist through dedicated recycling queue
  void payload.byteLength;
}
```

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 Native Socket Zero-Copy SIMD Deserialization & Buffer Lifecycle Invariant

Bun 1.2 Native Socket Zero-Copy SIMD Deserialization & Buffer Lifecycle Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict native ArrayBuffer lifecycle pooling and deterministic zero-copy subarray slicing within Bun.listen TCP sockets. Prohibits implicit TypedArray and Node.js Buffer allocations in high-throughput hot paths to eliminate JavaScriptCore heap fragmentation and optimize SIMD-accelerated deserialization. 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: Transient Buffer Allocations, Escaping Chunk Slices, and Desynchronized Memory Lifecycles Under Native TCP Streaming 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 DriftTransient Buffer Allocations, Escaping Chunk Slices, and Desynchronized Memory Lifecycles Under Native TCP StreamingCritical
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 process Bun.listen socket data synchronously or copy payload slices into a deterministic pre-allocated ring-buffer slab before crossing async boundaries.

Engineers MUST ALWAYS process Bun.listen socket data synchronously or copy payload slices into a deterministic pre-allocated ring-buffer slab before crossing async boundaries.

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 invoke Buffer.from(data), data.slice(), or implicit copy constructors inside socket data handlers.

Engineers MUST NOT invoke Buffer.from(data), data.slice(), or implicit copy constructors inside socket data handlers.

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 SHOULD use Uint8Array.prototype.subarray() exclusively for frame delimitation to maintain a shared underlying ArrayBuffer pointer.

Code SHOULD use Uint8Array.prototype.subarray() exclusively for frame delimitation to maintain a shared underlying ArrayBuffer pointer.

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 align binary deserialization offsets to 8-byte boundaries to enable Bun and JSC SIMD vectorized memory operations.

Services MUST align binary deserialization offsets to 8-byte boundaries to enable Bun and JSC SIMD vectorized memory 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

Components NEVER store direct references to incoming socket data Buffers beyond the synchronous execution context of the data() callback.

Components NEVER store direct references to incoming socket data Buffers beyond the synchronous execution context of the data() callback.

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 Native Socket Zero-Copy SIMD Deserialization & Buffer Lifecycle Invariant critical for AI coding assistants?

Enforces strict native ArrayBuffer lifecycle pooling and deterministic zero-copy subarray slicing within Bun.listen TCP sockets. Prohibits implicit TypedArray and Node.js Buffer allocations in high-throughput hot paths to eliminate JavaScriptCore heap fragmentation and optimize SIMD-accelerated deserialization. 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 (Transient Buffer Allocations, Escaping Chunk Slices, and Desynchronized Memory Lifecycles Under Native TCP Streaming) 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