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

Bun 1.2 Isolated Worker Sandboxing & Cgroup Resource Boundaries

Mandates strict resource isolation, deterministic memory limits, and preemptive lifecycle recycling when executing untrusted multitenant workloads in Bun 1.2+. Requires pairing native Bun Workers or child processes with Linux cgroups v2 boundary constraints, strict RSS/heap inspection, and hard abort timeouts to prevent noisy-neighbor starvation and host process OOM panics.

Prohibited Anti-Pattern: Unbounded Native Worker Spawning Without Cgroup Jails or Heap Watchdogs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Isolated Worker Sandboxing & Cgroup Resource Boundaries - Mandates strict resource isolation, deterministic memory limits, and preemptive lifecycle recycling when executing untrusted multitenant workloads in Bun 1.2+. Requires pairing native Bun Workers or child processes with Linux cgroups v2 boundary constraints, strict RSS/heap inspection, and hard abort timeouts to prevent noisy-neighbor starvation and host process OOM panics.
globs: src/workers/**/*.{ts,js}, src/sandbox/**/*.{ts,js}, src/services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-isolated-worker-sandboxing-cgroups"
---

# Bun 1.2 Isolated Worker Sandboxing & Cgroup Resource Boundaries

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Native Worker Spawning Without Cgroup Jails or Heap Watchdogs

## System Constraints
You are a Principal Software Architect enforcing production security and resource isolation for Bun 1.2+ environments. You must guarantee that all multitenant untrusted code execution executes inside strictly bounded, pre-instrumented worker environments governed by Linux cgroup v2 limits, strict execution deadlines, and automated recycling watchdogs.

## Strict Guidelines
- Engineers MUST ALWAYS isolate multitenant user code execution into dedicated Bun Worker instances or isolated child processes with explicitly defined memory and execution time quotas.
- Engineers MUST NOT rely on JavaScript language-level isolation (such as Object.freeze or proxy traps) without OS-level or runtime-enforced memory ceilings for untrusted code.
- Services MUST monitor worker memory utilization (RSS and heapUsed) periodically and preemptively terminate and recycle workers exceeding 80% of their allocated memory ceiling.
- Workers executing untrusted tasks MUST be constrained with hard execution timeouts using AbortSignal and explicit termination (`worker.terminate()` or `process.kill(SIGKILL)`).
- Production deployment manifests MUST map untrusted worker execution paths to dedicated Linux cgroups v2 slices with deterministic `memory.max`, `memory.high`, and `cpu.max` attributes.

## Bad vs Good Implementations
### Untrusted Script Execution with Hard Quotas and Preemptive Recycling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly running untrusted scripts without execution timeouts, heap inspection, or lifecycle controls exposes the parent Bun runtime to memory exhaustion, event-loop starvation, and denial-of-service across tenants.
```typescript
import { Worker } from 'bun';

export async function runTenantCode(tenantId: string, scriptCode: string) {
  // Anti-Pattern: Spawning native worker with direct code eval, no memory limits,
  // no timeout, and no recycling, allowing infinite loops or OOM crashes.
  const worker = new Worker(new URL('./eval-worker.ts', import.meta.url).href);
  
  return new Promise((resolve, reject) => {
    worker.postMessage({ tenantId, code: scriptCode });
    worker.onmessage = (event) => resolve(event.data);
    worker.onerror = (err) => reject(err);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit timeout guard via setTimeout, enforces smol memory footprint mode in Bun, sets up an active memory watchdog that aborts execution on boundary breach, and reliably terminates the worker to free underlying resources.
```typescript
import { Worker } from 'bun';

interface SandboxOptions {
  timeoutMs?: number;
  maxHeapBytes?: number;
}

const DEFAULT_TIMEOUT_MS = 5_000;
const DEFAULT_MAX_HEAP_BYTES = 64 * 1024 * 1024; // 64 MB

