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

Go 1.24 slog Trace Baggage Propagation and Detached Goroutine Safety in Chi Handlers

Enforces immutable W3C trace and baggage propagation through Go 1.24 structured logging (log/slog) across multiplexed Chi router pipelines. Mandates the use of context.WithoutCancel with supervised asynchronous task handoffs to eliminate orphan goroutine memory leaks and broken distributed trace lineages caused by premature HTTP request context termination.

Prohibited Anti-Pattern: Firing Naked Goroutines with r.Context() or context.Background() in HTTP Handlers Leading to Silent Context Canceled Aborts and Severed Distributed Traces

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 slog Trace Baggage Propagation and Detached Goroutine Safety in Chi Handlers - Enforces immutable W3C trace and baggage propagation through Go 1.24 structured logging (log/slog) across multiplexed Chi router pipelines. Mandates the use of context.WithoutCancel with supervised asynchronous task handoffs to eliminate orphan goroutine memory leaks and broken distributed trace lineages caused by premature HTTP request context termination.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-slog-context-baggage-chi-goroutine-leak-prevention"
---

# Go 1.24 slog Trace Baggage Propagation and Detached Goroutine Safety in Chi Handlers

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Firing Naked Goroutines with r.Context() or context.Background() in HTTP Handlers Leading to Silent Context Canceled Aborts and Severed Distributed Traces

## System Constraints
You are a Principal Backend Architect enforcing Go 1.24 production invariants for high-throughput HTTP microservices built with go-chi/chi and standard library log/slog. You strictly prohibit unmanaged goroutine spawning and broken distributed tracing context boundaries. Ensure all asynchronous offshoots preserve baggage and trace IDs while decoupling cancellation lifetimes.

## Strict Guidelines
- Engineers MUST ALWAYS propagate OpenTelemetry/W3C traceparent and baggage attributes across Go context boundaries using a custom slog.Handler that extracts trace/span IDs via trace.SpanContextFromContext(ctx).
- Engineers MUST NOT spawn naked goroutines ('go func()') inside Chi HTTP handler routes or middleware; all background executions MUST be submitted to a bounded, graceful-shutdown-aware worker queue or supervised errgroup.
- Engineers MUST decouple background async jobs from incoming HTTP cancellation loops using Go's standard library context.WithoutCancel(r.Context()) so that downstream tasks are not abruptly killed when the HTTP client disconnects or Chi handler terminates.
- Engineers MUST NOT initialize asynchronous contexts using context.Background() or context.TODO() when initiated from an HTTP request, as this strips span baggage and severs distributed tracing observability.
- Code MUST ALWAYS invoke slog methods with Context awareness (e.g., slog.InfoContext, slog.ErrorContext) passing the valid propagated context, and MUST NEVER rely on the global package-level slog.Info without context.
- Services MUST implement a panic-recovering worker queue wrapper for all asynchronous workloads to guarantee that unhandled panics in detached routines do not crash the runtime process.

## Bad vs Good Implementations
### Async Task Dispatch in Chi Route Handler with Baggage Preservation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a raw goroutine introduces unbounded concurrency, risk of unrecovered panics bringing down the service, and premature task termination when passing r.Context(). Switching to context.Background() strips distributed trace context and W3C baggage, rendering logs and downstream telemetry disjointed.
```go
package handlers

import (
	"context"
	"log/slog"
	"net/http"
	"github.com/go-chi/chi/v5"
)

func RegisterRoutes(r chi.Router) {
	r.Post("/api/v1/orders", handleCreateOrder)
}

func handleCreateOrder(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN 1: Package-level slog call discards context and trace correlation
	slog.Info("Processing order creation")

	// ANTI-PATTERN 2: Naked goroutine leak risk with r.Context() which cancels
	// immediately when the HTTP request finishes or client disconnects!
	go func() {
		// ANTI-PATTERN 3: Using context.Background() drops traceparent and baggage
		bgCtx := context.Background()
		if err := processAuditAsync(bgCtx, "order-123"); err != nil {
			slog.Error("Audit failed", "error", err)
		}
	}()

	w.WriteHeader(http.StatusAccepted)
}

func processAuditAsync(ctx context.Context, orderID string) error {
	return nil
}
```

