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

Go Chi Hierarchical Context Cancellation and Goroutine Leak Prevention Standard

Enforces strict propagation of Go Chi HTTP request contexts and structured cancellation causes across all downstream RPCs, database transactions, and spawned background workers. Prevents orphaned goroutine leaks and silent connection pool starvation caused by discarded or severed context trees during client disconnects. Mandates explicit context cause handling and synchronization via errgroup or worker pool lifecycles.

Prohibited Anti-Pattern: Severing Chi Request Contexts with context.Background() and Spawning Unbounded Background Goroutines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Hierarchical Context Cancellation and Goroutine Leak Prevention Standard - Enforces strict propagation of Go Chi HTTP request contexts and structured cancellation causes across all downstream RPCs, database transactions, and spawned background workers. Prevents orphaned goroutine leaks and silent connection pool starvation caused by discarded or severed context trees during client disconnects. Mandates explicit context cause handling and synchronization via errgroup or worker pool lifecycles.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, **/*router*.go, **/*handler*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-cancellation-goroutine-leak-guardrail"
---

# Go Chi Hierarchical Context Cancellation and Goroutine Leak Prevention Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Severing Chi Request Contexts with context.Background() and Spawning Unbounded Background Goroutines

## System Constraints
You are a Principal Go Systems Architect enforcing strict HTTP request context lifecycle management, context cancellation propagation, and goroutine leak prevention within Go Chi microservices. You must ensure that developers never detach child operations from the incoming HTTP request context unless utilizing an explicitly bounded, decoupled worker pool with its own lifecycle. You mandate the use of Go 1.20+ context.WithCancelCause and context.Cause to track upstream client disconnects versus downstream timeouts, and require rigorous errgroup or sync.WaitGroup coordination to guarantee zero orphaned goroutines or leaked database/HTTP transport pool connections.

## Strict Guidelines
- Engineers MUST ALWAYS derive outbound RPC, database, and cache call contexts directly from Chi's r.Context() using context.WithTimeoutCause or context.WithCancelCause.
- Engineers MUST NOT spawn detached 'go func()' blocks inside Chi HTTP handlers using r.Context() or context.Background() without explicit errgroup containment or structured detached queue delegation.
- Code MUST drain and close io.ReadCloser response bodies in defer statements immediately after checking outbound HTTP errors to release sockets back to the transport pool.
- Services MUST inspect context.Cause(ctx) when handling cancellation errors to distinguish between client aborts (e.g., Chi http.CloseNotifier / client TCP reset) and internal operational timeouts.
- Components NEVER drop context propagation in middleware chains, ensuring all wrapped chi.Context parameters and request cancellation signals remain intact throughout the call graph.

## Bad vs Good Implementations
### Outbound RPC and Goroutine Management in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler severs the incoming Chi request context by instantiating an isolated context.Background(), hiding client disconnects. It spawns an unmanaged goroutine with no lifecycle bounds or synchronization, causing goroutine leaks. The unmanaged goroutine also abandons an open HTTP response body, starving the DefaultTransport connection pool.
```go
package handlers

import (
	"context"
	"net/http"
	"time"
)

func FetchAggregatedUserData(w http.ResponseWriter, r *http.Request) {
	// BAD: Severing context tree using context.Background()
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// BAD: Launching unmonitored goroutine that outlives request
	go func() {
		// If client disconnects, this goroutine leaks and continues executing
		resp, err := http.Get("https://api.internal/telemetry")
		if err == nil {
			// BAD: Leaking connection pool socket if body is not closed or drained
			_ = resp.Body
		}
	}()

	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.internal/user", nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()
	w.WriteHeader(http.StatusOK)
}
```

