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

Bun 1.2 Native Worker PostMessage Queue Backpressure & Memory Bounds

Enforces bounded queue depths and explicit bidirectional backpressure on Bun 1.2 Worker thread message dispatching. Prevents silent native heap and RSS ballooning caused by unacknowledged postMessage queues during high-throughput CPU-bound processing bursts.

Prohibited Anti-Pattern: Unbounded postMessage Fire-and-Forget Dispatch Leading to Silent Native Heap Exhaustion and OOM Crashes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Worker PostMessage Queue Backpressure & Memory Bounds - Enforces bounded queue depths and explicit bidirectional backpressure on Bun 1.2 Worker thread message dispatching. Prevents silent native heap and RSS ballooning caused by unacknowledged postMessage queues during high-throughput CPU-bound processing bursts.
globs: src/**/*.worker.ts, src/**/workers/**/*.ts, src/**/thread-pool/**/*.ts, src/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-postmessage-backpressure-guardrail"
---

# Bun 1.2 Native Worker PostMessage Queue Backpressure & Memory Bounds

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded postMessage Fire-and-Forget Dispatch Leading to Silent Native Heap Exhaustion and OOM Crashes

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Worker Thread PostMessage Queue Backpressure Guardrails. Mandate bounded in-flight message processing, explicit credit-based or watermark-driven acknowledgement protocols, and memory-safe thread communication across all Bun worker thread pools.

## Strict Guidelines
- Engineers MUST ALWAYS enforce bounded in-flight message constraints (high/low watermarks or semaphore tokens) prior to invoking worker.postMessage() in Bun.
- Engineers MUST NOT dispatch unthrottled fire-and-forget postMessage payloads from high-frequency event loops or streams into native Bun Workers.
- Code SHOULD leverage ArrayBuffer transfer lists or SharedArrayBuffer with Atomics when passing large data structures to bypass Structured Clone Native Heap allocations.
- Services MUST monitor inflight task depth and suspend source stream intake or pause producer execution when the high watermark threshold is breached.
- Components NEVER assume Worker garbage collection frees pending postMessage queue payloads before native RSS reaches host memory limits.

## Bad vs Good Implementations
### Unbounded Worker Dispatch vs. Watermark Backpressure Queue

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Pushing unconstrained payloads into a worker thread overruns the native C++ message queue. Bun's JavaScriptCore thread cannot process tasks fast enough, resulting in runaway native RSS memory growth and SIGKILL terminations under load.
```typescript
import { Worker } from 'bun';

const worker = new Worker(new URL('./compute.worker.ts', import.meta.url));

// ANTI-PATTERN: Rapidly pushing unbounded items into Bun's native message queue.
// Structured Clone serialization accumulates in native RSS without JSC GC reclamation.
export async function processBatch(items: Uint8Array[]): Promise<void> {
  for (const item of items) {
    worker.postMessage({ type: 'PROCESS', data: item });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit credit-based acknowledgement and drain cycle with strict high and low watermarks. Suspends the producer before native postMessage queues saturate Bun's thread memory, and leverages Transferables to minimize RSS clone footprints.
```typescript
import { Worker } from 'bun';

const worker = new Worker(new URL('./compute.worker.ts', import.meta.url));
const HIGH_WATERMARK = 64;
const LOW_WATERMARK = 16;

let inflightCount = 0;
let drainResolver: (() => void) | null = null;

worker.onmessage = (event: MessageEvent) => {
  if (event.data.type === 'ACK') {
    inflightCount--;
    if (drainResolver && inflightCount <= LOW_WATERMARK) {
      const resolve = drainResolver;
      drainResolver = null;
      resolve();
    }
  }
};

export async function processBatch(items: Uint8Array[]): Promise<void> {
  for (const item of items) {
    if (inflightCount >= HIGH_WATERMARK) {
      await new Promise<void>((resolve) => {
        drainResolver = resolve;
      });
    }
    
    inflightCount++;
    // Pass transferable buffers where possible to eliminate serialization heap clones
    worker.postMessage({ type: 'PROCESS', buffer: item.buffer }, [item.buffer]);
  }
}
```

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 Worker PostMessage Queue Backpressure & Memory Bounds

Bun 1.2 Native Worker PostMessage Queue Backpressure & Memory Bounds defines an industrial-grade behavioral standard for backend engineering. Enforces bounded queue depths and explicit bidirectional backpressure on Bun 1.2 Worker thread message dispatching. Prevents silent native heap and RSS ballooning caused by unacknowledged postMessage queues during high-throughput CPU-bound processing bursts. 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 postMessage Fire-and-Forget Dispatch Leading to Silent Native Heap Exhaustion and OOM Crashes 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 postMessage Fire-and-Forget Dispatch Leading to Silent Native Heap Exhaustion and OOM CrashesCritical
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 enforce bounded in-flight message constraints (high/low watermarks or semaphore tokens) prior to invoking worker.postMessage() in Bun.

Engineers MUST ALWAYS enforce bounded in-flight message constraints (high/low watermarks or semaphore tokens) prior to invoking worker.postMessage() in Bun.

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 dispatch unthrottled fire-and-forget postMessage payloads from high-frequency event loops or streams into native Bun Workers.

Engineers MUST NOT dispatch unthrottled fire-and-forget postMessage payloads from high-frequency event loops or streams into native Bun Workers.

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 leverage ArrayBuffer transfer lists or SharedArrayBuffer with Atomics when passing large data structures to bypass Structured Clone Native Heap allocations.

Code SHOULD leverage ArrayBuffer transfer lists or SharedArrayBuffer with Atomics when passing large data structures to bypass Structured Clone Native Heap allocations.

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 monitor inflight task depth and suspend source stream intake or pause producer execution when the high watermark threshold is breached.

Services MUST monitor inflight task depth and suspend source stream intake or pause producer execution when the high watermark threshold is breached.

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 assume Worker garbage collection frees pending postMessage queue payloads before native RSS reaches host memory limits.

Components NEVER assume Worker garbage collection frees pending postMessage queue payloads before native RSS reaches host memory limits.

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 Worker PostMessage Queue Backpressure & Memory Bounds critical for AI coding assistants?

Enforces bounded queue depths and explicit bidirectional backpressure on Bun 1.2 Worker thread message dispatching. Prevents silent native heap and RSS ballooning caused by unacknowledged postMessage queues during high-throughput CPU-bound processing bursts. 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 postMessage Fire-and-Forget Dispatch Leading to Silent Native Heap Exhaustion and OOM Crashes) 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