This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-als-distributed-trace-propagation-boundary

Bun 1.2 AsyncLocalStorage Context Isolation & Trace Propagation Invariant

Enforces strict AsyncLocalStorage boundary encapsulation across Bun 1.2 native event loop ticks, microtask queues, and Worker thread boundaries. Prevents cross-request context bleeding and orphaned OpenTelemetry spans caused by un-bound async callbacks and unsafe enterWith invocations.

Prohibited Anti-Pattern: Context Bleeding via AsyncLocalStorage.enterWith and Un-bound Worker Thread Dispatches

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 AsyncLocalStorage Context Isolation & Trace Propagation Invariant - Enforces strict AsyncLocalStorage boundary encapsulation across Bun 1.2 native event loop ticks, microtask queues, and Worker thread boundaries. Prevents cross-request context bleeding and orphaned OpenTelemetry spans caused by un-bound async callbacks and unsafe enterWith invocations.
globs: src/**/*.ts, src/**/*.js, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-als-distributed-trace-propagation-boundary"
---

# Bun 1.2 AsyncLocalStorage Context Isolation & Trace Propagation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Context Bleeding via AsyncLocalStorage.enterWith and Un-bound Worker Thread Dispatches

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 AsyncLocalStorage Distributed Trace Propagation Boundary. Mandate invariants regarding async context preservation, banning AsyncLocalStorage.prototype.enterWith, and enforcing deterministic context injection across Worker threads, native WebStreams, and concurrent microtask queues.

## Strict Guidelines
- Engineers MUST NEVER invoke `AsyncLocalStorage.prototype.enterWith()` in production code paths; context must exclusively be scoped via `als.run()` or `als.bind()` to prevent microtask context bleeding in Bun's JavaScriptCore event loop.
- Engineers MUST ALWAYS serialize trace carrier metadata (e.g., W3C `traceparent`, `tracestate`) across native `Worker` message ports and reconstruct ALS context inside the worker execution frame.
- Services MUST wrap asynchronous event listeners and detached stream handlers with `als.bind()` whenever they execute outside the immediate lexical call stack of `als.run()`.
- Engineers MUST NOT rely on implicit context propagation across native FFI boundaries or detached promise chains initiated via `queueMicrotask` or `process.nextTick` without explicit context capture.
- Handlers in `Bun.serve` MUST establish the trace context root inside the top-level `fetch` dispatcher using `als.run()` before any business logic or sub-routine invocations.

## Bad vs Good Implementations
### Bun 1.2 Async Context Scope in Bun.serve and Worker Threads

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using enterWith() mutates the synchronous execution frame and leaks state across concurrent requests interleaved on the same thread. Dispathing to a Worker without serialized trace context breaks distributed lineage.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

interface TraceContext {
  traceId: string;
  spanId: string;
}

const traceStorage = new AsyncLocalStorage<TraceContext>();
const worker = new Worker(new URL('./worker.ts', import.meta.url).href);

