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

Bun 1.2 AsyncLocalStorage Context Preservation and Tenant Isolation Across Native Worker Threads

Enforces deterministic serialization, boundary transport, and safe re-hydration of AsyncLocalStorage context across Bun 1.2 native Worker threads. Guarantees zero trace context loss and eliminates catastrophic cross-tenant credential or telemetry bleeding caused by mutable worker pools and implicit thread boundaries.

Prohibited Anti-Pattern: Implicit Async Context Assumption Across postMessage Thread Boundaries Causing Telemetry Evaporation and Tenant Impersonation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 AsyncLocalStorage Context Preservation and Tenant Isolation Across Native Worker Threads - Enforces deterministic serialization, boundary transport, and safe re-hydration of AsyncLocalStorage context across Bun 1.2 native Worker threads. Guarantees zero trace context loss and eliminates catastrophic cross-tenant credential or telemetry bleeding caused by mutable worker pools and implicit thread boundaries.
globs: src/**/*.ts, workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-als-worker-context-preservation"
---

# Bun 1.2 AsyncLocalStorage Context Preservation and Tenant Isolation Across Native Worker Threads

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit Async Context Assumption Across postMessage Thread Boundaries Causing Telemetry Evaporation and Tenant Impersonation

## System Constraints
You are a Principal Backend Architect enforcing strict execution boundaries in Bun 1.2 runtimes. Bun native Worker threads do NOT inherit AsyncLocalStorage (ALS) from parent threads. You must ensure all asynchronous context, tenant identities, and distributed trace carriers are explicitly serialized into immutable envelopes, transferred across postMessage boundaries, and reconstituted using AsyncLocalStorage.run() within worker scopes. Disallow any module-scoped state in workers that can bleed across tasks.

## Strict Guidelines
- Engineers MUST ALWAYS wrap worker dispatch payloads in a strictly typed context envelope containing traceparent, tenantId, and authorization claims.
- Engineers MUST NOT rely on AsyncLocalStorage inheritance across Bun Worker boundaries, as worker threads initialize completely disjoint V8/JavaScriptCore heaps.
- Code MUST wrap worker message handler execution in `asyncLocalStorage.run(envelope.context, async () => { ... })` to scope state exclusively to that discrete invocation.
- Services MUST sanitize, validate, and freeze incoming context payloads before executing worker business logic to prevent prototype pollution or unverified tenant switching.
- Components NEVER store tenant-scoped data in top-level or module-scoped variables within worker source files, as long-lived worker pools will leak state across sequential tasks.

## Bad vs Good Implementations
### Context Bleed and Loss in Bun Worker Pool

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: AsyncLocalStorage state does not cross thread boundaries. The parent thread drops the trace, while the worker relies on mutable module-level state (`currentTenantId`), causing high-concurrency race conditions where Tenant B executes under Tenant A's identity.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

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

const als = new AsyncLocalStorage<RequestContext>();

// Parent thread passes raw payload; ALS is lost across Worker boundary
export function dispatchToWorker(worker: Worker, data: Uint8Array) {
  // Anti-pattern: Assuming worker magically sees 'als.getStore()'
  worker.postMessage({ data });
}

// Inside worker.ts
let currentTenantId: string; // Anti-pattern: Module-level state causes cross-tenant bleeding!

