This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-async-queue-context-propagation

OpenTelemetry Trace Context and Baggage Propagation Across Asynchronous Task Queues

Enforces deterministic causal distributed tracing and transactional baggage preservation across asynchronous worker pools, task queues, and decentralized event boundaries. Mandates explicit W3C TraceContext and Baggage injection at enqueue time and root context extraction with span linking at execution time. Eliminates broken distributed causal graphs and context leakage across shared concurrency runtimes.

Prohibited Anti-Pattern: Silent Context Severing and Blind Asynchronous Worker Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry Trace Context and Baggage Propagation Across Asynchronous Task Queues - Enforces deterministic causal distributed tracing and transactional baggage preservation across asynchronous worker pools, task queues, and decentralized event boundaries. Mandates explicit W3C TraceContext and Baggage injection at enqueue time and root context extraction with span linking at execution time. Eliminates broken distributed causal graphs and context leakage across shared concurrency runtimes.
globs: src/queues/**/*.{ts,js}, src/workers/**/*.{ts,js}, src/jobs/**/*.{ts,js}, src/messaging/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-async-queue-context-propagation"
---

# OpenTelemetry Trace Context and Baggage Propagation Across Asynchronous Task Queues

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Silent Context Severing and Blind Asynchronous Worker Execution

## System Constraints
You are a Principal Observability Architect enforcing OpenTelemetry standards across asynchronous execution boundaries. You must strictly mandate bidirectional W3C traceparent, tracestate, and baggage injection into message metadata on task publication, and explicit context extraction with context-scoped execution on worker consumption. Never allow implicit or headless queue operations.

## Strict Guidelines
- Engineers MUST ALWAYS inject active OpenTelemetry trace context and baggage into message metadata using `propagation.inject(context.active(), carrier)` immediately prior to enqueuing a task.
- Engineers MUST NOT rely on runtime ambient context surviving across process boundaries, asynchronous thread pools, or event loop queues without explicit serializable metadata carriers.
- Services MUST extract the trace context on the consumer side via `propagation.extract(ROOT_CONTEXT, message.headers)` before instantiating child spans or invoking business logic.
- Workers MUST execute task payloads inside `context.with(extractedContext, ...)` to maintain execution-scoped storage and prevent context leakage across reused worker processes.
- Code SHOULD designate producer operations as `SpanKind.PRODUCER` and consumer execution entry points as `SpanKind.CONSUMER` to conform with OpenTelemetry Semantic Conventions.

## Bad vs Good Implementations
### Asynchronous Queue Context Propagation (Producer & Consumer)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The producer fails to serialize the active OpenTelemetry context into the job metadata, and the worker initiates a detached root span. This severs causality, drops upstream baggage attributes (such as tenant or correlation IDs), and creates fragmented traces.
```typescript
import { Queue, Worker, Job } from 'bullmq';
import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('order-service');
const orderQueue = new Queue('orders');

// BAD: Enqueues job without injecting trace context or baggage into payload/metadata
export async function enqueueOrder(orderId: string, correlationId: string) {
  return tracer.startActiveSpan('enqueueOrder', async (span) => {
    await orderQueue.add('process-order', { orderId, correlationId });
    span.end();
  });
}

// BAD: Worker executes in an orphaned context; breaks the distributed causal trace
new Worker('orders', async (job: Job) => {
  return tracer.startActiveSpan('processOrderWorker', async (span) => {
    // Orphan root span: traceparent and upstream baggage are completely lost
    await processOrder(job.data.orderId);
    span.end();
  });
});

async function processOrder(id: string) {}
```

