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

Go Chi Structured Context Propagation and Goroutine Teardown Guardrail

Enforces strict context deadline inheritance, cooperative goroutine cancellation, and bounded lifecycle synchronization in Go Chi HTTP services. Prevents silent memory bloat, resource exhaustion, and zombie goroutines caused by detaching contexts or spawning unmonitored background routines from active HTTP handlers under sustained load.

Prohibited Anti-Pattern: Spawning fire-and-forget goroutines or stripping request context deadlines in Chi handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Structured Context Propagation and Goroutine Teardown Guardrail - Enforces strict context deadline inheritance, cooperative goroutine cancellation, and bounded lifecycle synchronization in Go Chi HTTP services. Prevents silent memory bloat, resource exhaustion, and zombie goroutines caused by detaching contexts or spawning unmonitored background routines from active HTTP handlers under sustained load.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-propagation-goroutine-teardown-guardrail"
---

# Go Chi Structured Context Propagation and Goroutine Teardown Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning fire-and-forget goroutines or stripping request context deadlines in Chi handlers

## System Constraints
You are a Principal Go Architect enforcing rigorous context propagation and goroutine lifecycle invariants across Go Chi services. Mandate explicit deadline propagation, channel draining, cooperative context cancellation via ctx.Done(), and synchronized goroutine teardown using sync.WaitGroup or errgroup.Group to completely eliminate goroutine leaks and silent memory bloat.

## Strict Guidelines
- Engineers MUST ALWAYS propagate r.Context() down through all database, RPC, and internal operations initiated within a Chi HTTP handler.
- Engineers MUST NEVER launch asynchronous background goroutines bound to r.Context() without a detached context or coordinated lifecycle mechanism, as client disconnections prematurely cancel the request context.
- Engineers MUST ALWAYS listen to ctx.Done() inside long-running worker loops and select blocks to guarantee prompt termination upon client aborts or timeout expiries.
- Services MUST implement chi middleware.Timeout or chi middleware.Throttle at the router level, and all spawned auxiliary goroutines MUST be tracked using sync.WaitGroup or errgroup.WithContext.
- Engineers MUST NEVER create unbuffered channels shared across goroutines where a context cancellation could leave a sender blocked indefinitely on a channel read.

## Bad vs Good Implementations
### Chi Handler Goroutine Teardown with Context Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching an unmonitored goroutine passing the HTTP request context leads to race conditions and unpredictable termination when the client disconnects. Conversely, detaching it with context.Background() without structured errgroup tracking or timeout guarantees leaves orphaned zombie goroutines if external calls stall.
```go
package handlers

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

func AsyncProcessor(w http.ResponseWriter, r *http.Request) {
	// BAD: Fire-and-forget goroutine using request context
	// If the client disconnects or Chi timeout triggers, r.Context() is canceled,
	// but if r.Context() is swapped with context.Background(), the goroutine leaks
	// on blocked channel/I/O without teardown orchestration.
	go func() {
		// Leaks memory and runs untracked; panics here crash the runtime
		ProcessTelemetry(r.Context(), r.URL.Query().Get("event"))
	}()

	w.WriteHeader(http.StatusAccepted)
}

func ProcessTelemetry(ctx context.Context, event string) {
	// Simulates work that hangs or leaks if context cancellation isn't monitored
	select {
	case <-ctx.Done():
		return
	}
}
```

#### Production Standard (Correct)
> **Standard**: Uses golang.org/x/sync/errgroup scoped to the HTTP request context with an explicit timeout. Employs buffered channels to prevent producer goroutines from hanging if one worker errors out early, ensuring deterministic termination and zero zombie goroutines.
```go
package handlers

import (
	"context"
	"net/http"
	"time"
	"golang.org/x/sync/errgroup"
)

func ResilientConcurrentHandler(w http.ResponseWriter, r *http.Request) {
	// GOOD: Bound total processing time to parent request deadline or explicit fallback
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	g, gctx := errgroup.WithContext(ctx)
	results := make(chan string, 2) // Buffered to prevent sender goroutine leaks

	g.Go(func() error {
		select {
		case <-gctx.Done():
			return gctx.Err()
		case results <- fetchPartA(gctx):
			return nil
		}
	})

	g.Go(func() error {
		select {
		case <-gctx.Done():
			return gctx.Err()
		case results <- fetchPartB(gctx):
			return nil
		}
	})

	if err := g.Wait(); err != nil {
		http.Error(w, err.Error(), http.StatusGatewayTimeout)
		return
	}
	close(results)

	w.WriteHeader(http.StatusOK)
}

func fetchPartA(ctx context.Context) string { return "A" }
func fetchPartB(ctx context.Context) string { return "B" }
```

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 Structured Context Propagation and Goroutine Teardown Guardrail

Go Chi Structured Context Propagation and Goroutine Teardown Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict context deadline inheritance, cooperative goroutine cancellation, and bounded lifecycle synchronization in Go Chi HTTP services. Prevents silent memory bloat, resource exhaustion, and zombie goroutines caused by detaching contexts or spawning unmonitored background routines from active HTTP handlers under sustained load. 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 fire-and-forget goroutines or stripping request context deadlines in Chi handlers 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 fire-and-forget goroutines or stripping request context deadlines in Chi handlersCritical
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() down through all database, RPC, and internal operations initiated within a Chi HTTP handler.

Engineers MUST ALWAYS propagate r.Context() down through all database, RPC, and internal operations initiated within a Chi 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.
2

Engineers MUST NEVER launch asynchronous background goroutines bound to r.Context() without a detached context or coordinated lifecycle mechanism, as client disconnections prematurely cancel the request context.

Engineers MUST NEVER launch asynchronous background goroutines bound to r.Context() without a detached context or coordinated lifecycle mechanism, as client disconnections prematurely cancel the request 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.
3

Engineers MUST ALWAYS listen to ctx.Done() inside long-running worker loops and select blocks to guarantee prompt termination upon client aborts or timeout expiries.

Engineers MUST ALWAYS listen to ctx.Done() inside long-running worker loops and select blocks to guarantee prompt termination upon client aborts or timeout expiries.

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 implement chi middleware.Timeout or chi middleware.Throttle at the router level, and all spawned auxiliary goroutines MUST be tracked using sync.WaitGroup or errgroup.WithContext.

Services MUST implement chi middleware.Timeout or chi middleware.Throttle at the router level, and all spawned auxiliary goroutines MUST be tracked using sync.WaitGroup or errgroup.WithContext.

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

Engineers MUST NEVER create unbuffered channels shared across goroutines where a context cancellation could leave a sender blocked indefinitely on a channel read.

Engineers MUST NEVER create unbuffered channels shared across goroutines where a context cancellation could leave a sender blocked indefinitely on a channel read.

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 Structured Context Propagation and Goroutine Teardown Guardrail critical for AI coding assistants?

Enforces strict context deadline inheritance, cooperative goroutine cancellation, and bounded lifecycle synchronization in Go Chi HTTP services. Prevents silent memory bloat, resource exhaustion, and zombie goroutines caused by detaching contexts or spawning unmonitored background routines from active HTTP handlers under sustained load. 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 fire-and-forget goroutines or stripping request context deadlines in Chi handlers) 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