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

Deterministic OpenTelemetry Context Propagation Across Goroutines in Go Chi

Enforces strict context propagation across asynchronous goroutine boundaries within Go Chi HTTP services. Passing the raw request context directly to fire-and-forget goroutines causes context cancellation upon HTTP handler return, while spinning up goroutines with context.Background() severs trace lineages and drops baggage. Engineers must explicitly detach cancellation while propagating trace and baggage metadata, or derive child contexts from context.WithoutCancel.

Prohibited Anti-Pattern: Spawning Asynchronous Goroutines with Direct HTTP Request Context or Blank context.Background()

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic OpenTelemetry Context Propagation Across Goroutines in Go Chi - Enforces strict context propagation across asynchronous goroutine boundaries within Go Chi HTTP services. Passing the raw request context directly to fire-and-forget goroutines causes context cancellation upon HTTP handler return, while spinning up goroutines with context.Background() severs trace lineages and drops baggage. Engineers must explicitly detach cancellation while propagating trace and baggage metadata, or derive child contexts from context.WithoutCancel.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-otel-goroutine-context-propagation"
---

# Deterministic OpenTelemetry Context Propagation Across Goroutines in Go Chi

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Asynchronous Goroutines with Direct HTTP Request Context or Blank context.Background()

## System Constraints
You are a Principal Backend Engineer and Distributed Systems Architect enforcing strict OpenTelemetry context propagation across goroutine lifecycles in Go Chi microservices. You mandate that asynchronous background operations preserve SpanContext, Baggage, and telemetry attributes without binding their operational lifecycle to the ephemeral HTTP request cancellation tree.

## Strict Guidelines
- Engineers MUST NEVER pass `r.Context()` directly to long-running, detached, or fire-and-forget goroutines; doing so causes immediate `context.Canceled` errors once the Chi HTTP handler terminates.
- Engineers MUST NEVER spawn detached goroutines initialized with `context.Background()` or `context.TODO()`, as this severs the distributed trace lineage, resets baggage, and produces disconnected orphan root spans.
- Engineers MUST use Go 1.21+ `context.WithoutCancel(ctx)` when launching asynchronous goroutines to decouple request cancellation while deterministically preserving SpanContext and Baggage values.
- Engineers MUST start a new child span using `tracer.Start(detachedCtx, "operation_name")` inside the spawned goroutine and defer `span.End()` to ensure asynchronous execution times are tracked under the parent trace tree.
- Services MUST bound the execution of detached goroutines using `context.WithTimeout` or `context.WithDeadline` derived from the un-canceled context to prevent resource leaks and unmonitored execution hangs.

## Bad vs Good Implementations
### Decoupling Cancellation while Preserving OTel Span Context in Asynchronous Handlers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing req.Context() causes the asynchronous work to abort prematurely because Chi cancels the HTTP request context when the handler returns. Conversely, replacing it with context.Background() breaks the distributed trace correlation, wiping trace IDs and Baggage.
```go
package main

import (
	"context"
	"net/http"
	"github.com/go-chi/chi/v5"
	"go.opentelemetry.io/otel"
)

func MountRoutes(r chi.Router) {
	r.Post("/process", func(w http.ResponseWriter, req *http.Request) {
		// ANTI-PATTERN 1: Passing raw request context will fail immediately
		// with context.Canceled when the handler returns to the Chi dispatcher.
		go func() {
			doHeavyAsyncWork(req.Context())
		}()

		// ANTI-PATTERN 2: Using context.Background() severs trace ID and drops baggage,
		// creating orphan root spans in the APM collector.
		go func() {
			ctx := context.Background()
			tr := otel.Tracer("worker")
			ctx, span := tr.Start(ctx, "orphan_task")
			defer span.End()
			doHeavyAsyncWork(ctx)
		}()

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

#### Production Standard (Correct)
> **Standard**: Using Go 1.21+ context.WithoutCancel retains the OpenTelemetry SpanContext and Baggage in detachedCtx while breaking the cancellation link with the parent HTTP request. Wrapping it in context.WithTimeout ensures finite execution, and starting a new child span maintains valid trace continuity.
```go
package main

