This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-opentelemetry-w3c-trace-propagation

Go Chi OpenTelemetry W3C Trace Context and Baggage Propagation Invariant

Mandates deterministic W3C trace context (traceparent, tracestate) and baggage extraction/injection across Go Chi HTTP routing layers, downstream network calls, and concurrent Goroutine boundaries. Prohibits context severance caused by raw context.Background() usage in asynchronous operations or unpropagated outbound HTTP requests.

Prohibited Anti-Pattern: Trace Context Severance via Unpropagated Goroutines and Raw Outbound HTTP Requests

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi OpenTelemetry W3C Trace Context and Baggage Propagation Invariant - Mandates deterministic W3C trace context (traceparent, tracestate) and baggage extraction/injection across Go Chi HTTP routing layers, downstream network calls, and concurrent Goroutine boundaries. Prohibits context severance caused by raw context.Background() usage in asynchronous operations or unpropagated outbound HTTP requests.
globs: **/*.go, cmd/**/*.go, internal/**/*.go, pkg/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-opentelemetry-w3c-trace-propagation"
---

# Go Chi OpenTelemetry W3C Trace Context and Baggage Propagation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Trace Context Severance via Unpropagated Goroutines and Raw Outbound HTTP Requests

## System Constraints
You are a Principal Backend Systems Architect enforcing strict OpenTelemetry W3C Distributed Tracing standards in Go microservices using the Chi router. You must eliminate all context severance, race conditions, and span orphanages across asynchronous boundaries and outbound RPC/HTTP calls. Enforce explicit context extraction at Chi middleware boundaries, detached context preservation for concurrent goroutines using context.WithoutCancel, and deterministic header injection on all egress requests.

## Strict Guidelines
- Services MUST configure otel.SetTextMapPropagator with propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}) during service bootstrap.
- Chi routers MUST use otelchi middleware (or an equivalent strict W3C TextMapPropagator extraction middleware) as the root middleware before any business or logging logic.
- Handlers spawning concurrent asynchronous tasks MUST NEVER pass raw r.Context() to long-running Goroutines; doing so causes immediate context.Canceled errors when the HTTP response completes.
- Handlers spawning asynchronous tasks MUST NEVER create an isolated context.Background() or context.TODO(); they MUST use context.WithoutCancel(r.Context()) (Go 1.21+) or an equivalent wrapper to preserve trace spans, span context, and baggage while decoupling lifecycle cancellation.
- Outbound HTTP clients MUST ALWAYS call otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) before executing requests, or wrap http.RoundTripper with otelhttp.NewTransport.
- Trace-derived metadata and baggage MUST NEVER be manually parsed using raw string slicing on the 'traceparent' header; use official OpenTelemetry API accessors exclusively.

## Bad vs Good Implementations
### Trace Context Preservation across Goroutine and Egress HTTP Call

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using context.Background() severs the distributed trace graph entirely, orphaning all downstream telemetry into detached single-span traces. Alternatively, using r.Context() in an unjoined goroutine triggers premature context cancellation errors when the HTTP client completes the primary request.
```go
package handler

import (
	"context"
	"net/http"
)

func HandleOrder(w http.ResponseWriter, r *http.Request) {
	// FLUID ANTI-PATTERNS: 
	// 1. Spawning goroutine with raw r.Context() causes runtime cancel races.
	// 2. Fallback to context.Background() completely severs the W3C trace-graph.
	// 3. Outbound HTTP request fails to inject traceparent/tracestate headers.
	go func() {
		bgCtx := context.Background()
		req, _ := http.NewRequestWithContext(bgCtx, http.MethodPost, "https://inventory.internal/reserve", nil)
		_, _ = http.DefaultClient.Do(req)
	}()

	w.WriteHeader(http.StatusAccepted)
}
```

