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

Go Chi Context Propagation & Upstream Resource Cancellation Invariant

Enforces deterministic cancellation propagation from Go Chi HTTP request contexts to downstream database connection pools, transactions, and child goroutines. Guarantees that premature client disconnections immediately terminate in-flight queries and release database connection leases, preventing connection pool starvation and orphaned backend execution.

Prohibited Anti-Pattern: Orphaned DB Leases and Zombie Goroutines via context.Background() or Unpropagated Chi Request Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Propagation & Upstream Resource Cancellation Invariant - Enforces deterministic cancellation propagation from Go Chi HTTP request contexts to downstream database connection pools, transactions, and child goroutines. Guarantees that premature client disconnections immediately terminate in-flight queries and release database connection leases, preventing connection pool starvation and orphaned backend execution.
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-propagation-guardrail"
---

# Go Chi Context Propagation & Upstream Resource Cancellation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned DB Leases and Zombie Goroutines via context.Background() or Unpropagated Chi Request Contexts

## System Constraints
You are a Principal Backend Architect enforcing strict Go Chi Context Propagation and Upstream Resource Cancellation invariants. You must prevent orphaned goroutines, connection pool exhaustion, and zombie SQL executions caused by client disconnects. Ensure every blocking call, database query, external network request, and spawned goroutine strictly derives from and respects `r.Context()`. Mandate that intentionally detached background tasks explicitly use `context.WithoutCancel` with dedicated bounded timeouts.

## Strict Guidelines
- Engineers MUST ALWAYS pass `r.Context()` directly into downstream data layers, drivers, and external client calls (`QueryContext`, `ExecContext`, `BeginTx`).
- Engineers MUST NOT instantiate `context.Background()` or `context.TODO()` inside HTTP request handlers or synchronous service logic.
- Engineers MUST ALWAYS manage concurrent child operations using `errgroup.WithContext(r.Context())` rather than bare `go func()` invocations.
- Services MUST monitor `ctx.Done()` in streaming, long-polling, or iterative batch handlers to abort immediately upon client TCP resets or disconnections.
- Code MUST explicitly call `tx.Rollback()` in a deferred closure so context cancellations trigger immediate rollback and release the acquired connection back to the pool.
- Engineers MUST use Go 1.21+ `context.WithoutCancel(r.Context())` wrapped with an independent `context.WithTimeout` ONLY when completing strictly required asynchronous side-effects (e.g., critical audit logging) that must outlive client disconnection.

## Bad vs Good Implementations
### Context Propagation and Concurrent Goroutine Safety in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: db.Query ignores r.Context(), keeping the SQL connection reserved until the query completes even if the client disconnects immediately. The unmonitored goroutine uses context.Background(), leaking resources without bounded execution or synchronization.
```go
package handlers

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

func GetUserMetrics(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// VIOLATION: Discards r.Context(); query continues running if client disconnects.
		rows, err := db.Query("SELECT metric_key, val FROM metrics WHERE user_id = $1", r.URL.Query().Get("id"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		// VIOLATION: Unbounded bare goroutine with detached context runs as a zombie.
		go func() {
			_, _ = db.ExecContext(context.Background(), "UPDATE users SET last_accessed_at = NOW() WHERE id = $1", r.URL.Query().Get("id"))
		}()

		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
	}
}
```

#### Production Standard (Correct)
> **Standard**: r.Context() is directly propagated into database calls, terminating the execution on client disconnect. Sub-goroutines are managed through errgroup, and detached operations strictly utilize context.WithoutCancel with an explicit, bounded deadline.
```go
package handlers

import (
	"context"
	"database/sql"
	"encoding/json"
	"net/http"
	"time"

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

func GetUserMetrics(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		// CORRECT: Propagates r.Context(); query aborts and releases connection if client disconnects
		rows, err := db.QueryContext(ctx, "SELECT metric_key, val FROM metrics WHERE user_id = $1", r.URL.Query().Get("id"))
		if err != nil {
			if ctx.Err() != nil {
				return // Client disconnected; do not write response
			}
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		g, gctx := errgroup.WithContext(ctx)
		g.Go(func() error {
			// CORRECT: Child tasks track cancellation
			return trackActivity(gctx, db, r.URL.Query().Get("id"))
		})

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

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
	}
}

func trackActivity(ctx context.Context, db *sql.DB, userID string) error {
	// CORRECT: Safe async side-effect detached with explicit bounded timeout
	asyncCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
	defer cancel()
	_, err := db.ExecContext(asyncCtx, "UPDATE users SET last_accessed_at = NOW() WHERE id = $1", userID)
	return err
}
```

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 Propagation & Upstream Resource Cancellation Invariant

Go Chi Context Propagation & Upstream Resource Cancellation Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation propagation from Go Chi HTTP request contexts to downstream database connection pools, transactions, and child goroutines. Guarantees that premature client disconnections immediately terminate in-flight queries and release database connection leases, preventing connection pool starvation and orphaned backend execution. 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 DB Leases and Zombie Goroutines via context.Background() or Unpropagated Chi Request Contexts 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 DB Leases and Zombie Goroutines via context.Background() or Unpropagated Chi Request ContextsCritical
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 into downstream data layers, drivers, and external client calls (`QueryContext`, `ExecContext`, `BeginTx`).

Engineers MUST ALWAYS pass `r.Context()` directly into downstream data layers, drivers, and external client calls (`QueryContext`, `ExecContext`, `BeginTx`).

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 instantiate `context.Background()` or `context.TODO()` inside HTTP request handlers or synchronous service logic.

Engineers MUST NOT instantiate `context.Background()` or `context.TODO()` inside HTTP request handlers or synchronous service logic.

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

Engineers MUST ALWAYS manage concurrent child operations using `errgroup.WithContext(r.Context())` rather than bare `go func()` invocations.

Engineers MUST ALWAYS manage concurrent child operations using `errgroup.WithContext(r.Context())` rather than bare `go func()` invocations.

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 monitor `ctx.Done()` in streaming, long-polling, or iterative batch handlers to abort immediately upon client TCP resets or disconnections.

Services MUST monitor `ctx.Done()` in streaming, long-polling, or iterative batch handlers to abort immediately upon client TCP resets or disconnections.

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

Code MUST explicitly call `tx.Rollback()` in a deferred closure so context cancellations trigger immediate rollback and release the acquired connection back to the pool.

Code MUST explicitly call `tx.Rollback()` in a deferred closure so context cancellations trigger immediate rollback and release the acquired connection back to the 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.
6

Engineers MUST use Go 1.21+ `context.WithoutCancel(r.Context())` wrapped with an independent `context.WithTimeout` ONLY when completing strictly required asynchronous side-effects (e.g., critical audit logging) that must outlive client disconnection.

Engineers MUST use Go 1.21+ `context.WithoutCancel(r.Context())` wrapped with an independent `context.WithTimeout` ONLY when completing strictly required asynchronous side-effects (e.g., critical audit logging) that must outlive 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.
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 & Upstream Resource Cancellation Invariant critical for AI coding assistants?

Enforces deterministic cancellation propagation from Go Chi HTTP request contexts to downstream database connection pools, transactions, and child goroutines. Guarantees that premature client disconnections immediately terminate in-flight queries and release database connection leases, preventing connection pool starvation and orphaned backend execution. 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 DB Leases and Zombie Goroutines via context.Background() or Unpropagated Chi Request Contexts) 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