#### Production Standard (Correct)
> **Standard**: Go 1.24 context.WithoutCancel preserves all context values (W3C trace spans, baggage, and security metadata) while ignoring the cancellation of the parent request context. Routing the job through a bounded TaskQueue prevents memory/goroutine leaks, handles panics gracefully, and ensures context-aware slog messages maintain correlated distributed traces.
```go
package handlers

import (
	"context"
	"errors"
	"log/slog"
	"net/http"

	"github.com/go-chi/chi/v5"
)

type TaskQueue interface {
	Submit(ctx context.Context, task func(ctx context.Context) error) error
}

type OrderHandler struct {
	queue  TaskQueue
	logger *slog.Logger
}

func (h *OrderHandler) RegisterRoutes(r chi.Router) {
	r.Post("/api/v1/orders", h.handleCreateOrder)
}

func (h *OrderHandler) handleCreateOrder(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	h.logger.InfoContext(ctx, "received order creation request", slog.String("order_id", "order-123"))

	// INVARIANT: Use context.WithoutCancel to preserve trace baggage, spans, and values
	// while decoupling the lifetime from the incoming HTTP request stream cancellation.
	asyncCtx := context.WithoutCancel(ctx)

	// INVARIANT: Dispatch to bounded supervisor instead of naked goroutine
	err := h.queue.Submit(asyncCtx, func(execCtx context.Context) error {
		h.logger.InfoContext(execCtx, "executing audit task in supervised worker")
		return processAuditAsync(execCtx, "order-123")
	})

	if errors.Is(err, context.DeadlineExceeded) || err != nil {
		h.logger.ErrorContext(ctx, "failed to enqueue async audit job", slog.Any("error", err))
		http.Error(w, "Service Overloaded", http.StatusServiceUnavailable)
		return
	}

	w.WriteHeader(http.StatusAccepted)
}

func processAuditAsync(ctx context.Context, orderID string) error {
	return nil
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 slog Trace Baggage Propagation and Detached Goroutine Safety in Chi Handlers

Go 1.24 slog Trace Baggage Propagation and Detached Goroutine Safety in Chi Handlers defines an industrial-grade behavioral standard for backend engineering. Enforces immutable W3C trace and baggage propagation through Go 1.24 structured logging (log/slog) across multiplexed Chi router pipelines. Mandates the use of context.WithoutCancel with supervised asynchronous task handoffs to eliminate orphan goroutine memory leaks and broken distributed trace lineages caused by premature HTTP request context termination. 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: Firing Naked Goroutines with r.Context() or context.Background() in HTTP Handlers Leading to Silent Context Canceled Aborts and Severed Distributed Traces 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 DriftFiring Naked Goroutines with r.Context() or context.Background() in HTTP Handlers Leading to Silent Context Canceled Aborts and Severed Distributed TracesCritical
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 OpenTelemetry/W3C traceparent and baggage attributes across Go context boundaries using a custom slog.Handler that extracts trace/span IDs via trace.SpanContextFromContext(ctx).

Engineers MUST ALWAYS propagate OpenTelemetry/W3C traceparent and baggage attributes across Go context boundaries using a custom slog.Handler that extracts trace/span IDs via trace.SpanContextFromContext(ctx).

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 naked goroutines ('go func()') inside Chi HTTP handler routes or middleware

Engineers MUST NOT spawn naked goroutines ('go func()') inside Chi HTTP handler routes or middleware; all background executions MUST be submitted to a bounded, graceful-shutdown-aware worker queue or supervised errgroup.

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 decouple background async jobs from incoming HTTP cancellation loops using Go's standard library context.WithoutCancel(r.Context()) so that downstream tasks are not abruptly killed when the HTTP client disconnects or Chi handler terminates.

Engineers MUST decouple background async jobs from incoming HTTP cancellation loops using Go's standard library context.WithoutCancel(r.Context()) so that downstream tasks are not abruptly killed when the HTTP client disconnects or Chi 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.
4

Engineers MUST NOT initialize asynchronous contexts using context.Background() or context.TODO() when initiated from an HTTP request, as this strips span baggage and severs distributed tracing observability.

Engineers MUST NOT initialize asynchronous contexts using context.Background() or context.TODO() when initiated from an HTTP request, as this strips span baggage and severs distributed tracing observability.

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 MUST ALWAYS invoke slog methods with Context awareness (e.g., slog.InfoContext, slog.ErrorContext) passing the valid propagated context, and MUST NEVER rely on the global package-level slog.Info without context.

Code MUST ALWAYS invoke slog methods with Context awareness (e.g., slog.InfoContext, slog.ErrorContext) passing the valid propagated context, and MUST NEVER rely on the global package-level slog.Info without context.

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

Services MUST implement a panic-recovering worker queue wrapper for all asynchronous workloads to guarantee that unhandled panics in detached routines do not crash the runtime process.

Services MUST implement a panic-recovering worker queue wrapper for all asynchronous workloads to guarantee that unhandled panics in detached routines do not crash the runtime process.

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 1.24 slog Trace Baggage Propagation and Detached Goroutine Safety in Chi Handlers critical for AI coding assistants?

Enforces immutable W3C trace and baggage propagation through Go 1.24 structured logging (log/slog) across multiplexed Chi router pipelines. Mandates the use of context.WithoutCancel with supervised asynchronous task handoffs to eliminate orphan goroutine memory leaks and broken distributed trace lineages caused by premature HTTP request context termination. 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 (Firing Naked Goroutines with r.Context() or context.Background() in HTTP Handlers Leading to Silent Context Canceled Aborts and Severed Distributed Traces) 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