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-asyncloc-178

Bun 1.2 AsyncLocalStorage Tenant Context Isolation Across Worker Boundaries

Enforces strict tenant context serialization, manual rehydration, and explicit lifecycle boundary isolation when propagating AsyncLocalStorage instances across Bun 1.2 worker thread boundaries. Prevents cross-tenant context bleeding, silent trace dropping, and unbounded heap retention in persistent worker pools.

Prohibited Anti-Pattern: Implicit ALS Propagation Assumption and Leaked Shared Worker State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 AsyncLocalStorage Tenant Context Isolation Across Worker Boundaries - Enforces strict tenant context serialization, manual rehydration, and explicit lifecycle boundary isolation when propagating AsyncLocalStorage instances across Bun 1.2 worker thread boundaries. Prevents cross-tenant context bleeding, silent trace dropping, and unbounded heap retention in persistent worker pools.
globs: src/**/*.{ts,tsx}, workers/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-asynclocalstorage-context-isolation-bun-1-2-asyncloc-178"
---

# Bun 1.2 AsyncLocalStorage Tenant Context Isolation Across Worker Boundaries

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit ALS Propagation Assumption and Leaked Shared Worker State

## System Constraints
You are a Principal Backend Architect enforcing Bun 1.2 AsyncLocalStorage Context Isolation across Worker Boundaries. Mandate explicit envelope serialization, worker-side rehydration via als.run(), and absolute heap isolation across concurrent tenant dispatches.

## Strict Guidelines
- Engineers MUST ALWAYS serialize execution context (tenantId, traceId, correlationTokens) into an immutable transport envelope before posting messages to Bun worker threads.
- Engineers MUST NEVER assume AsyncLocalStorage automatically propagates across Bun Worker or WorkerPool thread boundaries.
- Worker message listeners MUST ALWAYS wrap task execution within `tenantStorage.run(deserializedContext, async () => ...)` to ensure synchronous and asynchronous stack isolation.
- Services MUST NOT store tenant or request context in module-scoped or global variables inside long-lived persistent worker threads.
- Code MUST explicitly decouple large payload references from the rehydrated context envelope to prevent uncollected memory retention in the V8/JSC heap across worker job lifecycles.

## Bad vs Good Implementations
### Cross-Worker Boundary Context Propagation & Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: AsyncLocalStorage state is dropped entirely across worker boundaries. The worker attempts to manage state via a module-scoped variable, which persists across subsequent tasks on the same pooled worker thread, causing critical multi-tenant data leakage and memory retention.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

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

export const tenantStorage = new AsyncLocalStorage<TenantContext>();
let activeWorkerContext: TenantContext | undefined; // Anti-pattern: shared thread-global state

// Main thread dispatch
export function dispatchToWorker(worker: Worker, taskPayload: unknown) {
  // Anti-pattern: Fails to pass ALS state; assumes worker inherits execution context
  worker.postMessage({ payload: taskPayload });
}

// Worker thread execution script
self.onmessage = async (event: MessageEvent) => {
  const { payload } = event.data;
  // Anti-pattern: Retaining state in outer scope causes cross-task leakage in persistent pools
  activeWorkerContext = { tenantId: 'leaked-tenant', traceId: 'stale-trace' };
  await processTask(payload);
  // activeWorkerContext is never cleared, leaking references and tenant context
};

async function processTask(data: unknown) {
  console.log(`Processing under: ${activeWorkerContext?.tenantId}`);
}
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

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

export interface WorkerTaskEnvelope<T> {
  readonly context: TenantContext;
  readonly payload: T;
}

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

// Main thread dispatch: explicitly extracts context and packages it into an envelope
export function dispatchToWorker<T>(worker: Worker, payload: T): void {
  const currentContext = tenantStorage.getStore();
  if (!currentContext) {
    throw new Error('Tenant context required for background worker dispatch');
  }

  const envelope: WorkerTaskEnvelope<T> = {
    context: Object.freeze({ ...currentContext }),
    payload
  };

  worker.postMessage(envelope);
}

// Worker thread execution script: rehydrates and isolates task scope
self.onmessage = async (event: MessageEvent<WorkerTaskEnvelope<unknown>>) => {
  const { context, payload } = event.data;

  // Strict rehydration inside storage.run ensures clean async cleanup per task
  await tenantStorage.run(context, async () => {
    try {
      await processTask(payload);
    } finally {
      // The context automatically falls out of ALS scope, preventing retention
    }
  });
};

async function processTask(data: unknown): Promise<void> {
  const ctx = tenantStorage.getStore();
  console.log(`Securely processing for tenant: ${ctx?.tenantId}, trace: ${ctx?.traceId}`);
}
```

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

Bun 1.2 AsyncLocalStorage Tenant Context Isolation Across Worker Boundaries defines an industrial-grade behavioral standard for backend engineering. Enforces strict tenant context serialization, manual rehydration, and explicit lifecycle boundary isolation when propagating AsyncLocalStorage instances across Bun 1.2 worker thread boundaries. Prevents cross-tenant context bleeding, silent trace dropping, and unbounded heap retention in persistent worker pools. 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: Implicit ALS Propagation Assumption and Leaked Shared Worker State 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 DriftImplicit ALS Propagation Assumption and Leaked Shared Worker StateCritical
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 serialize execution context (tenantId, traceId, correlationTokens) into an immutable transport envelope before posting messages to Bun worker threads.

Engineers MUST ALWAYS serialize execution context (tenantId, traceId, correlationTokens) into an immutable transport envelope before posting messages to Bun worker threads.

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 NEVER assume AsyncLocalStorage automatically propagates across Bun Worker or WorkerPool thread boundaries.

Engineers MUST NEVER assume AsyncLocalStorage automatically propagates across Bun Worker or WorkerPool thread boundaries.

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

Worker message listeners MUST ALWAYS wrap task execution within `tenantStorage.run(deserializedContext, async () => ...)` to ensure synchronous and asynchronous stack isolation.

Worker message listeners MUST ALWAYS wrap task execution within `tenantStorage.run(deserializedContext, async () => ...)` to ensure synchronous and asynchronous stack isolation.

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

Services MUST NOT store tenant or request context in module-scoped or global variables inside long-lived persistent worker threads.

Services MUST NOT store tenant or request context in module-scoped or global variables inside long-lived persistent worker threads.

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

Code MUST explicitly decouple large payload references from the rehydrated context envelope to prevent uncollected memory retention in the V8/JSC heap across worker job lifecycles.

Code MUST explicitly decouple large payload references from the rehydrated context envelope to prevent uncollected memory retention in the V8/JSC heap across worker job lifecycles.

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

Enforces strict tenant context serialization, manual rehydration, and explicit lifecycle boundary isolation when propagating AsyncLocalStorage instances across Bun 1.2 worker thread boundaries. Prevents cross-tenant context bleeding, silent trace dropping, and unbounded heap retention in persistent worker pools. 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 (Implicit ALS Propagation Assumption and Leaked Shared Worker State) 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