#### Production Standard (Correct)
> **Standard**: The producer injects the active context into `job.data.traceCarrier`. The consumer extracts this carrier to reconstruct the exact upstream context using `ROOT_CONTEXT`, executing within `context.with()` and opening a `SpanKind.CONSUMER` child span that retains end-to-end distributed causality.
```typescript
import { Queue, Worker, Job } from 'bullmq';
import { trace, context, propagation, SpanKind, ROOT_CONTEXT } from '@opentelemetry/api';

const tracer = trace.getTracer('order-service');
const orderQueue = new Queue('orders');

interface QueuePayload<T> {
  data: T;
  traceCarrier: Record<string, string>;
}

// GOOD: Injects current context (traceparent, baggage) into carrier metadata
export async function enqueueOrder(orderId: string) {
  return tracer.startActiveSpan('enqueueOrder', { kind: SpanKind.PRODUCER }, async (span) => {
    try {
      const traceCarrier: Record<string, string> = {};
      propagation.inject(context.active(), traceCarrier);

      await orderQueue.add('process-order', {
        data: { orderId },
        traceCarrier,
      });
    } finally {
      span.end();
    }
  });
}

// GOOD: Extracts carrier into parent context and establishes linked consumer span
new Worker('orders', async (job: Job<QueuePayload<{ orderId: string }>>) => {
  const extractedContext = propagation.extract(ROOT_CONTEXT, job.data.traceCarrier);

  return context.with(extractedContext, async () => {
    return tracer.startActiveSpan(
      'processOrderWorker',
      { kind: SpanKind.CONSUMER },
      async (span) => {
        try {
          await processOrder(job.data.data.orderId);
        } catch (err) {
          span.recordException(err as Error);
          throw err;
        } finally {
          span.end();
        }
      }
    );
  });
});

async function processOrder(id: string) {}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry Trace Context and Baggage Propagation Across Asynchronous Task Queues

OpenTelemetry Trace Context and Baggage Propagation Across Asynchronous Task Queues defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic causal distributed tracing and transactional baggage preservation across asynchronous worker pools, task queues, and decentralized event boundaries. Mandates explicit W3C TraceContext and Baggage injection at enqueue time and root context extraction with span linking at execution time. Eliminates broken distributed causal graphs and context leakage across shared concurrency runtimes. 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: Silent Context Severing and Blind Asynchronous Worker Execution 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 DriftSilent Context Severing and Blind Asynchronous Worker ExecutionCritical
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 inject active OpenTelemetry trace context and baggage into message metadata using `propagation.inject(context.active(), carrier)` immediately prior to enqueuing a task.

Engineers MUST ALWAYS inject active OpenTelemetry trace context and baggage into message metadata using `propagation.inject(context.active(), carrier)` immediately prior to enqueuing a task.

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 runtime ambient context surviving across process boundaries, asynchronous thread pools, or event loop queues without explicit serializable metadata carriers.

Engineers MUST NOT rely on runtime ambient context surviving across process boundaries, asynchronous thread pools, or event loop queues without explicit serializable metadata carriers.

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 extract the trace context on the consumer side via `propagation.extract(ROOT_CONTEXT, message.headers)` before instantiating child spans or invoking business logic.

Services MUST extract the trace context on the consumer side via `propagation.extract(ROOT_CONTEXT, message.headers)` before instantiating child spans or invoking business logic.

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 execute task payloads inside `context.with(extractedContext, ...)` to maintain execution-scoped storage and prevent context leakage across reused worker processes.

Workers MUST execute task payloads inside `context.with(extractedContext, ...)` to maintain execution-scoped storage and prevent context leakage across reused worker processes.

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 SHOULD designate producer operations as `SpanKind.PRODUCER` and consumer execution entry points as `SpanKind.CONSUMER` to conform with OpenTelemetry Semantic Conventions.

Code SHOULD designate producer operations as `SpanKind.PRODUCER` and consumer execution entry points as `SpanKind.CONSUMER` to conform with OpenTelemetry Semantic Conventions.

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 OpenTelemetry Trace Context and Baggage Propagation Across Asynchronous Task Queues critical for AI coding assistants?

Enforces deterministic causal distributed tracing and transactional baggage preservation across asynchronous worker pools, task queues, and decentralized event boundaries. Mandates explicit W3C TraceContext and Baggage injection at enqueue time and root context extraction with span linking at execution time. Eliminates broken distributed causal graphs and context leakage across shared concurrency runtimes. 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 (Silent Context Severing and Blind Asynchronous Worker Execution) 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

OpenTelemetry