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

Bun 1.2 Worker Thread AsyncLocalStorage Tenant Context Isolation

Enforces strict tenant boundary isolation and distributed tracing propagation across pooled native Worker threads in Bun 1.2+. Guarantees that AsyncLocalStorage (ALS) store references are explicitly reinvoked per dispatched event and never shared across native thread boundaries or leaked via ambient parent worker scopes.

Prohibited Anti-Pattern: Ambient or Cross-Dispatched AsyncLocalStorage State Bleed in Pooled Native Worker Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker Thread AsyncLocalStorage Tenant Context Isolation - Enforces strict tenant boundary isolation and distributed tracing propagation across pooled native Worker threads in Bun 1.2+. Guarantees that AsyncLocalStorage (ALS) store references are explicitly reinvoked per dispatched event and never shared across native thread boundaries or leaked via ambient parent worker scopes.
globs: src/**/workers/**/*.{ts,js}, src/**/worker-pool/**/*.{ts,js}, src/**/*.worker.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-asynclocalstorage-context-isolation"
---

# Bun 1.2 Worker Thread AsyncLocalStorage Tenant Context Isolation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ambient or Cross-Dispatched AsyncLocalStorage State Bleed in Pooled Native Worker Threads

## System Constraints
You are a Principal Backend Architect enforcing zero-leak multi-tenancy and context propagation in Bun 1.2+ native worker thread pools. Native threads do not automatically serialize or propagate AsyncLocalStorage (ALS) instances from the coordinator; ALS stores initialized at the worker module root persist across multiple event-loop message dispatches on the same thread, causing catastrophic cross-tenant context pollution. You must enforce explicit request-scoped store binding using `storage.run()` on every inbound worker message and ensure that tenant identifiers and trace vectors are strictly decoupled between distinct dispatches.

## Strict Guidelines
- Engineers MUST ALWAYS wrap every incoming native worker `message` event handler body inside `storage.run(newContext, async () => { ... })`.
- Engineers MUST NOT rely on ambient module-level AsyncLocalStorage states or global variables to retain context across consecutive dispatches in persistent pooled workers.
- Services MUST serialize tenant ID, trace parent headers, and correlation metadata explicitly in the `postMessage` payload and reconstruct ALS state inside the worker.
- Code MUST explicitly validate and cleanse tenant context before dispatching downstream database calls or subprocess executions inside worker routines.
- Engineers MUST NEVER use `storage.enterWith()` in persistent worker event listeners, as it leaks context into subsequent event loop ticks for future worker tasks.

## Bad vs Good Implementations
### Context Leakage via Global ALS in Bun Pooled Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `enterWith` inside a persistent worker message handler permanently mutates the worker's asynchronous context. When the native thread is reused for another tenant's task, context from the previous dispatch bleeds into the new task if an error occurs or before reassignment completes.
```typescript
import { AsyncLocalStorage } from "node:async_hooks";

interface ExecutionContext {
  tenantId: string;
  traceId: string;
}

export const tenantStorage = new AsyncLocalStorage<ExecutionContext>();

// ANTI-PATTERN: enterWith permanently attaches state to the pooled worker's event loop
declare var self: Worker;
self.onmessage = async (event: MessageEvent<{ tenantId: string; traceId: string; payload: unknown }>) => {
  const { tenantId, traceId, payload } = event.data;
  
  // DANGEROUS: Leaks across subsequent message dispatches within the same native thread
  tenantStorage.enterWith({ tenantId, traceId });

  const result = await processPayload(payload);
  self.postMessage({ result, tenantId: tenantStorage.getStore()?.tenantId });
};

async function processPayload(payload: unknown) {
  const ctx = tenantStorage.getStore();
  // Under concurrency or unhandled rejections, previous tenant data bleeds into next job
  return { processed: true, tenant: ctx?.tenantId };
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping message handling logic within `tenantStorage.run()` guarantees that context is scoped strictly to that asynchronous task execution subtree. Even when native worker threads are pooled and reused across millions of events, tenant boundaries remain strictly isolated.
```typescript
import { AsyncLocalStorage } from "node:async_hooks";

