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

Go Chi v5 Panic-Safe W3C Trace & Baggage Propagation Standard

Enforces deterministic extraction and injection of W3C Trace Context (traceparent, tracestate) and distributed Baggage across Go Chi v5 middleware chains. Guarantees panic-safe span lifecycle management, semantic error recording, and context preservation to eliminate orphan traces and broken distributed causality.

Prohibited Anti-Pattern: Broken Context Inheritance and Leaked Spans via Manual Header Handling or Naive Middleware Chaining

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi v5 Panic-Safe W3C Trace & Baggage Propagation Standard - Enforces deterministic extraction and injection of W3C Trace Context (traceparent, tracestate) and distributed Baggage across Go Chi v5 middleware chains. Guarantees panic-safe span lifecycle management, semantic error recording, and context preservation to eliminate orphan traces and broken distributed causality.
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-w3c-otel-context-propagation-guardrail"
---

# Go Chi v5 Panic-Safe W3C Trace & Baggage Propagation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Broken Context Inheritance and Leaked Spans via Manual Header Handling or Naive Middleware Chaining

## System Constraints
You are a Principal Software Architect enforcing zero-loss W3C context and span propagation within Go Chi v5 HTTP microservices. You mandate strictly structured OpenTelemetry propagation using TextMapPropagator, panic-defended span boundaries, and baggage synchronization across HTTP request lifecycles. Ensure every middleware retains Chi route contexts and accurately attaches span lifecycle hooks.

## Strict Guidelines
- Engineers MUST ALWAYS extract distributed context using otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) before starting a root/child span in Chi middleware.
- Engineers MUST NEVER replace r.Context() with context.Background() or context.TODO() inside handlers or intermediate middleware, preserving existing trace, baggage, and chi.RouteContext pointers.
- Middleware MUST defer span.End() immediately after tracer.Start and MUST capture panic events with recover(), recording the panic via span.RecordError and setting codes.Error before re-panicking or delegating to Chi's recoverer.
- Engineers MUST configure standard OpenTelemetry semconv HTTP server attributes (http.request.method, url.path, client.address) at span initialization and dynamically enrich the span name using chi.RouteContext(r.Context()).RoutePattern() post-execution.
- Services MUST serialize and propagate baggage across outgoing downstream HTTP calls by injecting the span and baggage context into outgoing request headers using otel.GetTextMapPropagator().Inject.

## Bad vs Good Implementations
### OpenTelemetry W3C Middleware Implementation in Chi v5

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates a disconnected root trace that discards incoming W3C headers (traceparent/tracestate), drops Chi route context by using context.Background(), and leaks unfinalized spans if downstream handlers panic.
```go
package middleware

import (
	"context"
	"net/http"
	"go.opentelemetry.io/otel"
)

func TracingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Ignoring incoming W3C traceparent headers and baggage
		// Starting a disconnected span on an isolated context
		tracer := otel.GetTracerProvider().Tracer("http-service")
		ctx, span := tracer.Start(context.Background(), r.URL.Path)
		// ANTI-PATTERN: span.End() is not protected against panics

		r = r.WithContext(ctx)
		next.ServeHTTP(w, r)
		span.End()
	})
}
```

