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

Go Chi Context-Aware Deadline and Upstream Cancellation Cascade

Enforces strict propagation of Chi HTTP request contexts (`r.Context()`) down to all database drivers, external RPC calls, and derived child goroutines. Prevents orphaned goroutines, zombie connection leaks, and wasted compute across downstream dependencies when clients abort or disconnect prematurely.

Prohibited Anti-Pattern: Ignoring r.Context() or Decoupling Background Goroutines with context.Background()

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context-Aware Deadline and Upstream Cancellation Cascade - Enforces strict propagation of Chi HTTP request contexts (`r.Context()`) down to all database drivers, external RPC calls, and derived child goroutines. Prevents orphaned goroutines, zombie connection leaks, and wasted compute across downstream dependencies when clients abort or disconnect prematurely.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-cancellation-cascade"
---

# Go Chi Context-Aware Deadline and Upstream Cancellation Cascade

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ignoring r.Context() or Decoupling Background Goroutines with context.Background()

## System Constraints
You are a Principal Engineer enforcing Go Chi Context-Aware Deadline & Upstream Cancellation Cascade. Mandate that every HTTP handler in a Chi router strictly passes r.Context() to all I/O-bound operations (database queries, network requests, cache lookups). Prohibit context.Background() and context.TODO() within handler chains unless explicitly decoupling via context.WithoutCancel() for non-critical telemetry. Require asynchronous operations spawned inside handlers to be bound by context cancellation signals and synchronized using sync.WaitGroup or errgroup.Group.

## Strict Guidelines
- Engineers MUST ALWAYS pass `r.Context()` directly to database methods (e.g., `QueryContext`, `ExecContext`, `BeginTx`) and external HTTP/gRPC client calls.
- Engineers MUST NOT spawn detached goroutines inside HTTP handlers using `context.Background()` or raw `r.Context()` without observing cancellation channels (`ctx.Done()`).
- Services MUST configure `middleware.Timeout` or handle `context.WithTimeout` defensively to establish an upper-bound SLA deadline for every incoming route.
- Code SHOULD map `context.Canceled` and `context.DeadlineExceeded` to appropriate HTTP status codes (499 Client Closed Request or 504 Gateway Timeout) and avoid logging false-positive severity alerts for benign client disconnects.
- Components NEVER drop context boundaries during request-scoped fan-out; asynchronous parallel operations MUST be managed using `errgroup.WithContext(r.Context())`.

## Bad vs Good Implementations
### Database Query and Goroutine Fan-Out Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using QueryRow without a context ignores upstream HTTP disconnections, leaving the PostgreSQL/MySQL connection handle tied up executing expensive queries. Spawning a fire-and-forget goroutine with context.Background() loses request lifecycle tracking and risk unbounded worker accumulation under heavy load.
```go
package main

import (
	"context"
	"database/sql"
	"net/http"

	"github.com/go-chi/chi/v5"
)

func HandleUserData(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		userID := chi.URLParam(r, "id")

		// Anti-pattern: Bypassing r.Context(), causing queries to keep running if client disconnects
		row := db.QueryRow("SELECT name, email FROM users WHERE id = $1", userID)
		var name, email string
		if err := row.Scan(&name, &email); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Anti-pattern: Unbounded, detached background work using context.Background()
		go func() {
			_, _ = db.ExecContext(context.Background(), "UPDATE users SET last_seen = NOW() WHERE id = $1", userID)
		}()

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(name))
	}
}
```

#### Production Standard (Correct)
> **Standard**: Passing ctx via db.QueryRowContext ensures that an aborted request immediately cancels the pending query on the database wire protocol. For asynchronous tasks that must outlive client disconnects, context.WithoutCancel(ctx) maintains trace baggage while severing cancellation, paired with an explicit timeout to prevent resource starvation.
```go
package main

import (
	"context"
	"database/sql"
	"errors"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"
)

func HandleUserData(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		userID := chi.URLParam(r, "id")

		// Invariant: Enforce client-bound context on all DB query handles
		row := db.QueryRowContext(ctx, "SELECT name, email FROM users WHERE id = $1", userID)
		var name, email string
		if err := row.Scan(&name, &email); err != nil {
			if errors.Is(err, context.Canceled) {
				// Client disconnected upstream; terminate early without noise
				return
			}
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}

		// Invariant: If asynchronous task must outlive client, detach safely using context.WithoutCancel with strict timeout
		bgCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
		go func() {
			defer cancel()
			_, _ = db.ExecContext(bgCtx, "UPDATE users SET last_seen = NOW() WHERE id = $1", userID)
		}()

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(name))
	}
}
```

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 Context-Aware Deadline and Upstream Cancellation Cascade

Go Chi Context-Aware Deadline and Upstream Cancellation Cascade defines an industrial-grade behavioral standard for backend engineering. Enforces strict propagation of Chi HTTP request contexts (`r.Context()`) down to all database drivers, external RPC calls, and derived child goroutines. Prevents orphaned goroutines, zombie connection leaks, and wasted compute across downstream dependencies when clients abort or disconnect 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: Ignoring r.Context() or Decoupling Background Goroutines with context.Background() 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 DriftIgnoring r.Context() or Decoupling Background Goroutines with context.Background()Critical
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()` directly to database methods (e.g., `QueryContext`, `ExecContext`, `BeginTx`) and external HTTP/gRPC client calls.

Engineers MUST ALWAYS pass `r.Context()` directly to database methods (e.g., `QueryContext`, `ExecContext`, `BeginTx`) and external HTTP/gRPC client calls.

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 raw `r.Context()` without observing cancellation channels (`ctx.Done()`).

Engineers MUST NOT spawn detached goroutines inside HTTP handlers using `context.Background()` or raw `r.Context()` without observing cancellation channels (`ctx.Done()`).

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

Services MUST configure `middleware.Timeout` or handle `context.WithTimeout` defensively to establish an upper-bound SLA deadline for every incoming route.

Services MUST configure `middleware.Timeout` or handle `context.WithTimeout` defensively to establish an upper-bound SLA deadline for every incoming route.

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 SHOULD map `context.Canceled` and `context.DeadlineExceeded` to appropriate HTTP status codes (499 Client Closed Request or 504 Gateway Timeout) and avoid logging false-positive severity alerts for benign client disconnects.

Code SHOULD map `context.Canceled` and `context.DeadlineExceeded` to appropriate HTTP status codes (499 Client Closed Request or 504 Gateway Timeout) and avoid logging false-positive severity alerts for benign client disconnects.

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 boundaries during request-scoped fan-out

Components NEVER drop context boundaries during request-scoped fan-out; asynchronous parallel operations MUST be managed using `errgroup.WithContext(r.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-Aware Deadline and Upstream Cancellation Cascade critical for AI coding assistants?

Enforces strict propagation of Chi HTTP request contexts (`r.Context()`) down to all database drivers, external RPC calls, and derived child goroutines. Prevents orphaned goroutines, zombie connection leaks, and wasted compute across downstream dependencies when clients abort or disconnect 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 (Ignoring r.Context() or Decoupling Background Goroutines with context.Background()) 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