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

Bun 1.2 Isolated Worker Memory Quarantine & Heap Ceiling Enforcement

Enforces strict heap resource boundaries and deterministic lifecycle quarantine on isolated Bun Worker threads in multi-tenant runtimes. Prevents single-tenant runaway memory allocations or memory leaks from triggering OS-level OOM killer (SIGKILL) signals that terminate the primary parent Bun HTTP cluster.

Prohibited Anti-Pattern: Spawning Unbounded Multi-Tenant Workers Without Heap Caps, Smol Mode, or Watchdog Eviction

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Isolated Worker Memory Quarantine & Heap Ceiling Enforcement - Enforces strict heap resource boundaries and deterministic lifecycle quarantine on isolated Bun Worker threads in multi-tenant runtimes. Prevents single-tenant runaway memory allocations or memory leaks from triggering OS-level OOM killer (SIGKILL) signals that terminate the primary parent Bun HTTP cluster.
globs: src/**/*.ts, workers/**/*.ts, lib/runtime/**/*.ts, services/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-isolated-worker-memory-quarantine"
---

# Bun 1.2 Isolated Worker Memory Quarantine & Heap Ceiling Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Unbounded Multi-Tenant Workers Without Heap Caps, Smol Mode, or Watchdog Eviction

## System Constraints
You are a Principal Backend Engineer enforcing the Bun 1.2 Isolated Worker Memory Quarantine Invariant. Mandate that every worker thread spawned to execute multi-tenant or untrusted computational payloads enforces strict resource limits, active memory watchdog termination, and isolated heap boundaries to completely immunize the host application against process-wide OOM crashes.

## Strict Guidelines
- Engineers MUST ALWAYS pass explicit `resourceLimits` (`maxOldGenerationSizeMb`, `maxYoungGenerationSizeMb`) when instantiating `new Worker()` in Bun multi-tenant contexts.
- Engineers MUST ALWAYS enable `{ smol: true }` on worker instantiation for transient tasks to minimize the initial JavaScriptCore heap footprint.
- Services MUST attach an aggressive watchdog heartbeat monitoring worker memory consumption and terminate the worker via `worker.terminate()` before JSC heap exhaustion crashes the host process.
- Workers MUST NOT share shared ArrayBuffers across tenant boundaries without precise offset bounds checks and detached buffer disposal after task completion.
- Workers MUST listen to the `error` and `close` events, ensuring in-flight promises reject with a typed `WorkerMemoryLimitExceededError` rather than hanging indefinitely upon abrupt worker termination.
- Components NEVER execute raw tenant code directly on the parent event loop without isolating execution inside an explicit sub-process or memory-capped worker boundary.

## Bad vs Good Implementations
### Unbounded Worker Execution vs. Memory-Quarantined Guardrail Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns a worker with inherited process heap defaults and no memory ceilings. A single malicious or misconfigured tenant workload can consume all available system RAM, triggering the Linux OOM killer to terminate the entire Bun server process.
```typescript
export async function executeTenantTask(tenantId: string, taskCode: string): Promise<unknown> {
  // Anti-Pattern: Spawning a worker without resourceLimits or memory watchdog.
  // If tenant code executes `new Array(1e8).fill('leak')`, it causes process-wide OOM SIGKILL.
  const worker = new Worker(new URL('./task-runner.ts', import.meta.url).href);

  return new Promise((resolve, reject) => {
    worker.postMessage({ tenantId, taskCode });
    worker.onmessage = (event) => {
      worker.terminate();
      resolve(event.data);
    };
    worker.onerror = (err) => {
      worker.terminate();
      reject(err);
    };
  });
}
```

