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

Bun 1.2 Isolated Native Worker Linear Memory Quota Enforcement

Enforces strict physical and virtual linear memory quotas alongside deterministic cooperative cancellation tokens within Bun 1.2 native multithreaded worker pools. Prevents rogue tenant payloads from triggering unbounded heap growth, process-level OOM aborts, or cross-tenant degradation by isolating execution environments within monitored, cancelable Worker boundaries.

Prohibited Anti-Pattern: Unbounded Multithreaded Worker Execution Without Proactive RSS Tracking or SharedArrayBuffer Cancellation Tokens

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Isolated Native Worker Linear Memory Quota Enforcement - Enforces strict physical and virtual linear memory quotas alongside deterministic cooperative cancellation tokens within Bun 1.2 native multithreaded worker pools. Prevents rogue tenant payloads from triggering unbounded heap growth, process-level OOM aborts, or cross-tenant degradation by isolating execution environments within monitored, cancelable Worker boundaries.
globs: src/workers/**/*.{ts,js}, src/services/**/*.{ts,js}, src/pool/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-worker-memory-quota-enforcement"
---

# Bun 1.2 Isolated Native Worker Linear Memory Quota Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Multithreaded Worker Execution Without Proactive RSS Tracking or SharedArrayBuffer Cancellation Tokens

## System Constraints
You are a Principal Backend Systems Architect specializing in Bun runtimes, JavaScriptCore memory models, and resilient multi-tenant isolation. Your mandate is to enforce strict memory quotas and zero-downtime execution boundaries across Bun native Worker pools. You must enforce explicit byte-level memory tracking, cooperative cancellation via Atomics/SharedArrayBuffer, and hard worker termination when linear memory boundaries are approached.

## Strict Guidelines
- Engineers MUST ALWAYS provision a SharedArrayBuffer-backed atomic cancellation token and pass it during Worker instantiation to enable synchronous, zero-latency cooperatively triggered interruptions.
- Engineers MUST NOT spawn naked, unbounded `new Worker()` instances directly from HTTP request cycles or asynchronous handlers without attaching them to a managed lifecycle pool.
- Pool supervisors MUST poll worker process metrics via `process.memoryUsage()` or worker-side telemetry against a strict deterministic ceiling (e.g., max 128MB linear RSS allowance per tenant partition).
- Workers MUST cooperatively check cancellation state via `Atomics.load(controlBuffer, 0)` at tight iterative loops, large file chunk operations, or streaming transformations.
- Supervisors MUST invoke `worker.terminate()` immediately if the worker fails to respect an atomic abort signal within a bounded grace period (e.g., 250ms), or when worker-reported RSS exceeds 90% of the provisioned quota.

## Bad vs Good Implementations
### Unbounded Worker Execution Lacking Memory Quotas and Cancellation Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker runs unconstrained with no memory thresholds or cancellation tokens. If the tenant payload executes an infinite loop or allocates dense arrays, the worker consumes host memory until the entire Bun server process encounters an uncatchable Out-Of-Memory (OOM) crash, taking down all concurrent tenants.
```typescript
import { Worker } from 'bun';

// ANTI-PATTERN: Spawning unmonitored native worker with infinite heap allowance
// Rogue tenant payloads will exhaust process memory, triggering kernel SIGKILL for the entire Bun process.
export async function runTenantJob(tenantId: string, payload: unknown): Promise<unknown> {
  const worker = new Worker(new URL('./task-runner.ts', import.meta.url).href);
  
  return new Promise((resolve, reject) => {
    worker.postMessage({ tenantId, payload });
    worker.onmessage = (event) => {
      worker.terminate();
      resolve(event.data);
    };
    worker.onerror = (err) => {
      worker.terminate();
      reject(err);
    };
  });
}
```