#### Production Standard (Correct)
> **Standard**: Correctly extracts W3C trace and baggage headers using TextMapPropagator, starts a SpanKindServer span on the extracted context, guarantees span finalization and error recording on panic, and applies standard semantic route conventions via Chi's RouteContext.
```go
package middleware

import (
	"fmt"
	"net/http"
	"github.com/go-chi/chi/v5"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/codes"
	"go.opentelemetry.io/otel/propagation"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
	"go.opentelemetry.io/otel/trace"
)

func TraceAndBaggageMiddleware(tracerName string) func(http.Handler) http.Handler {
	tracer := otel.GetTracerProvider().Tracer(tracerName)
	propagator := otel.GetTextMapPropagator()

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// Extract incoming W3C trace context and baggage into request context
			ctx := propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header))

			attrs := []trace.SpanStartOption{
				trace.WithSpanKind(trace.SpanKindServer),
				trace.WithAttributes(
					semconv.HTTPRequestMethodKey.String(r.Method),
					semconv.URLPath(r.URL.Path),
				),
			}

			ctx, span := tracer.Start(ctx, fmt.Sprintf("HTTP %s", r.Method), attrs...)
			defer span.End()

			// Ensure panics capture error status before bubbling to Chi Recoverer
			defer func() {
				if rec := recover(); rec != nil {
					span.SetStatus(codes.Error, "panic recovered")
					if err, ok := rec.(error); ok {
						span.RecordError(err)
					} else {
						span.RecordError(fmt.Errorf("%v", rec))
					}
					panic(rec) // Re-throw to retain upstream error handling
				}
			}()

			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)

			// Enrich route pattern after handler resolution completes
			if routeCtx := chi.RouteContext(r.Context()); routeCtx != nil {
				if pattern := routeCtx.RoutePattern(); pattern != "" {
					span.SetName(fmt.Sprintf("%s %s", r.Method, pattern))
					span.SetAttributes(semconv.HTTPRoute(pattern))
				}
			}
		})
	}
}
```

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 v5 Panic-Safe W3C Trace & Baggage Propagation Standard

Go Chi v5 Panic-Safe W3C Trace & Baggage Propagation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic extraction and injection of W3C Trace Context (traceparent, tracestate) and distributed Baggage across Go Chi v5 middleware chains. Guarantees panic-safe span lifecycle management, semantic error recording, and context preservation to eliminate orphan traces and broken distributed causality. 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: Broken Context Inheritance and Leaked Spans via Manual Header Handling or Naive Middleware Chaining 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 DriftBroken Context Inheritance and Leaked Spans via Manual Header Handling or Naive Middleware ChainingCritical
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 extract distributed context using otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) before starting a root/child span in Chi middleware.

Engineers MUST ALWAYS extract distributed context using otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) before starting a root/child span in Chi middleware.

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 replace r.Context() with context.Background() or context.TODO() inside handlers or intermediate middleware, preserving existing trace, baggage, and chi.RouteContext pointers.

Engineers MUST NEVER replace r.Context() with context.Background() or context.TODO() inside handlers or intermediate middleware, preserving existing trace, baggage, and chi.RouteContext pointers.

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

Middleware MUST defer span.End() immediately after tracer.Start and MUST capture panic events with recover(), recording the panic via span.RecordError and setting codes.Error before re-panicking or delegating to Chi's recoverer.

Middleware MUST defer span.End() immediately after tracer.Start and MUST capture panic events with recover(), recording the panic via span.RecordError and setting codes.Error before re-panicking or delegating to Chi's recoverer.

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 configure standard OpenTelemetry semconv HTTP server attributes (http.request.method, url.path, client.address) at span initialization and dynamically enrich the span name using chi.RouteContext(r.Context()).RoutePattern() post-execution.

Engineers MUST configure standard OpenTelemetry semconv HTTP server attributes (http.request.method, url.path, client.address) at span initialization and dynamically enrich the span name using chi.RouteContext(r.Context()).RoutePattern() post-execution.

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

Services MUST serialize and propagate baggage across outgoing downstream HTTP calls by injecting the span and baggage context into outgoing request headers using otel.GetTextMapPropagator().Inject.

Services MUST serialize and propagate baggage across outgoing downstream HTTP calls by injecting the span and baggage context into outgoing request headers using otel.GetTextMapPropagator().Inject.

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 v5 Panic-Safe W3C Trace & Baggage Propagation Standard critical for AI coding assistants?

Enforces deterministic extraction and injection of W3C Trace Context (traceparent, tracestate) and distributed Baggage across Go Chi v5 middleware chains. Guarantees panic-safe span lifecycle management, semantic error recording, and context preservation to eliminate orphan traces and broken distributed causality. 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 (Broken Context Inheritance and Leaked Spans via Manual Header Handling or Naive Middleware Chaining) 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