export default {
  port: 3000,
  async fetch(req: Request): Promise<Response> {
    const traceId = req.headers.get('x-trace-id') ?? crypto.randomUUID();
    
    // CRITICAL BUG: enterWith leaks across interleaved event loop ticks
    // in Bun's JSC runtime, corrupting context for concurrent requests.
    traceStorage.enterWith({ traceId, spanId: crypto.randomUUID() });

    // CRITICAL BUG: Worker message lacks trace carrier propagation;
    // background processing becomes an orphaned distributed trace span.
    worker.postMessage({ task: 'process_telemetry', data: await req.json() });

    return new Response(JSON.stringify({ status: 'queued', traceId }), {
      headers: { 'content-type': 'application/json' },
    });
  },
};
```

#### Production Standard (Correct)
> **Standard**: Guarantees absolute context boundary safety using AsyncLocalStorage.prototype.run() and strictly forwards serialized trace carrier context to worker threads.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

interface TraceContext {
  traceId: string;
  spanId: string;
}

interface WorkerTaskMessage {
  task: string;
  data: unknown;
  traceContext: TraceContext;
}

export const traceStorage = new AsyncLocalStorage<TraceContext>();
const worker = new Worker(new URL('./worker.ts', import.meta.url).href);

export default {
  port: 3000,
  async fetch(req: Request): Promise<Response> {
    const traceContext: TraceContext = {
      traceId: req.headers.get('x-trace-id') ?? crypto.randomUUID(),
      spanId: crypto.randomUUID(),
    };

    // INVARIANT: run() encapsulates context within the execution tree,
    // ensuring isolation even under high-concurrency microtask interleaving.
    return traceStorage.run(traceContext, async () => {
      const payload = await req.json();
      const currentContext = traceStorage.getStore()!;

      // INVARIANT: Explicit carrier propagation across Worker boundaries
      const message: WorkerTaskMessage = {
        task: 'process_telemetry',
        data: payload,
        traceContext: currentContext,
      };
      worker.postMessage(message);

      return new Response(
        JSON.stringify({ status: 'queued', traceId: currentContext.traceId }),
        { headers: { 'content-type': 'application/json' } }
      );
    });
  },
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 AsyncLocalStorage Context Isolation & Trace Propagation Invariant

Bun 1.2 AsyncLocalStorage Context Isolation & Trace Propagation Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict AsyncLocalStorage boundary encapsulation across Bun 1.2 native event loop ticks, microtask queues, and Worker thread boundaries. Prevents cross-request context bleeding and orphaned OpenTelemetry spans caused by un-bound async callbacks and unsafe enterWith invocations. 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: Context Bleeding via AsyncLocalStorage.enterWith and Un-bound Worker Thread Dispatches 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 DriftContext Bleeding via AsyncLocalStorage.enterWith and Un-bound Worker Thread DispatchesCritical
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 NEVER invoke `AsyncLocalStorage.prototype.enterWith()` in production code paths

Engineers MUST NEVER invoke `AsyncLocalStorage.prototype.enterWith()` in production code paths; context must exclusively be scoped via `als.run()` or `als.bind()` to prevent microtask context bleeding in Bun's JavaScriptCore event loop.

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 ALWAYS serialize trace carrier metadata (e.g., W3C `traceparent`, `tracestate`) across native `Worker` message ports and reconstruct ALS context inside the worker execution frame.

Engineers MUST ALWAYS serialize trace carrier metadata (e.g., W3C `traceparent`, `tracestate`) across native `Worker` message ports and reconstruct ALS context inside the worker execution frame.

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 wrap asynchronous event listeners and detached stream handlers with `als.bind()` whenever they execute outside the immediate lexical call stack of `als.run()`.

Services MUST wrap asynchronous event listeners and detached stream handlers with `als.bind()` whenever they execute outside the immediate lexical call stack of `als.run()`.

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

Engineers MUST NOT rely on implicit context propagation across native FFI boundaries or detached promise chains initiated via `queueMicrotask` or `process.nextTick` without explicit context capture.

Engineers MUST NOT rely on implicit context propagation across native FFI boundaries or detached promise chains initiated via `queueMicrotask` or `process.nextTick` without explicit context capture.

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

Handlers in `Bun.serve` MUST establish the trace context root inside the top-level `fetch` dispatcher using `als.run()` before any business logic or sub-routine invocations.

Handlers in `Bun.serve` MUST establish the trace context root inside the top-level `fetch` dispatcher using `als.run()` before any business logic or sub-routine invocations.

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 Isolation & Trace Propagation Invariant critical for AI coding assistants?

Enforces strict AsyncLocalStorage boundary encapsulation across Bun 1.2 native event loop ticks, microtask queues, and Worker thread boundaries. Prevents cross-request context bleeding and orphaned OpenTelemetry spans caused by un-bound async callbacks and unsafe enterWith invocations. 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 (Context Bleeding via AsyncLocalStorage.enterWith and Un-bound Worker Thread Dispatches) 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