#### Production Standard (Correct)
> **Standard**: Allocates a deterministic `SharedArrayBuffer` for zero-latency cancellation checks via `Atomics`, sets Bun's `smol` flag to constrain per-worker JSC heap overhead, tracks memory usage against an explicit 128MB boundary, and guarantees hard termination via `worker.terminate()` if linear limits are breached or tasks fail to abort within the grace window.
```typescript
import { Worker } from 'bun';

const CANCEL_FLAG_INDEX = 0;
const STATUS_FLAG_INDEX = 1;
const MAX_MEMORY_BYTES = 128 * 1024 * 1024; // 128 MiB Linear Ceiling
const GRACE_PERIOD_MS = 250;

interface JobResult<T> {
  success: boolean;
  data?: T;
  error?: string;
}

export async function runTenantJobIsolated<T>(tenantId: string, payload: unknown): Promise<JobResult<T>> {
  const controlBuffer = new SharedArrayBuffer(8); // 2 x Int32 cells
  const controlArray = new Int32Array(controlBuffer);
  
  const worker = new Worker(new URL('./task-runner.ts', import.meta.url).href, {
    smol: true // Bun optimization: low memory footprint JSC context
  });

  return new Promise<JobResult<T>>((resolve) => {
    let quotaWatcher: Timer | null = null;

    const cleanup = () => {
      if (quotaWatcher) clearInterval(quotaWatcher);
      worker.terminate();
    };

    const triggerEmergencyAbort = (reason: string) => {
      // Signal atomic cancellation cooperatively
      Atomics.store(controlArray, CANCEL_FLAG_INDEX, 1);
      Atomics.notify(controlArray, CANCEL_FLAG_INDEX);
      
      // Hard-kill worker after deterministic grace threshold
      setTimeout(() => {
        cleanup();
        resolve({ success: false, error: `Worker aborted: ${reason}` });
      }, GRACE_PERIOD_MS);
    };

    // Monitor worker metrics defensively
    quotaWatcher = setInterval(() => {
      // Request atomic status or verify heartbeat
      const memAllocated = Atomics.load(controlArray, STATUS_FLAG_INDEX);
      if (memAllocated > MAX_MEMORY_BYTES) {
        triggerEmergencyAbort('Exceeded linear memory quota limit');
      }
    }, 50);

    worker.onmessage = (event: MessageEvent) => {
      cleanup();
      resolve({ success: true, data: event.data });
    };

    worker.onerror = (err: ErrorEvent) => {
      cleanup();
      resolve({ success: false, error: err.message });
    };

    worker.postMessage({ tenantId, payload, controlBuffer });
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Isolated Native Worker Linear Memory Quota Enforcement

Bun 1.2 Isolated Native Worker Linear Memory Quota Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict physical and virtual linear memory quotas alongside deterministic cooperative cancellation tokens within Bun 1.2 native multithreaded worker pools. Prevents rogue tenant payloads from triggering unbounded heap growth, process-level OOM aborts, or cross-tenant degradation by isolating execution environments within monitored, cancelable Worker boundaries. 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 Multithreaded Worker Execution Without Proactive RSS Tracking or SharedArrayBuffer Cancellation Tokens 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 Multithreaded Worker Execution Without Proactive RSS Tracking or SharedArrayBuffer Cancellation TokensCritical
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 provision a SharedArrayBuffer-backed atomic cancellation token and pass it during Worker instantiation to enable synchronous, zero-latency cooperatively triggered interruptions.

Engineers MUST ALWAYS provision a SharedArrayBuffer-backed atomic cancellation token and pass it during Worker instantiation to enable synchronous, zero-latency cooperatively triggered interruptions.

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 spawn naked, unbounded `new Worker()` instances directly from HTTP request cycles or asynchronous handlers without attaching them to a managed lifecycle pool.

Engineers MUST NOT spawn naked, unbounded `new Worker()` instances directly from HTTP request cycles or asynchronous handlers without attaching them to a managed lifecycle 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.
3

Pool supervisors MUST poll worker process metrics via `process.memoryUsage()` or worker-side telemetry against a strict deterministic ceiling (e.g., max 128MB linear RSS allowance per tenant partition).

Pool supervisors MUST poll worker process metrics via `process.memoryUsage()` or worker-side telemetry against a strict deterministic ceiling (e.g., max 128MB linear RSS allowance per tenant partition).

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 cooperatively check cancellation state via `Atomics.load(controlBuffer, 0)` at tight iterative loops, large file chunk operations, or streaming transformations.

Workers MUST cooperatively check cancellation state via `Atomics.load(controlBuffer, 0)` at tight iterative loops, large file chunk operations, or streaming transformations.

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 invoke `worker.terminate()` immediately if the worker fails to respect an atomic abort signal within a bounded grace period (e.g., 250ms), or when worker-reported RSS exceeds 90% of the provisioned quota.

Supervisors MUST invoke `worker.terminate()` immediately if the worker fails to respect an atomic abort signal within a bounded grace period (e.g., 250ms), or when worker-reported RSS exceeds 90% of the provisioned quota.

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 Native Worker Linear Memory Quota Enforcement critical for AI coding assistants?

Enforces strict physical and virtual linear memory quotas alongside deterministic cooperative cancellation tokens within Bun 1.2 native multithreaded worker pools. Prevents rogue tenant payloads from triggering unbounded heap growth, process-level OOM aborts, or cross-tenant degradation by isolating execution environments within monitored, cancelable Worker boundaries. 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 Multithreaded Worker Execution Without Proactive RSS Tracking or SharedArrayBuffer Cancellation Tokens) 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