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

Go Chi Upstream Context Deadline & Cascading RPC Cancellation Guardrail

Enforces strict derivation and propagation of HTTP request contexts across Chi middleware, database transactions, and outbound RPC trees. Guarantees deterministic cascading cancellation upon client disconnection or middleware timeout expiration, eliminating orphan goroutines and socket exhaustion under heavy degradation.

Prohibited Anti-Pattern: Severing context trees with context.Background() and unmonitored goroutines during outbound RPC fan-out

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Upstream Context Deadline & Cascading RPC Cancellation Guardrail - Enforces strict derivation and propagation of HTTP request contexts across Chi middleware, database transactions, and outbound RPC trees. Guarantees deterministic cascading cancellation upon client disconnection or middleware timeout expiration, eliminating orphan goroutines and socket exhaustion under heavy degradation.
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-propagation"
---

# Go Chi Upstream Context Deadline & Cascading RPC Cancellation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Severing context trees with context.Background() and unmonitored goroutines during outbound RPC fan-out

## System Constraints
You are a Principal Software Architect enforcing production-grade Go concurrency safety and Chi routing standards. You mandate that incoming HTTP request contexts (`r.Context()`) must never be severed, severed contexts must never be passed to downstream RPCs or database queries, and all fan-out concurrency must strictly bind to the derived request context lifecycle using errgroup or select-loop cancellation listeners.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` from Chi handlers directly or via `context.WithTimeoutCause` / `context.WithDeadlineCause` to outbound RPC clients, database drivers, and cache clients.
- Engineers MUST NOT instantiate detached root contexts using `context.Background()` or `context.TODO()` within the call graph of an incoming HTTP request.
- Code MUST monitor `ctx.Done()` when coordinating fan-out operations; concurrent branches MUST be managed using `golang.org/x/sync/errgroup.WithContext(ctx)` rather than raw, unmonitored goroutines.
- Services MUST register `chi.Middleware(middleware.Timeout(duration))` at the root router or route group level to enforce deterministic upper bounds on pipeline execution.
- Components NEVER execute asynchronous side effects by capturing `r.Context()` inside uncoordinated background goroutines, as the context is canceled immediately upon response finalization.

## Bad vs Good Implementations
### Context Propagation and Fan-out Cancellation in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler replaces r.Context() with context.Background(), severing the upstream Chi router deadline and client disconnection signals. The outbound goroutine makes a request with context.Background(), causing it to continue executing and leaking network sockets even if the handler returns after hitting a timeout.
```go
package handlers

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

func FetchAggregatedUserData(client *http.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Discarding r.Context(), severing client cancellation & Chi deadlines
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		resChan := make(chan UserProfile, 1)

		// ANTI-PATTERN: Leaking goroutine if client disconnects or timeout expires
		go func() {
			req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://api.internal/user", nil)
			res, err := client.Do(req)
			if err != nil {
				return
			}
			defer res.Body.Close()
			var profile UserProfile
			json.NewDecoder(res.Body).Decode(&profile)
			resChan <- profile
		}()

		select {
		case profile := <-resChan:
			json.NewEncoder(w).Encode(profile)
		case <-ctx.Done():
			http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout)
		}
	}
}
```

#### Production Standard (Correct)
> **Standard**: The handler derives its timeout from r.Context() using context.WithTimeoutCause, ensuring Chi middleware timeouts and client cancellations abort the operation. Sub-operations use errgroup.WithContext(gctx), terminating outbound socket calls instantly when cancellation cascades.
```go
package handlers

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

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

func FetchAggregatedUserData(client *http.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Derive bounded context from Chi request context to inherit upstream cancellations
		ctx, cancel := context.WithTimeoutCause(r.Context(), 3*time.Second, errors.New("user aggregation deadline exceeded"))
		defer cancel()

		g, gctx := errgroup.WithContext(ctx)
		var profile UserProfile

		g.Go(func() error {
			req, err := http.NewRequestWithContext(gctx, http.MethodGet, "https://api.internal/user", nil)
			if err != nil {
				return fmt.Errorf("failed creating downstream request: %w", err)
			}

			res, err := client.Do(req)
			if err != nil {
				return fmt.Errorf("downstream rpc failed: %w", err)
			}
			defer res.Body.Close()

			if err := json.NewDecoder(res.Body).Decode(&profile); err != nil {
				return fmt.Errorf("decoding profile payload: %w", err)
			}
			return nil
		})

		if err := g.Wait(); err != nil {
			if errors.Is(ctx.Err(), context.Canceled) {
				// 499 Client Closed Request or ignore since downstream connection severed
				return
			}
			if errors.Is(ctx.Err(), context.DeadlineExceeded) {
				http.Error(w, context.Cause(ctx).Error(), http.StatusGatewayTimeout)
				return
			}
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(profile)
	}
}
```

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 Upstream Context Deadline & Cascading RPC Cancellation Guardrail

Go Chi Upstream Context Deadline & Cascading RPC Cancellation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict derivation and propagation of HTTP request contexts across Chi middleware, database transactions, and outbound RPC trees. Guarantees deterministic cascading cancellation upon client disconnection or middleware timeout expiration, eliminating orphan goroutines and socket exhaustion under heavy degradation. 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: Severing context trees with context.Background() and unmonitored goroutines during outbound RPC fan-out 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 DriftSevering context trees with context.Background() and unmonitored goroutines during outbound RPC fan-outCritical
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 propagate `r.Context()` from Chi handlers directly or via `context.WithTimeoutCause` / `context.WithDeadlineCause` to outbound RPC clients, database drivers, and cache clients.

Engineers MUST ALWAYS propagate `r.Context()` from Chi handlers directly or via `context.WithTimeoutCause` / `context.WithDeadlineCause` to outbound RPC clients, database drivers, and cache clients.

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 detached root contexts using `context.Background()` or `context.TODO()` within the call graph of an incoming HTTP request.

Engineers MUST NOT instantiate detached root contexts using `context.Background()` or `context.TODO()` within the call graph of an incoming HTTP request.

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

Code MUST monitor `ctx.Done()` when coordinating fan-out operations

Code MUST monitor `ctx.Done()` when coordinating fan-out operations; concurrent branches MUST be managed using `golang.org/x/sync/errgroup.WithContext(ctx)` rather than raw, unmonitored goroutines.

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 register `chi.Middleware(middleware.Timeout(duration))` at the root router or route group level to enforce deterministic upper bounds on pipeline execution.

Services MUST register `chi.Middleware(middleware.Timeout(duration))` at the root router or route group level to enforce deterministic upper bounds on pipeline execution.

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 execute asynchronous side effects by capturing `r.Context()` inside uncoordinated background goroutines, as the context is canceled immediately upon response finalization.

Components NEVER execute asynchronous side effects by capturing `r.Context()` inside uncoordinated background goroutines, as the context is canceled immediately upon response finalization.

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 Upstream Context Deadline & Cascading RPC Cancellation Guardrail critical for AI coding assistants?

Enforces strict derivation and propagation of HTTP request contexts across Chi middleware, database transactions, and outbound RPC trees. Guarantees deterministic cascading cancellation upon client disconnection or middleware timeout expiration, eliminating orphan goroutines and socket exhaustion under heavy degradation. 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 (Severing context trees with context.Background() and unmonitored goroutines during outbound RPC fan-out) 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