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

Go Chi Context Propagation & Deterministic Goroutine Lifecycle Invariant

Enforces strict context-tree inheritance and bounded goroutine lifecycles within Go Chi HTTP handlers. Eliminates unbounded goroutine accumulation and orphaned I/O operations caused by abrupt HTTP/3 client stream cancellations (QUIC RESET_STREAM) and connection drops under peak load.

Prohibited Anti-Pattern: Spawning detached, unbounded goroutines or ignoring request context cancellation during client disconnect spikes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Propagation & Deterministic Goroutine Lifecycle Invariant - Enforces strict context-tree inheritance and bounded goroutine lifecycles within Go Chi HTTP handlers. Eliminates unbounded goroutine accumulation and orphaned I/O operations caused by abrupt HTTP/3 client stream cancellations (QUIC RESET_STREAM) and connection drops under peak load.
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-context-lifecycle-goroutine-leak-prevention"
---

# Go Chi Context Propagation & Deterministic Goroutine Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached, unbounded goroutines or ignoring request context cancellation during client disconnect spikes

## System Constraints
You are a Principal Go Systems Architect enforcing strict HTTP request context lifecycle management and zero-goroutine-leak standards in Go Chi services. Under HTTP/3 and QUIC, client stream terminations occur abruptly and asynchronously. You must ensure that all handler-originated goroutines are strictly bound to errgroup.Group, that downstream network calls consume r.Context(), and that asynchronous side effects are safely detached via context.WithoutCancel with bounded worker queues rather than raw goroutine dispatch.

## Strict Guidelines
- Handlers MUST pass `r.Context()` directly to all downstream database calls, Redis transactions, and external RPC/HTTP invocations to propagate cancellation immediately upon client stream reset.
- Engineers MUST NOT spawn detached `go func()` calls inside Chi HTTP handlers closing over `r.Context()`; when client disconnects, child goroutines hanging on unbuffered channel sends or canceled contexts leak indefinitely.
- Concurrent fan-out within a request MUST be governed by `golang.org/x/sync/errgroup.WithContext(r.Context())` and bounded by semaphore channels or worker pools.
- All channels used for goroutine fan-in/fan-out within an active request MUST either be sufficiently buffered for all spawned sub-tasks or implement an explicit `select` branch on `ctx.Done()` to prevent permanent goroutine deadlock upon early handler exit.
- Asynchronous background work (e.g., audit logging, analytics) that must survive client disconnection MUST be decoupled from `r.Context()` using `context.WithoutCancel(r.Context())` and passed to a bounded, non-blocking persistent worker pool (never a bare goroutine).
- Services MUST enable Chi's timeout and cancellation-aware middleware (`middleware.Timeout`, `middleware.Heartbeat`) and configure HTTP server `ReadTimeout`, `WriteTimeout`, and `IdleTimeout` explicitly.

## Bad vs Good Implementations
### Anti-Pattern: Detached Goroutines and Context-Blind Channel Operations

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP/3 client issues a QUIC reset or drops connection, `r.Context()` is canceled. The unbuffered channel `ch` causes any remaining goroutine to block forever attempting to write to a channel that will never be read from again, quickly exhausting the Go runtime's OS thread pool and heap under high disconnect spikes.
```go
package api

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

func HandleSearch(db Database, extClient ExternalClient) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// BAD: Unbuffered channel combined with uncoordinated goroutines.
		// If client disconnects or an error triggers early return, 
		// the slower goroutine permanently blocks on send.
		ch := make(chan Result)
		
		go func() {
			// BAD: context.Background() discards client disconnect signals.
			res, err := db.Find(context.Background(), r.URL.Query().Get("q"))
			if err == nil {
				ch <- res // Leaks goroutine if receiver abandons channel
			}
		}()

		go func() {
			// BAD: r.Context() can cancel while downstream is running without wait group
			res, _ := extClient.Fetch(r.Context())
			ch <- res // Leaks goroutine if HandleSearch returns early
		}()

		firstResult := <-ch
		json.NewEncoder(w).Encode(firstResult)
	}
}
```