export interface WorkerTaskContext {
  readonly tenantId: string;
  readonly traceId: string;
}

export const tenantStorage = new AsyncLocalStorage<WorkerTaskContext>();

declare var self: Worker;

self.onmessage = (event: MessageEvent<{ tenantId: string; traceId: string; payload: unknown }>) => {
  const { tenantId, traceId, payload } = event.data;
  
  if (!tenantId || !traceId) {
    throw new Error("Protocol violation: Missing required tenant or trace context.");
  }

  const context: WorkerTaskContext = Object.freeze({
    tenantId,
    traceId,
  });

  // SAFE: Bound execution ensures clean tear-down and total context isolation per message
  tenantStorage.run(context, async () => {
    try {
      const result = await processPayload(payload);
      self.postMessage({ success: true, result });
    } catch (err: unknown) {
      const error = err instanceof Error ? err.message : "Unknown worker failure";
      self.postMessage({ success: false, error, traceId: context.traceId });
    }
  });
};

async function processPayload(payload: unknown) {
  const ctx = tenantStorage.getStore();
  if (!ctx) {
    throw new Error("Unrecoverable state: ExecutionContext missing in worker task.");
  }
  return { processed: true, tenant: ctx.tenantId };
}
```

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 Worker Thread AsyncLocalStorage Tenant Context Isolation

Bun 1.2 Worker Thread AsyncLocalStorage Tenant Context Isolation defines an industrial-grade behavioral standard for backend engineering. Enforces strict tenant boundary isolation and distributed tracing propagation across pooled native Worker threads in Bun 1.2+. Guarantees that AsyncLocalStorage (ALS) store references are explicitly reinvoked per dispatched event and never shared across native thread boundaries or leaked via ambient parent worker scopes. 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: Ambient or Cross-Dispatched AsyncLocalStorage State Bleed in Pooled Native Worker Threads 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 DriftAmbient or Cross-Dispatched AsyncLocalStorage State Bleed in Pooled Native Worker ThreadsCritical
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 wrap every incoming native worker `message` event handler body inside `storage.run(newContext, async () => { ... })`.

Engineers MUST ALWAYS wrap every incoming native worker `message` event handler body inside `storage.run(newContext, async () => { ... })`.

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 ambient module-level AsyncLocalStorage states or global variables to retain context across consecutive dispatches in persistent pooled workers.

Engineers MUST NOT rely on ambient module-level AsyncLocalStorage states or global variables to retain context across consecutive dispatches in persistent pooled workers.

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 serialize tenant ID, trace parent headers, and correlation metadata explicitly in the `postMessage` payload and reconstruct ALS state inside the worker.

Services MUST serialize tenant ID, trace parent headers, and correlation metadata explicitly in the `postMessage` payload and reconstruct ALS state inside the worker.

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

Code MUST explicitly validate and cleanse tenant context before dispatching downstream database calls or subprocess executions inside worker routines.

Code MUST explicitly validate and cleanse tenant context before dispatching downstream database calls or subprocess executions inside worker routines.

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

Engineers MUST NEVER use `storage.enterWith()` in persistent worker event listeners, as it leaks context into subsequent event loop ticks for future worker tasks.

Engineers MUST NEVER use `storage.enterWith()` in persistent worker event listeners, as it leaks context into subsequent event loop ticks for future worker tasks.

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 Worker Thread AsyncLocalStorage Tenant Context Isolation critical for AI coding assistants?

Enforces strict tenant boundary isolation and distributed tracing propagation across pooled native Worker threads in Bun 1.2+. Guarantees that AsyncLocalStorage (ALS) store references are explicitly reinvoked per dispatched event and never shared across native thread boundaries or leaked via ambient parent worker scopes. 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 (Ambient or Cross-Dispatched AsyncLocalStorage State Bleed in Pooled Native Worker Threads) 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