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

Bun 1.2 Multi-Tenant Worker Memory Isolation & Execution Quotas

Enforces strict heap budgets, thread-level WebWorker isolation, and execution CPU/memory quotas when running untrusted multi-tenant workloads in Bun 1.2. Prohibits in-process evaluation and ensures all worker instances are aggressively terminated via deterministic abort signals and heap bounds to prevent noisy-neighbor memory leakage.

Prohibited Anti-Pattern: Executing untrusted tenant code within the primary process heap or unmetered, long-lived WebWorkers without hard termination ceilings.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Tenant Worker Memory Isolation & Execution Quotas - Enforces strict heap budgets, thread-level WebWorker isolation, and execution CPU/memory quotas when running untrusted multi-tenant workloads in Bun 1.2. Prohibits in-process evaluation and ensures all worker instances are aggressively terminated via deterministic abort signals and heap bounds to prevent noisy-neighbor memory leakage.
globs: src/sandbox/**/*.ts, src/workers/**/*.ts, src/services/tenant/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-1-2-worker-tenant-memory-isolation"
---

# Bun 1.2 Multi-Tenant Worker Memory Isolation & Execution Quotas

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing untrusted tenant code within the primary process heap or unmetered, long-lived WebWorkers without hard termination ceilings.

## System Constraints
You are a Principal Systems Architect enforcing multi-tenant isolation standards under Bun 1.2. You mandate that untrusted tenant-authored execution happens exclusively within sandboxed WebWorker threads with immutable input payloads, explicit memory ceilings, strict CPU wall-clock deadlines, and mandatory termination routines to prevent process-level OOM crashes and cross-tenant memory leakage.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate isolated WebWorkers using `new Worker(new URL(..., import.meta.url), { smol: true })` for tenant execution to reduce baseline JavaScriptCore heap footprint.
- Engineers MUST NOT execute tenant-provided code via `eval()`, `new Function()`, or dynamic `import()` within the host application thread or shared worker pools.
- Engineers MUST ALWAYS enforce an absolute wall-clock CPU timeout using `AbortController` coupled with `worker.terminate()` to guarantee tenant execution bounds.
- Workers MUST communicate solely via strictly serialized structured clone messages or `ArrayBuffer` transfers; shared mutable state across tenant boundaries is strictly prohibited.
- Worker managers MUST inspect memory delta and trigger explicit garbage collection or worker disposal when memory threshold limits (e.g., 64MB per worker) are exceeded.
- Engineers MUST ALWAYS wrap worker messaging in safe cleanup blocks (`finally { worker.terminate(); }`) for ephemeral tenant jobs to prevent dangling thread handles.

## Bad vs Good Implementations
### Unbounded Main-Thread Execution vs. Sandboxed Worker with Heap and Time Ceilings

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct code evaluation via `new Function` runs within the host thread's heap. An infinite loop locks up the Bun event loop, and allocations pollute host memory with no recovery mechanism.
```typescript
import { type Context } from "elysia";

// ANTI-PATTERN: Executing untrusted tenant script directly in main thread.
// A rogue script can hijack globals, leak memory, or cause an unrecoverable process OOM.
export async function executeTenantJob(tenantId: string, userScript: string, payload: unknown) {
  const sandbox = {
    tenantId,
    data: payload,
    result: null,
  };

  // DANGEROUS: Evaluates code directly in host JSC context
  const runner = new Function("sandbox", `
    with (sandbox) {
      ${userScript}
    }
  `);
  
  runner(sandbox);
  return sandbox.result;
}
```