#### Production Standard (Correct)
> **Standard**: Uses `errgroup.WithContext(r.Context())` to coordinate all spawned child goroutines, buffers channels to avoid send-blocks, and guarantees that every goroutine terminates before the HTTP handler exits. Background tasks are properly decoupled using Go 1.21's `context.WithoutCancel` and handed off to a bounded queue instead of spawning detached goroutines.
```go
package api

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

func HandleSearch(db Database, extClient ExternalClient, bgQueue WorkQueue) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		g, groupCtx := errgroup.WithContext(ctx)

		// Buffered to prevent goroutine leaks if group exits early
		dbChan := make(chan Result, 1)
		extChan := make(chan Result, 1)

		g.Go(func() error {
			res, err := db.Find(groupCtx, r.URL.Query().Get("q"))
			if err != nil {
				return err
			}
			dbChan <- res
			return nil
		})

		g.Go(func() error {
			res, err := extClient.Fetch(groupCtx)
			if err != nil {
				return err
			}
			extChan <- res
			return nil
		})

		if err := g.Wait(); err != nil {
			http.Error(w, "failed to retrieve results", http.StatusBadGateway)
			return
		}

		// Detach background telemetry from cancelled request context safely
		bgCtx := context.WithoutCancel(ctx)
		bgQueue.Enqueue(bgCtx, "search_metric_increment")

		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]Result{
			"db":  <-dbChan,
			"ext": <-extChan,
		})
	}
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Context Propagation & Deterministic Goroutine Lifecycle Invariant

Go Chi Context Propagation & Deterministic Goroutine Lifecycle Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict context-tree inheritance and bounded goroutine lifecycles within Go Chi HTTP handlers. Eliminates unbounded goroutine accumulation and orphaned I/O operations caused by abrupt HTTP/3 client stream cancellations (QUIC RESET_STREAM) and connection drops under peak 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 detached, unbounded goroutines or ignoring request context cancellation during client disconnect spikes 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 detached, unbounded goroutines or ignoring request context cancellation during client disconnect spikesCritical
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

Handlers MUST pass `r.Context()` directly to all downstream database calls, Redis transactions, and external RPC/HTTP invocations to propagate cancellation immediately upon client stream reset.

Handlers MUST pass `r.Context()` directly to all downstream database calls, Redis transactions, and external RPC/HTTP invocations to propagate cancellation immediately upon client stream reset.

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()` calls inside Chi HTTP handlers closing over `r.Context()`

Engineers MUST NOT spawn detached `go func()` calls inside Chi HTTP handlers closing over `r.Context()`; when client disconnects, child goroutines hanging on unbuffered channel sends or canceled contexts leak indefinitely.

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

Concurrent fan-out within a request MUST be governed by `golang.org/x/sync/errgroup.WithContext(r.Context())` and bounded by semaphore channels or worker pools.

Concurrent fan-out within a request MUST be governed by `golang.org/x/sync/errgroup.WithContext(r.Context())` and bounded by semaphore channels or worker pools.

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

All channels used for goroutine fan-in/fan-out within an active request MUST either be sufficiently buffered for all spawned sub-tasks or implement an explicit `select` branch on `ctx.Done()` to prevent permanent goroutine deadlock upon early handler exit.

All channels used for goroutine fan-in/fan-out within an active request MUST either be sufficiently buffered for all spawned sub-tasks or implement an explicit `select` branch on `ctx.Done()` to prevent permanent goroutine deadlock upon early handler exit.

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

Asynchronous background work (e.g., audit logging, analytics) that must survive client disconnection MUST be decoupled from `r.Context()` using `context.WithoutCancel(r.Context())` and passed to a bounded, non-blocking persistent worker pool (never a bare goroutine).

Asynchronous background work (e.g., audit logging, analytics) that must survive client disconnection MUST be decoupled from `r.Context()` using `context.WithoutCancel(r.Context())` and passed to a bounded, non-blocking persistent worker pool (never a bare goroutine).

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 enable Chi's timeout and cancellation-aware middleware (`middleware.Timeout`, `middleware.Heartbeat`) and configure HTTP server `ReadTimeout`, `WriteTimeout`, and `IdleTimeout` explicitly.

Services MUST enable Chi's timeout and cancellation-aware middleware (`middleware.Timeout`, `middleware.Heartbeat`) and configure HTTP server `ReadTimeout`, `WriteTimeout`, and `IdleTimeout` explicitly.

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 Context Propagation & Deterministic Goroutine Lifecycle Invariant critical for AI coding assistants?

Enforces strict context-tree inheritance and bounded goroutine lifecycles within Go Chi HTTP handlers. Eliminates unbounded goroutine accumulation and orphaned I/O operations caused by abrupt HTTP/3 client stream cancellations (QUIC RESET_STREAM) and connection drops under peak 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 detached, unbounded goroutines or ignoring request context cancellation during client disconnect spikes) 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