#### Production Standard (Correct)
> **Standard**: Uses context.WithoutCancel to shield the asynchronous background execution from HTTP request lifecycle termination while maintaining full W3C SpanContext and Baggage. Outbound calls explicitly inject W3C headers via TextMapPropagator, ensuring end-to-end distributed trace propagation.
```go
package handler

import (
	"context"
	"net/http"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/trace"
)

func HandleOrder(w http.ResponseWriter, r *http.Request) {
	tr := otel.Tracer("order-service")
	ctx, span := tr.Start(r.Context(), "HandleOrder", trace.WithSpanKind(trace.SpanKindServer))
	defer span.End()

	// 1. Detach cancellation while preserving W3C TraceContext and Baggage (Go 1.21+)
	asyncCtx := context.WithoutCancel(ctx)

	go func(ctx context.Context) {
		asyncCtx, asyncSpan := tr.Start(ctx, "ProcessInventoryAsync", trace.WithSpanKind(trace.SpanKindInternal))
		defer asyncSpan.End()

		req, err := http.NewRequestWithContext(asyncCtx, http.MethodPost, "https://inventory.internal/reserve", nil)
		if err != nil {
			asyncSpan.RecordError(err)
			return
		}

		// 2. Deterministically inject W3C traceparent and baggage into egress request
		otel.GetTextMapPropagator().Inject(asyncCtx, propagation.HeaderCarrier(req.Header))

		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			asyncSpan.RecordError(err)
			return
		}
		defer resp.Body.Close()
	}(asyncCtx)

	w.WriteHeader(http.StatusAccepted)
}
```

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: Go Chi OpenTelemetry W3C Trace Context and Baggage Propagation Invariant

Go Chi OpenTelemetry W3C Trace Context and Baggage Propagation Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic W3C trace context (traceparent, tracestate) and baggage extraction/injection across Go Chi HTTP routing layers, downstream network calls, and concurrent Goroutine boundaries. Prohibits context severance caused by raw context.Background() usage in asynchronous operations or unpropagated outbound HTTP requests. 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: Trace Context Severance via Unpropagated Goroutines and Raw Outbound HTTP Requests 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 DriftTrace Context Severance via Unpropagated Goroutines and Raw Outbound HTTP RequestsCritical
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

Services MUST configure otel.SetTextMapPropagator with propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}) during service bootstrap.

Services MUST configure otel.SetTextMapPropagator with propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}) during service bootstrap.

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

Chi routers MUST use otelchi middleware (or an equivalent strict W3C TextMapPropagator extraction middleware) as the root middleware before any business or logging logic.

Chi routers MUST use otelchi middleware (or an equivalent strict W3C TextMapPropagator extraction middleware) as the root middleware before any business or logging 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.
3

Handlers spawning concurrent asynchronous tasks MUST NEVER pass raw r.Context() to long-running Goroutines

Handlers spawning concurrent asynchronous tasks MUST NEVER pass raw r.Context() to long-running Goroutines; doing so causes immediate context.Canceled errors when the HTTP response completes.

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

Handlers spawning asynchronous tasks MUST NEVER create an isolated context.Background() or context.TODO()

Handlers spawning asynchronous tasks MUST NEVER create an isolated context.Background() or context.TODO(); they MUST use context.WithoutCancel(r.Context()) (Go 1.21+) or an equivalent wrapper to preserve trace spans, span context, and baggage while decoupling lifecycle cancellation.

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

Outbound HTTP clients MUST ALWAYS call otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) before executing requests, or wrap http.RoundTripper with otelhttp.NewTransport.

Outbound HTTP clients MUST ALWAYS call otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) before executing requests, or wrap http.RoundTripper with otelhttp.NewTransport.

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.
6

Trace-derived metadata and baggage MUST NEVER be manually parsed using raw string slicing on the 'traceparent' header

Trace-derived metadata and baggage MUST NEVER be manually parsed using raw string slicing on the 'traceparent' header; use official OpenTelemetry API accessors exclusively.

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 Go Chi OpenTelemetry W3C Trace Context and Baggage Propagation Invariant critical for AI coding assistants?

Mandates deterministic W3C trace context (traceparent, tracestate) and baggage extraction/injection across Go Chi HTTP routing layers, downstream network calls, and concurrent Goroutine boundaries. Prohibits context severance caused by raw context.Background() usage in asynchronous operations or unpropagated outbound HTTP requests. 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 (Trace Context Severance via Unpropagated Goroutines and Raw Outbound HTTP Requests) 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

Go