#### Production Standard (Correct)
> **Standard**: Executes the tenant script inside a distinct WebWorker thread using Bun's `{ smol: true }` option. Enforces strict wall-clock termination via AbortController, monitors worker heap usage, clones input buffers to prevent cross-realm reference contamination, and always calls worker.terminate() in a `finally` block.
```typescript
import { resolve } from "node:path";

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

interface WorkerTaskResult {
  success: boolean;
  output?: unknown;
  error?: string;
}

export async function executeTenantJobIsolated(
  tenantId: string,
  scriptPath: string,
  payload: Record<string, unknown>,
  options: ExecutionOptions = {}
): Promise<WorkerTaskResult> {
  const { timeoutMs = 2500, maxMemoryBytes = 64 * 1024 * 1024 } = options;
  const abortController = new AbortController();
  
  // Spin up an isolated WebWorker configured with compact memory footprint
  const worker = new Worker(resolve(import.meta.dir, "./tenant-sandbox.worker.ts"), {
    smol: true,
  });

  const timeoutId = setTimeout(() => {
    abortController.abort(new Error(`Tenant ${tenantId} exceeded CPU time budget of ${timeoutMs}ms`));
    worker.terminate();
  }, timeoutMs);

  try {
    return await new Promise<WorkerTaskResult>((resolvePromise, rejectPromise) => {
      abortController.signal.addEventListener("abort", () => {
        rejectPromise(abortController.signal.reason);
      });

      worker.onmessage = (event: MessageEvent<{ type: string; data: unknown; memoryBytes: number }>) => {
        const { type, data, memoryBytes } = event.data;
        
        if (memoryBytes > maxMemoryBytes) {
          worker.terminate();
          rejectPromise(new Error(`Tenant ${tenantId} exceeded memory limit: ${memoryBytes} bytes`));
          return;
        }

        if (type === "COMPLETE") {
          resolvePromise({ success: true, output: data });
        } else if (type === "ERROR") {
          resolvePromise({ success: false, error: String(data) });
        }
      };

      worker.onerror = (err) => {
        rejectPromise(new Error(`Worker fatal error: ${err.message}`));
      };

      // Post strictly serialized payload to worker
      worker.postMessage({
        tenantId,
        targetScript: scriptPath,
        payload: structuredClone(payload),
      });
    });
  } finally {
    clearTimeout(timeoutId);
    // Ensure worker thread is completely killed to prevent memory leakage
    worker.terminate();
  }
}
```

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 Multi-Tenant Worker Memory Isolation & Execution Quotas

Bun 1.2 Multi-Tenant Worker Memory Isolation & Execution Quotas defines an industrial-grade behavioral standard for backend engineering. Enforces strict heap budgets, thread-level WebWorker isolation, and execution CPU/memory quotas when running untrusted multi-tenant workloads in Bun 1.2. Prohibits in-process evaluation and ensures all worker instances are aggressively terminated via deterministic abort signals and heap bounds to prevent noisy-neighbor memory leakage. 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: Executing untrusted tenant code within the primary process heap or unmetered, long-lived WebWorkers without hard termination ceilings. 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 DriftExecuting untrusted tenant code within the primary process heap or unmetered, long-lived WebWorkers without hard termination ceilings.Critical
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 instantiate isolated WebWorkers using `new Worker(new URL(..., import.meta.url), { smol

Engineers MUST ALWAYS instantiate isolated WebWorkers using `new Worker(new URL(..., import.meta.url), { smol: true })` for tenant execution to reduce baseline 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.
2

Engineers MUST NOT execute tenant-provided code via `eval()`, `new Function()`, or dynamic `import()` within the host application thread or shared worker pools.

Engineers MUST NOT execute tenant-provided code via `eval()`, `new Function()`, or dynamic `import()` within the host application thread or shared worker pools.

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 ALWAYS enforce an absolute wall-clock CPU timeout using `AbortController` coupled with `worker.terminate()` to guarantee tenant execution bounds.

Engineers MUST ALWAYS enforce an absolute wall-clock CPU timeout using `AbortController` coupled with `worker.terminate()` to guarantee tenant execution bounds.

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 communicate solely via strictly serialized structured clone messages or `ArrayBuffer` transfers

Workers MUST communicate solely via strictly serialized structured clone messages or `ArrayBuffer` transfers; shared mutable state across tenant boundaries is strictly prohibited.

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

Worker managers MUST inspect memory delta and trigger explicit garbage collection or worker disposal when memory threshold limits (e.g., 64MB per worker) are exceeded.

Worker managers MUST inspect memory delta and trigger explicit garbage collection or worker disposal when memory threshold limits (e.g., 64MB per worker) are exceeded.

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

Engineers MUST ALWAYS wrap worker messaging in safe cleanup blocks (`finally { worker.terminate()

Engineers MUST ALWAYS wrap worker messaging in safe cleanup blocks (`finally { worker.terminate(); }`) for ephemeral tenant jobs to prevent dangling thread handles.

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 Multi-Tenant Worker Memory Isolation & Execution Quotas critical for AI coding assistants?

Enforces strict heap budgets, thread-level WebWorker isolation, and execution CPU/memory quotas when running untrusted multi-tenant workloads in Bun 1.2. Prohibits in-process evaluation and ensures all worker instances are aggressively terminated via deterministic abort signals and heap bounds to prevent noisy-neighbor memory leakage. 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 (Executing untrusted tenant code within the primary process heap or unmetered, long-lived WebWorkers without hard termination ceilings.) 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