This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-worker-heap-budget-cancellation-protocol

Bun 1.2 Native Worker Heap Budgeting and Cooperative Cancellation Protocol

Mandates deterministic heap memory quotas, cooperative AbortSignal-driven cancellation, and proactive teardown routines for Bun isolated native workers. Prevents unmonitored JavaScriptCore heap growth from triggering kernel OOM-killer panics and event-loop thread starvation under high concurrency.

Prohibited Anti-Pattern: Spawning Unconstrained Bun Workers Without Heap Telemetry, Backpressure, or Cooperative Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Worker Heap Budgeting and Cooperative Cancellation Protocol - Mandates deterministic heap memory quotas, cooperative AbortSignal-driven cancellation, and proactive teardown routines for Bun isolated native workers. Prevents unmonitored JavaScriptCore heap growth from triggering kernel OOM-killer panics and event-loop thread starvation under high concurrency.
globs: src/**/workers/**/*.{ts,js}, src/**/*.worker.{ts,js}, src/**/worker-pool/**/*.{ts,js}, src/**/queue/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-heap-budget-cancellation-protocol"
---

# Bun 1.2 Native Worker Heap Budgeting and Cooperative Cancellation Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Unconstrained Bun Workers Without Heap Telemetry, Backpressure, or Cooperative Cancellation

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Isolated Native Worker Heap Budget & Cancellation Protocol. Mandate invariants that prevent unmanaged JavaScriptCore worker heap allocations, ensure strict message queue backpressure, and enforce two-phase worker cancellation (cooperative signal followed by deterministic forceful termination).

## Strict Guidelines
- Engineers MUST ALWAYS initialize Bun workers with explicit smol heap constraints (`{ smol: true }`) or custom resource envelopes when executing untrusted or variable-load computations.
- Engineers MUST ALWAYS implement a two-phase cancellation protocol consisting of an initial cooperative `AbortSignal` broadcast followed by a strict hard-timeout fallback to `worker.terminate()`.
- Engineers MUST NOT allow unmonitored fire-and-forget `worker.postMessage()` invocations without inspecting queue backpressure or tracking worker in-flight task limits.
- Worker scripts MUST periodically evaluate memory usage via `process.memoryUsage().heapUsed` during chunked processing and emit self-reported telemetry or voluntarily yield before breaching worker budgets.
- Supervisors MUST actively deregister worker event listeners (`message`, `error`, `close`) and clear keep-alive references (`worker.unref()`) when workers are idle or pending teardown.
- Components NEVER instantiate unbounded raw `new Worker()` instances directly inside request handlers; all worker dispatches MUST flow through a concurrency-bounded supervisor or worker pool.

## Bad vs Good Implementations
### Unbounded Worker Spawning with Missing Heap Budget & Silent OOM Vulnerability

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates an unbound worker instance per request without `{ smol: true }` or a memory budget. If the task enters an infinite allocation loop or processes oversized data, JavaScriptCore exhausts host RAM without warning, triggering a host-level SIGKILL/OOM panic. There is no timeout or cancellation protocol to reclaim resources.
```typescript
import { Worker } from "bun";

// ANTI-PATTERN: Direct instantiation in handler, no heap budget, no cancellation
export async function processDataJob(payload: unknown): Promise<unknown> {
  const worker = new Worker(new URL("./processor.worker.ts", import.meta.url));

  return new Promise((resolve, reject) => {
    worker.postMessage({ type: "EXECUTE", payload });
    
    // If worker enters infinite allocation loop, entire host Bun process may panic
    worker.onmessage = (event) => {
      resolve(event.data);
    };
    worker.onerror = (err) => {
      reject(err);
    };
  });
}
```