#### Production Standard (Correct)
> **Standard**: Derives a context bound to the incoming Chi request using context.WithTimeoutCause. Concurrent operations are orchestrated via errgroup.WithContext, ensuring all goroutines terminate if the client drops the connection. Outbound response bodies are safely drained and closed, preventing transport connection pool leaks. context.Cause is inspected for deterministic error reporting.
```go
package handlers

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"time"

	"golang.org/x/sync/errgroup"
)

var errClientCancelled = errors.New("client cancelled request")

func FetchAggregatedUserData(w http.ResponseWriter, r *http.Request) {
	// GOOD: Inherit Chi request context with structured cancellation cause
	ctx, cancel := context.WithTimeoutCause(r.Context(), 3*time.Second, errors.New("user aggregation deadline exceeded"))
	defer cancel()

	// GOOD: Use errgroup bound to derived context for concurrent child operations
	g, groupCtx := errgroup.WithContext(ctx)

	g.Go(func() error {
		req, err := http.NewRequestWithContext(groupCtx, http.MethodGet, "https://api.internal/telemetry", nil)
		if err != nil {
			return err
		}
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			return fmt.Errorf("telemetry rpc failed: %w", err)
		}
		// GOOD: Immediate close and discard drain to prevent pool starvation
		defer resp.Body.Close()
		_, _ = io.Copy(io.Discard, resp.Body)
		return nil
	})

	if err := g.Wait(); err != nil {
		cause := context.Cause(groupCtx)
		if errors.Is(groupCtx.Err(), context.Canceled) {
			http.Error(w, fmt.Sprintf("Request aborted: %v", cause), http.StatusRequestTimeout)
			return
		}
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Hierarchical Context Cancellation and Goroutine Leak Prevention Standard

Go Chi Hierarchical Context Cancellation and Goroutine Leak Prevention Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict propagation of Go Chi HTTP request contexts and structured cancellation causes across all downstream RPCs, database transactions, and spawned background workers. Prevents orphaned goroutine leaks and silent connection pool starvation caused by discarded or severed context trees during client disconnects. Mandates explicit context cause handling and synchronization via errgroup or worker pool lifecycles. 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: Severing Chi Request Contexts with context.Background() and Spawning Unbounded Background Goroutines 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 DriftSevering Chi Request Contexts with context.Background() and Spawning Unbounded Background GoroutinesCritical
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 derive outbound RPC, database, and cache call contexts directly from Chi's r.Context() using context.WithTimeoutCause or context.WithCancelCause.

Engineers MUST ALWAYS derive outbound RPC, database, and cache call contexts directly from Chi's r.Context() using context.WithTimeoutCause or context.WithCancelCause.

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 'go func()' blocks inside Chi HTTP handlers using r.Context() or context.Background() without explicit errgroup containment or structured detached queue delegation.

Engineers MUST NOT spawn detached 'go func()' blocks inside Chi HTTP handlers using r.Context() or context.Background() without explicit errgroup containment or structured detached queue delegation.

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 MUST drain and close io.ReadCloser response bodies in defer statements immediately after checking outbound HTTP errors to release sockets back to the transport pool.

Code MUST drain and close io.ReadCloser response bodies in defer statements immediately after checking outbound HTTP errors to release sockets back to the transport pool.

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 inspect context.Cause(ctx) when handling cancellation errors to distinguish between client aborts (e.g., Chi http.CloseNotifier / client TCP reset) and internal operational timeouts.

Services MUST inspect context.Cause(ctx) when handling cancellation errors to distinguish between client aborts (e.g., Chi http.CloseNotifier / client TCP reset) and internal operational timeouts.

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 propagation in middleware chains, ensuring all wrapped chi.Context parameters and request cancellation signals remain intact throughout the call graph.

Components NEVER drop context propagation in middleware chains, ensuring all wrapped chi.Context parameters and request cancellation signals remain intact throughout the call graph.

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 Hierarchical Context Cancellation and Goroutine Leak Prevention Standard critical for AI coding assistants?

Enforces strict propagation of Go Chi HTTP request contexts and structured cancellation causes across all downstream RPCs, database transactions, and spawned background workers. Prevents orphaned goroutine leaks and silent connection pool starvation caused by discarded or severed context trees during client disconnects. Mandates explicit context cause handling and synchronization via errgroup or worker pool lifecycles. 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 (Severing Chi Request Contexts with context.Background() and Spawning Unbounded Background Goroutines) 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