export async function runTenantCodeIsolated(
  tenantId: string,
  scriptCode: string,
  options: SandboxOptions = {}
): Promise<unknown> {
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  const maxHeapBytes = options.maxHeapBytes ?? DEFAULT_MAX_HEAP_BYTES;

  const workerUrl = new URL('./eval-worker.ts', import.meta.url).href;
  const worker = new Worker(workerUrl, {
    smol: true,
    ref: false,
  });

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

    const cleanup = () => {
      clearInterval(memoryWatchdog);
      clearTimeout(timeoutId);
      try {
        worker.terminate();
      } catch {
        // Worker may already be terminated
      }
    };

    const timeoutId = setTimeout(() => {
      if (!isSettled) {
        isSettled = true;
        cleanup();
        reject(new Error(`[TenantSandboxError] Execution timed out after ${timeoutMs}ms (Tenant: ${tenantId})`));
      }
    }, timeoutMs);

    const memoryWatchdog = setInterval(() => {
      const memUsage = process.memoryUsage();
      if (memUsage.heapUsed > maxHeapBytes) {
        if (!isSettled) {
          isSettled = true;
          cleanup();
          reject(new Error(`[TenantSandboxError] Memory ceiling of ${maxHeapBytes} bytes exceeded (Tenant: ${tenantId})`));
        }
      }
    }, 100);

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

    worker.onerror = (err) => {
      if (!isSettled) {
        isSettled = true;
        cleanup();
        reject(err);
      }
    };

    worker.postMessage({ tenantId, code: scriptCode });
  });
}
```

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 Sandboxing & Cgroup Resource Boundaries

Bun 1.2 Isolated Worker Sandboxing & Cgroup Resource Boundaries defines an industrial-grade behavioral standard for backend engineering. Mandates strict resource isolation, deterministic memory limits, and preemptive lifecycle recycling when executing untrusted multitenant workloads in Bun 1.2+. Requires pairing native Bun Workers or child processes with Linux cgroups v2 boundary constraints, strict RSS/heap inspection, and hard abort timeouts to prevent noisy-neighbor starvation and host process OOM panics. 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 Native Worker Spawning Without Cgroup Jails or Heap Watchdogs 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 Native Worker Spawning Without Cgroup Jails or Heap WatchdogsCritical
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 isolate multitenant user code execution into dedicated Bun Worker instances or isolated child processes with explicitly defined memory and execution time quotas.

Engineers MUST ALWAYS isolate multitenant user code execution into dedicated Bun Worker instances or isolated child processes with explicitly defined memory and execution time quotas.

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 rely on JavaScript language-level isolation (such as Object.freeze or proxy traps) without OS-level or runtime-enforced memory ceilings for untrusted code.

Engineers MUST NOT rely on JavaScript language-level isolation (such as Object.freeze or proxy traps) without OS-level or runtime-enforced memory ceilings for untrusted code.

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 monitor worker memory utilization (RSS and heapUsed) periodically and preemptively terminate and recycle workers exceeding 80% of their allocated memory ceiling.

Services MUST monitor worker memory utilization (RSS and heapUsed) periodically and preemptively terminate and recycle workers exceeding 80% of their allocated memory ceiling.

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 executing untrusted tasks MUST be constrained with hard execution timeouts using AbortSignal and explicit termination (`worker.terminate()` or `process.kill(SIGKILL)`).

Workers executing untrusted tasks MUST be constrained with hard execution timeouts using AbortSignal and explicit termination (`worker.terminate()` or `process.kill(SIGKILL)`).

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

Production deployment manifests MUST map untrusted worker execution paths to dedicated Linux cgroups v2 slices with deterministic `memory.max`, `memory.high`, and `cpu.max` attributes.

Production deployment manifests MUST map untrusted worker execution paths to dedicated Linux cgroups v2 slices with deterministic `memory.max`, `memory.high`, and `cpu.max` attributes.

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 Sandboxing & Cgroup Resource Boundaries critical for AI coding assistants?

Mandates strict resource isolation, deterministic memory limits, and preemptive lifecycle recycling when executing untrusted multitenant workloads in Bun 1.2+. Requires pairing native Bun Workers or child processes with Linux cgroups v2 boundary constraints, strict RSS/heap inspection, and hard abort timeouts to prevent noisy-neighbor starvation and host process OOM panics. 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 Native Worker Spawning Without Cgroup Jails or Heap Watchdogs) 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