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

Go Chi Context Cancellation Deadline Tree Propagation Invariant

Enforces strict deadline and cancellation tree propagation from root Chi HTTP request contexts into child worker pools, downstream RPCs, and database operations. Disallows naked context re-instantiation via context.Background() or context.TODO() in HTTP handler call trees, preventing orphaned cloud resource consumption and memory leaks upon client disconnection.

Prohibited Anti-Pattern: Orphaned Goroutine and Cloud Resource Leak via Request Context Severance

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Cancellation Deadline Tree Propagation Invariant - Enforces strict deadline and cancellation tree propagation from root Chi HTTP request contexts into child worker pools, downstream RPCs, and database operations. Disallows naked context re-instantiation via context.Background() or context.TODO() in HTTP handler call trees, preventing orphaned cloud resource consumption and memory leaks upon client disconnection.
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-cancellation-deadline-propagation-go-chi-context-c-443"
---

# Go Chi Context Cancellation Deadline Tree Propagation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned Goroutine and Cloud Resource Leak via Request Context Severance

## System Constraints
You are a Principal Software Architect enforcing deterministic Go context cancellation tree propagation. In Go HTTP services using the Chi router, every spawned goroutine, worker pool, database transaction, and external RPC MUST deterministically bind to a child context derived from r.Context(). You must reject any pattern where context.Background() or context.TODO() is introduced mid-stream during HTTP request execution. If a background job must outlive the HTTP request lifecycle, engineers MUST use context.WithoutCancel(r.Context()) combined with an explicit bounded timeout. All asynchronous fan-out operations must implement cooperative cancellation checks via select on ctx.Done().

## Strict Guidelines
- Engineers MUST ALWAYS pass r.Context() down call chains and derive child contexts with timeouts using context.WithTimeout or context.WithTimeoutCause.
- Engineers MUST NOT spawn detached goroutines inside HTTP handlers using context.Background() or context.TODO() for request-scoped work.
- Asynchronous fan-out routines MUST be managed through errgroup.WithContext(ctx) to guarantee collective teardown on early failure or client disconnection.
- Code MUST periodically inspect ctx.Done() during computationally expensive loops or I/O chunking to break early on client aborts.
- Tasks intentionally outliving the client request MUST explicitly invoke context.WithoutCancel(r.Context()) and MUST apply an independent bounded deadline via context.WithTimeout to prevent indefinite thread hangs.
- Database connections, Redis commands, and downstream HTTP/gRPC clients MUST receive the derived Chi request context, never a fresh background context.

## Bad vs Good Implementations
### Chi Request Fan-Out with errgroup Cancellation Tree

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Severing the context tree with context.Background() causes cloud resource leaks when clients disconnect. Spawning raw goroutines without sync mechanisms like errgroup causes race conditions and leaked channels.
```go
package handler

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

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

	// Anti-Pattern: Severing root context with context.Background()
	// Orphaned goroutines continue executing downstream cloud calls
	// even if client drops the HTTP connection.
	go func() {
		ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
		res, _ := fetchBillingData(ctx)
		results <- res
	}()

	go func() {
		res, _ := fetchUserData(r.Context()) // Direct goroutine without synchronization
		results <- res
	}()

	w.Write([]byte(<-results + <-results))
}
```

#### Production Standard (Correct)
> **Standard**: Propagates Chi r.Context() through errgroup.WithContext, ensuring deterministic cascading cancellation across all concurrent child routines if any worker fails or the HTTP client disconnects.
```go
package handler

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

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

func HandleAggregateData(w http.ResponseWriter, r *http.Request) {
	// Derive bounded child context from Chi request context
	ctx, cancel := context.WithTimeoutCause(r.Context(), 5*time.Second, context.DeadlineExceeded)
	defer cancel()

	g, gctx := errgroup.WithContext(ctx)

	var billingRes string
	var userRes string

	g.Go(func() error {
		var err error
		billingRes, err = fetchBillingData(gctx)
		return err
	})

	g.Go(func() error {
		var err error
		userRes, err = fetchUserData(gctx)
		return err
	})

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

	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(billingRes + ":" + userRes))
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Context Cancellation Deadline Tree Propagation Invariant

Go Chi Context Cancellation Deadline Tree Propagation Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict deadline and cancellation tree propagation from root Chi HTTP request contexts into child worker pools, downstream RPCs, and database operations. Disallows naked context re-instantiation via context.Background() or context.TODO() in HTTP handler call trees, preventing orphaned cloud resource consumption and memory leaks upon client disconnection. 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: Orphaned Goroutine and Cloud Resource Leak via Request Context Severance 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 DriftOrphaned Goroutine and Cloud Resource Leak via Request Context SeveranceCritical
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 pass r.Context() down call chains and derive child contexts with timeouts using context.WithTimeout or context.WithTimeoutCause.

Engineers MUST ALWAYS pass r.Context() down call chains and derive child contexts with timeouts using context.WithTimeout or context.WithTimeoutCause.

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 inside HTTP handlers using context.Background() or context.TODO() for request-scoped work.

Engineers MUST NOT spawn detached goroutines inside HTTP handlers using context.Background() or context.TODO() for request-scoped work.

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

Asynchronous fan-out routines MUST be managed through errgroup.WithContext(ctx) to guarantee collective teardown on early failure or client disconnection.

Asynchronous fan-out routines MUST be managed through errgroup.WithContext(ctx) to guarantee collective teardown on early failure or client disconnection.

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

Code MUST periodically inspect ctx.Done() during computationally expensive loops or I/O chunking to break early on client aborts.

Code MUST periodically inspect ctx.Done() during computationally expensive loops or I/O chunking to break early on client aborts.

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

Tasks intentionally outliving the client request MUST explicitly invoke context.WithoutCancel(r.Context()) and MUST apply an independent bounded deadline via context.WithTimeout to prevent indefinite thread hangs.

Tasks intentionally outliving the client request MUST explicitly invoke context.WithoutCancel(r.Context()) and MUST apply an independent bounded deadline via context.WithTimeout to prevent indefinite thread hangs.

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

Database connections, Redis commands, and downstream HTTP/gRPC clients MUST receive the derived Chi request context, never a fresh background context.

Database connections, Redis commands, and downstream HTTP/gRPC clients MUST receive the derived Chi request context, never a fresh background 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.
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 Cancellation Deadline Tree Propagation Invariant critical for AI coding assistants?

Enforces strict deadline and cancellation tree propagation from root Chi HTTP request contexts into child worker pools, downstream RPCs, and database operations. Disallows naked context re-instantiation via context.Background() or context.TODO() in HTTP handler call trees, preventing orphaned cloud resource consumption and memory leaks upon client disconnection. 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 (Orphaned Goroutine and Cloud Resource Leak via Request Context Severance) 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