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

Go Chi v5 Structured Context Cancellation & OpenTelemetry Lifecycle Propagation

Enforces deterministic context cancellation propagation across Go Chi v5 HTTP middleware pipelines and downstream RPC/database calls. Prevents orphaned downstream executions, goroutine leaks, and broken OpenTelemetry trace lineage by binding client connection terminations directly to derived execution contexts and span finalization.

Prohibited Anti-Pattern: Detaching r.Context() or Leaking Unbounded Goroutines During Chi HTTP Request Lifecycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi v5 Structured Context Cancellation & OpenTelemetry Lifecycle Propagation - Enforces deterministic context cancellation propagation across Go Chi v5 HTTP middleware pipelines and downstream RPC/database calls. Prevents orphaned downstream executions, goroutine leaks, and broken OpenTelemetry trace lineage by binding client connection terminations directly to derived execution contexts and span finalization.
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-otel-context-cancellation-guardrail"
---

# Go Chi v5 Structured Context Cancellation & OpenTelemetry Lifecycle Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detaching r.Context() or Leaking Unbounded Goroutines During Chi HTTP Request Lifecycles

## System Constraints
You are a Principal Software Architect enforcing Go Chi v5 and OpenTelemetry context propagation guardrails. You must mandate that every incoming HTTP request context (`r.Context()`) remains the single source of truth for all downstream database queries, gRPC calls, outbound HTTP requests, and concurrent fan-out tasks. Never decouple background work from the request context without explicit, structured detached trace propagation, and ensure all goroutines terminate upon `ctx.Done()`.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` directly to database drivers, cache lookups, and outbound gRPC/HTTP clients to immediately stop work on client disconnect.
- Engineers MUST NOT spawn detached background goroutines (`go func() { ... }()`) using `context.Background()` or `context.TODO()` inside Chi handler scopes.
- Code SHOULD utilize structured concurrency primitives (such as `golang.org/x/sync/errgroup.WithContext`) when fanning out concurrent operations within an HTTP handler.
- Services MUST configure Chi middleware chains to inject OpenTelemetry spans via `otelhttp` or custom trace middleware that accurately reflects `http.Handler` context termination.
- Components NEVER drop context cancellation signals; if asynchronous processing must survive beyond HTTP response delivery, engineers MUST use an explicit out-of-band message queue or create a decoupled, detached span linked via OpenTelemetry Span Links.

## Bad vs Good Implementations
### Concurrent Fan-Out and Downstream Dispatch in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler creates a new context.Background(), severing the link to the client HTTP connection. If the client disconnects or Chi aborts the request, the downstream call continues running, leaking resources. Trace correlation is also broken because parent spans from Chi middleware are discarded.
```go
package handlers

import (
	"context"
	"net/http"

	"go.opentelemetry.io/otel"
)

func HandleSearch(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: Discarding r.Context(), leaking goroutines on client abort,
	// and breaking OpenTelemetry span context propagation.
	ctx := context.Background()
	tr := otel.Tracer("search")
	ctx, span := tr.Start(ctx, "HandleSearch")
	defer span.End()

	results := make(chan string)
	go func() {
		// Goroutine runs indefinitely if caller hangs, ignoring HTTP disconnects
		res, _ := downstreamServiceCall(context.TODO())
		results <- res
	}()

	w.Write([]byte(<-results))
}

func downstreamServiceCall(ctx context.Context) (string, error) {
	return "data", nil
}
```

#### Production Standard (Correct)
> **Standard**: The handler derives execution context directly from `r.Context()`, applies an explicit timeout, and controls concurrent dispatch using `errgroup.WithContext`. Downstream calls immediately cancel if the client drops the connection, and OpenTelemetry spans accurately capture cancellation errors.
```go
package handlers

import (
	"net/http"
	"time"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/codes"
	"golang.org/x/sync/errgroup"
)

func HandleSearch(w http.ResponseWriter, r *http.Request) {
	// PRODUCTION INVARIANT: Inherit r.Context() carrying Chi middleware & OTel trace state
	ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
	defer cancel()

	tr := otel.Tracer("search")
	ctx, span := tr.Start(ctx, "HandleSearch")
	defer span.End()

	g, gctx := errgroup.WithContext(ctx)
	var result string

	g.Go(func() error {
		res, err := downstreamServiceCall(gctx)
		if err != nil {
			return err
		}
		result = res
		return nil
	})

	if err := g.Wait(); err != nil {
		span.RecordError(err)
		span.SetStatus(codes.Error, err.Error())
		http.Error(w, "downstream request failed", http.StatusGatewayTimeout)
		return
	}

	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(result))
}

func downstreamServiceCall(ctx context.Context) (string, error) {
	select {
	case <-ctx.Done():
		return "", ctx.Err()
	default:
		return "data", nil
	}
}
```

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 Structured Context Cancellation & OpenTelemetry Lifecycle Propagation

Go Chi v5 Structured Context Cancellation & OpenTelemetry Lifecycle Propagation defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic context cancellation propagation across Go Chi v5 HTTP middleware pipelines and downstream RPC/database calls. Prevents orphaned downstream executions, goroutine leaks, and broken OpenTelemetry trace lineage by binding client connection terminations directly to derived execution contexts and span finalization. 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: Detaching r.Context() or Leaking Unbounded Goroutines During Chi HTTP Request Lifecycles 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 DriftDetaching r.Context() or Leaking Unbounded Goroutines During Chi HTTP Request LifecyclesCritical
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 propagate `r.Context()` directly to database drivers, cache lookups, and outbound gRPC/HTTP clients to immediately stop work on client disconnect.

Engineers MUST ALWAYS propagate `r.Context()` directly to database drivers, cache lookups, and outbound gRPC/HTTP clients to immediately stop work on client disconnect.

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 spawn detached background goroutines (`go func() { ... }()`) using `context.Background()` or `context.TODO()` inside Chi handler scopes.

Engineers MUST NOT spawn detached background goroutines (`go func() { ... }()`) using `context.Background()` or `context.TODO()` inside Chi handler scopes.

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

Code SHOULD utilize structured concurrency primitives (such as `golang.org/x/sync/errgroup.WithContext`) when fanning out concurrent operations within an HTTP handler.

Code SHOULD utilize structured concurrency primitives (such as `golang.org/x/sync/errgroup.WithContext`) when fanning out concurrent operations within an HTTP handler.

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

Services MUST configure Chi middleware chains to inject OpenTelemetry spans via `otelhttp` or custom trace middleware that accurately reflects `http.Handler` context termination.

Services MUST configure Chi middleware chains to inject OpenTelemetry spans via `otelhttp` or custom trace middleware that accurately reflects `http.Handler` context termination.

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

Components NEVER drop context cancellation signals

Components NEVER drop context cancellation signals; if asynchronous processing must survive beyond HTTP response delivery, engineers MUST use an explicit out-of-band message queue or create a decoupled, detached span linked via OpenTelemetry Span Links.

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 Structured Context Cancellation & OpenTelemetry Lifecycle Propagation critical for AI coding assistants?

Enforces deterministic context cancellation propagation across Go Chi v5 HTTP middleware pipelines and downstream RPC/database calls. Prevents orphaned downstream executions, goroutine leaks, and broken OpenTelemetry trace lineage by binding client connection terminations directly to derived execution contexts and span finalization. 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 (Detaching r.Context() or Leaking Unbounded Goroutines During Chi HTTP Request Lifecycles) 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