self.onmessage = async (event: MessageEvent) => {
  // Trace context is completely missing here
  // Using a shared mutable reference leaks previous tenant if an error or reuse occurs
  currentTenantId = event.data.tenantId ?? 'default';
  await processTask(event.data.data, currentTenantId);
};
```

#### Production Standard (Correct)
> **Standard**: Context is explicitly propagated using an immutable `WorkerTaskEnvelope`. The worker re-hydrates the ALS context using `als.run()` per message event, preventing global state pollution and ensuring zero trace context loss across threads.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

export interface WorkerContext {
  readonly tenantId: string;
  readonly traceId: string;
  readonly traceFlags: number;
}

export interface WorkerTaskEnvelope<T = unknown> {
  readonly context: WorkerContext;
  readonly payload: T;
}

export const als = new AsyncLocalStorage<WorkerContext>();

// Parent Thread Dispatcher
export function dispatchToWorker<T>(worker: Worker, payload: T): void {
  const currentContext = als.getStore();
  if (!currentContext) {
    throw new Error('Invariant violation: Cannot dispatch worker task without active ALS context');
  }

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

  worker.postMessage(envelope);
}

// Inside worker.ts (Native Bun Worker)
self.onmessage = async (event: MessageEvent<WorkerTaskEnvelope<Uint8Array>>) => {
  const { context, payload } = event.data;

  if (!context?.tenantId || !context?.traceId) {
    throw new Error('Security violation: Dropping unauthenticated or context-less worker message');
  }

  // Strictly scope the task lifecycle within the re-hydrated context
  await als.run(Object.freeze(context), async () => {
    await processTask(payload);
  });
};

async function processTask(data: Uint8Array): Promise<void> {
  const activeContext = als.getStore();
  // Guaranteed safe, zero-leakage execution for activeContext.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 AsyncLocalStorage Context Preservation and Tenant Isolation Across Native Worker Threads

Bun 1.2 AsyncLocalStorage Context Preservation and Tenant Isolation Across Native Worker Threads defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic serialization, boundary transport, and safe re-hydration of AsyncLocalStorage context across Bun 1.2 native Worker threads. Guarantees zero trace context loss and eliminates catastrophic cross-tenant credential or telemetry bleeding caused by mutable worker pools and implicit thread 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: Implicit Async Context Assumption Across postMessage Thread Boundaries Causing Telemetry Evaporation and Tenant Impersonation 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 Async Context Assumption Across postMessage Thread Boundaries Causing Telemetry Evaporation and Tenant ImpersonationCritical
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 worker dispatch payloads in a strictly typed context envelope containing traceparent, tenantId, and authorization claims.

Engineers MUST ALWAYS wrap worker dispatch payloads in a strictly typed context envelope containing traceparent, tenantId, and authorization claims.

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 AsyncLocalStorage inheritance across Bun Worker boundaries, as worker threads initialize completely disjoint V8/JavaScriptCore heaps.

Engineers MUST NOT rely on AsyncLocalStorage inheritance across Bun Worker boundaries, as worker threads initialize completely disjoint V8/JavaScriptCore heaps.

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

Code MUST wrap worker message handler execution in `asyncLocalStorage.run(envelope.context, async () => { ... })` to scope state exclusively to that discrete invocation.

Code MUST wrap worker message handler execution in `asyncLocalStorage.run(envelope.context, async () => { ... })` to scope state exclusively to that discrete invocation.

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 sanitize, validate, and freeze incoming context payloads before executing worker business logic to prevent prototype pollution or unverified tenant switching.

Services MUST sanitize, validate, and freeze incoming context payloads before executing worker business logic to prevent prototype pollution or unverified tenant switching.

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

Components NEVER store tenant-scoped data in top-level or module-scoped variables within worker source files, as long-lived worker pools will leak state across sequential tasks.

Components NEVER store tenant-scoped data in top-level or module-scoped variables within worker source files, as long-lived worker pools will leak state across sequential 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 AsyncLocalStorage Context Preservation and Tenant Isolation Across Native Worker Threads critical for AI coding assistants?

Enforces deterministic serialization, boundary transport, and safe re-hydration of AsyncLocalStorage context across Bun 1.2 native Worker threads. Guarantees zero trace context loss and eliminates catastrophic cross-tenant credential or telemetry bleeding caused by mutable worker pools and implicit thread 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 (Implicit Async Context Assumption Across postMessage Thread Boundaries Causing Telemetry Evaporation and Tenant Impersonation) 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