import (
	"context"
	"net/http"
	"time"
	"github.com/go-chi/chi/v5"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
)

func MountRoutes(r chi.Router) {
	tr := otel.Tracer("chi-handler")

	r.Post("/process", func(w http.ResponseWriter, req *http.Request) {
		httpCtx := req.Context()
		// PRODUCTION INVARIANT: Preserve trace context and baggage values
		// while stripping request-scoped deadline and cancellation semantics.
		detachedCtx := context.WithoutCancel(httpCtx)

		go func() {
			// Bind an explicit operational timeout to prevent indefinite leakage.
			asyncCtx, cancel := context.WithTimeout(detachedCtx, 30*time.Second)
			defer cancel()

			asyncCtx, span := tr.Start(
				asyncCtx,
				"process.async_worker",
				trace.WithSpanKind(trace.SpanKindInternal),
			)
			defer span.End()

			doHeavyAsyncWork(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: Deterministic OpenTelemetry Context Propagation Across Goroutines in Go Chi

Deterministic OpenTelemetry Context Propagation Across Goroutines in Go Chi defines an industrial-grade behavioral standard for backend engineering. Enforces strict context propagation across asynchronous goroutine boundaries within Go Chi HTTP services. Passing the raw request context directly to fire-and-forget goroutines causes context cancellation upon HTTP handler return, while spinning up goroutines with context.Background() severs trace lineages and drops baggage. Engineers must explicitly detach cancellation while propagating trace and baggage metadata, or derive child contexts from context.WithoutCancel. 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: Spawning Asynchronous Goroutines with Direct HTTP Request Context or Blank context.Background() 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 DriftSpawning Asynchronous Goroutines with Direct HTTP Request Context or Blank context.Background()Critical
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 pass `r.Context()` directly to long-running, detached, or fire-and-forget goroutines

Engineers MUST NEVER pass `r.Context()` directly to long-running, detached, or fire-and-forget goroutines; doing so causes immediate `context.Canceled` errors once the Chi HTTP handler terminates.

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 spawn detached goroutines initialized with `context.Background()` or `context.TODO()`, as this severs the distributed trace lineage, resets baggage, and produces disconnected orphan root spans.

Engineers MUST NEVER spawn detached goroutines initialized with `context.Background()` or `context.TODO()`, as this severs the distributed trace lineage, resets baggage, and produces disconnected orphan root spans.

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

Engineers MUST use Go 1.21+ `context.WithoutCancel(ctx)` when launching asynchronous goroutines to decouple request cancellation while deterministically preserving SpanContext and Baggage values.

Engineers MUST use Go 1.21+ `context.WithoutCancel(ctx)` when launching asynchronous goroutines to decouple request cancellation while deterministically preserving SpanContext and Baggage values.

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 start a new child span using `tracer.Start(detachedCtx, "operation_name")` inside the spawned goroutine and defer `span.End()` to ensure asynchronous execution times are tracked under the parent trace tree.

Engineers MUST start a new child span using `tracer.Start(detachedCtx, "operation_name")` inside the spawned goroutine and defer `span.End()` to ensure asynchronous execution times are tracked under the parent trace tree.

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 bound the execution of detached goroutines using `context.WithTimeout` or `context.WithDeadline` derived from the un-canceled context to prevent resource leaks and unmonitored execution hangs.

Services MUST bound the execution of detached goroutines using `context.WithTimeout` or `context.WithDeadline` derived from the un-canceled context to prevent resource leaks and unmonitored execution hangs.

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 Deterministic OpenTelemetry Context Propagation Across Goroutines in Go Chi critical for AI coding assistants?

Enforces strict context propagation across asynchronous goroutine boundaries within Go Chi HTTP services. Passing the raw request context directly to fire-and-forget goroutines causes context cancellation upon HTTP handler return, while spinning up goroutines with context.Background() severs trace lineages and drops baggage. Engineers must explicitly detach cancellation while propagating trace and baggage metadata, or derive child contexts from context.WithoutCancel. 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 (Spawning Asynchronous Goroutines with Direct HTTP Request Context or Blank context.Background()) 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

Deterministic