#### Production Standard (Correct)
> **Standard**: Configures strict young and old generation memory caps using Bun's resourceLimits and smol mode. Wraps execution in deterministic timeout and error handlers that trap OOM conditions cleanly, isolating failures strictly to the tenant context while preserving host cluster stability.
```typescript
export class WorkerMemoryLimitExceededError extends Error {
  constructor(tenantId: string, limitMb: number) {
    super(`Tenant [${tenantId}] breached worker memory quarantine hard-cap (${limitMb}MB).`);
    this.name = 'WorkerMemoryLimitExceededError';
  }
}

interface ExecutionOptions {
  maxHeapMb?: number;
  timeoutMs?: number;
}

export async function executeTenantTask(
  tenantId: string,
  taskCode: string,
  options: ExecutionOptions = {}
): Promise<unknown> {
  const maxHeapMb = options.maxHeapMb ?? 64;
  const timeoutMs = options.timeoutMs ?? 5000;

  // Invariant: Enforce explicit V8/JSC heap ceilings and smol mode
  const worker = new Worker(new URL('./task-runner.ts', import.meta.url).href, {
    smol: true,
    resourceLimits: {
      maxOldGenerationSizeMb: maxHeapMb,
      maxYoungGenerationSizeMb: Math.max(8, Math.floor(maxHeapMb / 4)),
    },
  });

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

    const cleanup = () => {
      isSettled = true;
      clearTimeout(timeoutTimer);
      worker.terminate();
    };

    const timeoutTimer = setTimeout(() => {
      if (!isSettled) {
        cleanup();
        reject(new Error(`Tenant [${tenantId}] task execution timed out after ${timeoutMs}ms.`));
      }
    }, timeoutMs);

    worker.onmessage = (event: MessageEvent) => {
      if (!isSettled) {
        cleanup();
        resolve(event.data);
      }
    };

    worker.onerror = (event: ErrorEvent) => {
      if (!isSettled) {
        cleanup();
        const isOOM = event.message?.toLowerCase().includes('out of memory');
        reject(isOOM ? new WorkerMemoryLimitExceededError(tenantId, maxHeapMb) : event.error);
      }
    };

    worker.postMessage({ tenantId, taskCode });
  });
}
```

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 Isolated Worker Memory Quarantine & Heap Ceiling Enforcement

Bun 1.2 Isolated Worker Memory Quarantine & Heap Ceiling Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict heap resource boundaries and deterministic lifecycle quarantine on isolated Bun Worker threads in multi-tenant runtimes. Prevents single-tenant runaway memory allocations or memory leaks from triggering OS-level OOM killer (SIGKILL) signals that terminate the primary parent Bun HTTP cluster. 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 Unbounded Multi-Tenant Workers Without Heap Caps, Smol Mode, or Watchdog Eviction 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 Unbounded Multi-Tenant Workers Without Heap Caps, Smol Mode, or Watchdog EvictionCritical
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 explicit `resourceLimits` (`maxOldGenerationSizeMb`, `maxYoungGenerationSizeMb`) when instantiating `new Worker()` in Bun multi-tenant contexts.

Engineers MUST ALWAYS pass explicit `resourceLimits` (`maxOldGenerationSizeMb`, `maxYoungGenerationSizeMb`) when instantiating `new Worker()` in Bun multi-tenant contexts.

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 enable `{ smol

Engineers MUST ALWAYS enable `{ smol: true }` on worker instantiation for transient tasks to minimize the initial JavaScriptCore heap footprint.

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

Services MUST attach an aggressive watchdog heartbeat monitoring worker memory consumption and terminate the worker via `worker.terminate()` before JSC heap exhaustion crashes the host process.

Services MUST attach an aggressive watchdog heartbeat monitoring worker memory consumption and terminate the worker via `worker.terminate()` before JSC heap exhaustion crashes the host process.

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

Workers MUST NOT share shared ArrayBuffers across tenant boundaries without precise offset bounds checks and detached buffer disposal after task completion.

Workers MUST NOT share shared ArrayBuffers across tenant boundaries without precise offset bounds checks and detached buffer disposal after task completion.

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

Workers MUST listen to the `error` and `close` events, ensuring in-flight promises reject with a typed `WorkerMemoryLimitExceededError` rather than hanging indefinitely upon abrupt worker termination.

Workers MUST listen to the `error` and `close` events, ensuring in-flight promises reject with a typed `WorkerMemoryLimitExceededError` rather than hanging indefinitely upon abrupt worker termination.

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 execute raw tenant code directly on the parent event loop without isolating execution inside an explicit sub-process or memory-capped worker boundary.

Components NEVER execute raw tenant code directly on the parent event loop without isolating execution inside an explicit sub-process or memory-capped worker boundary.

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 Isolated Worker Memory Quarantine & Heap Ceiling Enforcement critical for AI coding assistants?

Enforces strict heap resource boundaries and deterministic lifecycle quarantine on isolated Bun Worker threads in multi-tenant runtimes. Prevents single-tenant runaway memory allocations or memory leaks from triggering OS-level OOM killer (SIGKILL) signals that terminate the primary parent Bun HTTP cluster. 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 Unbounded Multi-Tenant Workers Without Heap Caps, Smol Mode, or Watchdog Eviction) 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