#### Production Standard (Correct)
> **Standard**: Enforces isolated execution with `{ smol: true }`, actively monitors worker-emitted heap telemetry against `maxHeapBytes`, handles proactive cancellation with a two-phase cooperative signal followed by a forceful termination fallback, and unrefs timers to prevent event loop hanging.
```typescript
import { Worker } from "bun";

interface WorkerTask<TInput, TOutput> {
  payload: TInput;
  signal: AbortSignal;
  maxHeapBytes: number;
  timeoutMs: number;
}

export async function executeGuardedWorkerTask<TInput, TOutput>(
  task: WorkerTask<TInput, TOutput>
): Promise<TOutput> {
  const worker = new Worker(new URL("./processor.worker.ts", import.meta.url), {
    smol: true // Instructs JSC to use conservative heap limits and eager GC
  });

  return new Promise<TOutput>((resolve, reject) => {
    let isSettled = false;

    const cleanup = () => {
      if (!isSettled) {
        isSettled = true;
        clearTimeout(timer);
        task.signal.removeEventListener("abort", onAbort);
        worker.terminate();
      }
    };

    const onAbort = () => {
      // Phase 1: Cooperative cancellation signal
      worker.postMessage({ type: "ABORT" });
      // Phase 2: Guaranteed forceful termination fallback after 500ms grace period
      setTimeout(() => cleanup(), 500).unref();
    };

    const timer = setTimeout(() => {
      cleanup();
      reject(new Error(`Worker execution exceeded budget timeout of ${task.timeoutMs}ms`));
    }, task.timeoutMs);

    task.signal.addEventListener("abort", onAbort, { once: true });

    worker.onmessage = (event: MessageEvent) => {
      const message = event.data;
      if (message.type === "TELEMETRY" && message.heapUsed > task.maxHeapBytes) {
        cleanup();
        reject(new Error(`Worker breached heap budget: ${message.heapUsed}B > ${task.maxHeapBytes}B`));
        return;
      }
      if (message.type === "SUCCESS") {
        cleanup();
        resolve(message.result as TOutput);
      }
    };

    worker.onerror = (err) => {
      cleanup();
      reject(err);
    };

    worker.postMessage({ type: "EXECUTE", payload: task.payload });
  });
}
```

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 Heap Budgeting and Cooperative Cancellation Protocol

Bun 1.2 Native Worker Heap Budgeting and Cooperative Cancellation Protocol defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic heap memory quotas, cooperative AbortSignal-driven cancellation, and proactive teardown routines for Bun isolated native workers. Prevents unmonitored JavaScriptCore heap growth from triggering kernel OOM-killer panics and event-loop thread starvation under high concurrency. 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: Spawning Unconstrained Bun Workers Without Heap Telemetry, Backpressure, or Cooperative Cancellation 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 DriftSpawning Unconstrained Bun Workers Without Heap Telemetry, Backpressure, or Cooperative CancellationCritical
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 initialize Bun workers with explicit smol heap constraints (`{ smol

Engineers MUST ALWAYS initialize Bun workers with explicit smol heap constraints (`{ smol: true }`) or custom resource envelopes when executing untrusted or variable-load computations.

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 ALWAYS implement a two-phase cancellation protocol consisting of an initial cooperative `AbortSignal` broadcast followed by a strict hard-timeout fallback to `worker.terminate()`.

Engineers MUST ALWAYS implement a two-phase cancellation protocol consisting of an initial cooperative `AbortSignal` broadcast followed by a strict hard-timeout fallback to `worker.terminate()`.

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 allow unmonitored fire-and-forget `worker.postMessage()` invocations without inspecting queue backpressure or tracking worker in-flight task limits.

Engineers MUST NOT allow unmonitored fire-and-forget `worker.postMessage()` invocations without inspecting queue backpressure or tracking worker in-flight task 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.
4

Worker scripts MUST periodically evaluate memory usage via `process.memoryUsage().heapUsed` during chunked processing and emit self-reported telemetry or voluntarily yield before breaching worker budgets.

Worker scripts MUST periodically evaluate memory usage via `process.memoryUsage().heapUsed` during chunked processing and emit self-reported telemetry or voluntarily yield before breaching worker budgets.

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

Supervisors MUST actively deregister worker event listeners (`message`, `error`, `close`) and clear keep-alive references (`worker.unref()`) when workers are idle or pending teardown.

Supervisors MUST actively deregister worker event listeners (`message`, `error`, `close`) and clear keep-alive references (`worker.unref()`) when workers are idle or pending teardown.

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 raw `new Worker()` instances directly inside request handlers

Components NEVER instantiate unbounded raw `new Worker()` instances directly inside request handlers; all worker dispatches MUST flow through a concurrency-bounded supervisor or worker pool.

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 Heap Budgeting and Cooperative Cancellation Protocol critical for AI coding assistants?

Mandates deterministic heap memory quotas, cooperative AbortSignal-driven cancellation, and proactive teardown routines for Bun isolated native workers. Prevents unmonitored JavaScriptCore heap growth from triggering kernel OOM-killer panics and event-loop thread starvation under high concurrency. 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 (Spawning Unconstrained Bun Workers Without Heap Telemetry, Backpressure, or Cooperative Cancellation) 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