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

Go Chi Structured Context Deadline & Goroutine Tree Lifecycle Propagation

Mandates strict structured concurrency and cancellation propagation from Chi HTTP request contexts to all downstream goroutines and I/O clients. Prevents orphaned background operations, memory leaks, and database connection pool exhaustion when clients disconnect or streaming requests terminate prematurely.

Prohibited Anti-Pattern: Detached Background Context Spawning and Goroutine Leaks in Chi HTTP Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Structured Context Deadline & Goroutine Tree Lifecycle Propagation - Mandates strict structured concurrency and cancellation propagation from Chi HTTP request contexts to all downstream goroutines and I/O clients. Prevents orphaned background operations, memory leaks, and database connection pool exhaustion when clients disconnect or streaming requests terminate prematurely.
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-deadline-goroutine-lifecycle"
---

# Go Chi Structured Context Deadline & Goroutine Tree Lifecycle Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Background Context Spawning and Goroutine Leaks in Chi HTTP Handlers

## System Constraints
You are a Principal Backend Architect enforcing strict Go concurrency invariants. In Chi router microservices, HTTP request contexts represent the absolute boundary of work. You must enforce structured goroutine trees via errgroup or waitgroups bound to r.Context(), forbid context.Background() in request paths, and guarantee deterministic cancellation of all I/O and worker routines.

## Strict Guidelines
- Engineers MUST ALWAYS derive child goroutine contexts directly from r.Context() or pass an explicit sub-context derived using context.WithTimeout/context.WithDeadline.
- Engineers MUST NOT spawn detached goroutines using context.Background() or context.TODO() inside HTTP handlers or middleware unless delegating to a dedicated decoupled background worker pool with its own lifecycle manager.
- Handlers spawning concurrent worker routines MUST use errgroup.WithContext(r.Context()) to guarantee structured lifecycle termination and aggregate error propagation.
- All channel reads, writes, and blocking I/O within worker goroutines MUST be multiplexed with select cases listening to ctx.Done() to avert permanent goroutine leakage.
- Database queries, cache calls, and downstream HTTP client requests MUST receive the cancellation context to ensure connection sockets and transactions are immediately released on client disconnect.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an unmonitored goroutine using context.Background(). If the client drops connection or Chi middleware cancels the request, the goroutine continues executing indefinitely, holding sockets and attempting to write to an unbuffered channel, causing a permanent goroutine and memory leak.
```go
package handlers

import (
	"context"
	"encoding/json"
	"net/http"
)

func ProcessStreamHandler(w http.ResponseWriter, r *http.Request) {
	results := make(chan string)

	// ANTI-PATTERN: Detached goroutine with context.Background ignores client disconnect
	// and Chi timeout middleware. Leaks if client disconnects or channel blocks.
	go func() {
		res, err := fetchExternalData(context.Background())
		if err != nil {
			return
		}
		results <- res
	}()

	data := <-results
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"data": data})
}

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

#### Production Standard (Correct)
> **Standard**: Leverages errgroup.WithContext derived from r.Context(). The worker goroutine receives the derived context, aborting immediately via ctx.Done() if Chi's timeout middleware triggers or the client disconnects, preventing thread exhaustion and socket pool depletion.
```go
package handlers

import (
	"encoding/json"
	"net/http"
	"time"

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

type ResponsePayload struct {
	Data string `json:"data"`
}

func ProcessStreamHandler(w http.ResponseWriter, r *http.Request) {
	// Bound execution to request lifecycle with defensive timeout
	g, ctx := errgroup.WithContext(r.Context())
	var result string

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

	if err := g.Wait(); err != nil {
		if ctx.Err() != nil {
			// Client disconnected or deadline exceeded; stop processing cleanly
			http.Error(w, "request cancelled", http.StatusGatewayTimeout)
			return
		}
		http.Error(w, "internal server error", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(ResponsePayload{Data: result})
}

func fetchExternalData(ctx context.Context) (string, error) {
	select {
	case <-ctx.Done():
		return "", ctx.Err()
	case <-time.After(50 * time.Millisecond):
		return "payload", 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 Structured Context Deadline & Goroutine Tree Lifecycle Propagation

Go Chi Structured Context Deadline & Goroutine Tree Lifecycle Propagation defines an industrial-grade behavioral standard for backend engineering. Mandates strict structured concurrency and cancellation propagation from Chi HTTP request contexts to all downstream goroutines and I/O clients. Prevents orphaned background operations, memory leaks, and database connection pool exhaustion when clients disconnect or streaming requests terminate prematurely. 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: Detached Background Context Spawning and Goroutine Leaks in Chi HTTP 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 DriftDetached Background Context Spawning and Goroutine Leaks in Chi HTTP 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 derive child goroutine contexts directly from r.Context() or pass an explicit sub-context derived using context.WithTimeout/context.WithDeadline.

Engineers MUST ALWAYS derive child goroutine contexts directly from r.Context() or pass an explicit sub-context derived using context.WithTimeout/context.WithDeadline.

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 goroutines using context.Background() or context.TODO() inside HTTP handlers or middleware unless delegating to a dedicated decoupled background worker pool with its own lifecycle manager.

Engineers MUST NOT spawn detached goroutines using context.Background() or context.TODO() inside HTTP handlers or middleware unless delegating to a dedicated decoupled background worker pool with its own lifecycle manager.

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

Handlers spawning concurrent worker routines MUST use errgroup.WithContext(r.Context()) to guarantee structured lifecycle termination and aggregate error propagation.

Handlers spawning concurrent worker routines MUST use errgroup.WithContext(r.Context()) to guarantee structured lifecycle termination and aggregate error propagation.

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 channel reads, writes, and blocking I/O within worker goroutines MUST be multiplexed with select cases listening to ctx.Done() to avert permanent goroutine leakage.

All channel reads, writes, and blocking I/O within worker goroutines MUST be multiplexed with select cases listening to ctx.Done() to avert permanent goroutine leakage.

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

Database queries, cache calls, and downstream HTTP client requests MUST receive the cancellation context to ensure connection sockets and transactions are immediately released on client disconnect.

Database queries, cache calls, and downstream HTTP client requests MUST receive the cancellation context to ensure connection sockets and transactions are immediately released 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.
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 Deadline & Goroutine Tree Lifecycle Propagation critical for AI coding assistants?

Mandates strict structured concurrency and cancellation propagation from Chi HTTP request contexts to all downstream goroutines and I/O clients. Prevents orphaned background operations, memory leaks, and database connection pool exhaustion when clients disconnect or streaming requests terminate prematurely. 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 (Detached Background Context Spawning and Goroutine Leaks in Chi HTTP 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