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-and-shedding-standard

Chi v5 Strict Context Deadline Propagation, Shedding, and Cooperative Goroutine Termination

Enforces strict context deadline propagation and cooperative goroutine cancellation across Go Chi v5 middleware pipelines, downstream I/O calls, and asynchronous worker queues. Mandates immediate early load-shedding via bounded concurrency limiters and early context expiration checks to prevent goroutine leaks, unbounded memory growth, and cascading connection pool saturation.

Prohibited Anti-Pattern: Spawning detached unbuffered goroutines or continuing downstream I/O across Chi middleware after client context cancellation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Chi v5 Strict Context Deadline Propagation, Shedding, and Cooperative Goroutine Termination - Enforces strict context deadline propagation and cooperative goroutine cancellation across Go Chi v5 middleware pipelines, downstream I/O calls, and asynchronous worker queues. Mandates immediate early load-shedding via bounded concurrency limiters and early context expiration checks to prevent goroutine leaks, unbounded memory growth, and cascading connection pool saturation.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, api/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-deadline-propagation-and-shedding-standard"
---

# Chi v5 Strict Context Deadline Propagation, Shedding, and Cooperative Goroutine Termination

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached unbuffered goroutines or continuing downstream I/O across Chi middleware after client context cancellation.

## System Constraints
You are a Principal Software Architect enforcing production-grade Go Chi v5 Context-Deadline Propagation and Concurrency Shedding standards. You strictly reject code that spawns detached goroutines without lifecycle tracing, ignores context.Done() cancellation signals, relies on context.Background() inside request lifecycles, or lacks bounded concurrency semaphores at middleware layers.

## Strict Guidelines
- Engineers MUST ALWAYS pass r.Context() down every layer of the call stack (database queries, external HTTP clients, cache lookups, and transaction blocks) without decoupling.
- Engineers MUST NOT initialize background work using context.Background() or context.TODO() inside an active HTTP request handler; decoupled tasks must clone explicit telemetry attributes and utilize dedicated worker pools with application shutdown lifecycles.
- Engineers MUST ALWAYS implement bounded admission control (e.g., using a buffered channel semaphore or token bucket middleware) that immediately returns HTTP 503 or 429 when concurrency limits are breached, shedding requests prior to handler dispatch.
- Engineers MUST ALWAYS monitor select { case <-ctx.Done(): ... } prior to executing expensive operations and whenever interacting with non-cancellable APIs or long-running computations.
- Middleware chains MUST NEVER proceed to next.ServeHTTP(w, r) if r.Context().Err() is already non-nil (context.Canceled or context.DeadlineExceeded).
- Services MUST wrap HTTP servers with chi/middleware.Timeout and configure net/http.Server ReadHeaderTimeout, IdleTimeout, and BaseContext with unified lifecycle management.

## Bad vs Good Implementations
### Middleware Admission Control and Cooperative Cancellation Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an unmonitored goroutine using context.Background(), leaking runtime goroutines and database connections under cascading client timeouts. Uses context.TODO() instead of propagating r.Context(), preventing downstream drivers from cancelling queries when the upstream client aborts.
```go
package api

import (
	"context"
	"net/http"
	"github.com/go-chi/chi/v5"
)

func RegisterRoutes(r chi.Router, db *Database) {
	r.Post("/process", func(w http.ResponseWriter, r *http.Request) {
		// Flaw 1: Spawning decoupled goroutine with detached context
		go func() {
			// Flaw 2: context.Background isolates work from client disconnects
			_ = db.ExecuteHeavyReport(context.Background())
		}()

		// Flaw 3: Incurring downstream I/O without checking context state
		res, err := db.FetchUserData(context.TODO(), 12345)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(res)
	})
}
```

#### Production Standard (Correct)
> **Standard**: Implements non-blocking load shedding via a buffered concurrency channel, bounds total request execution time using Chi's Timeout middleware, enforces r.Context() propagation across all database methods, and terminates execution immediately if the client disconnects or times out.
```go
package api

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

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

type SheddingMiddleware struct {
	sem chan struct{}
}

func NewSheddingMiddleware(maxConcurrent int) *SheddingMiddleware {
	return &SheddingMiddleware{sem: make(chan struct{}, maxConcurrent)}
}

func (sm *SheddingMiddleware) Handler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		select {
		case sm.sem <- struct{}{}:
			defer func() { <-sm.sem }()
		case <-r.Context().Done():
			http.Error(w, "Client Closed Request", 499)
			return
		default:
			w.Header().Set("Retry-After", "5")
			http.Error(w, "Server Concurrency Limit Exceeded", http.StatusServiceUnavailable)
			return
		}

		if err := r.Context().Err(); err != nil {
			return
		}
		next.ServeHTTP(w, r)
	})
}

func MountRoutes(r chi.Router, db *Database, shedder *SheddingMiddleware) {
	r.Use(middleware.Timeout(5 * time.Second))
	r.Use(shedder.Handler)

	r.Post("/process", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		res, err := db.FetchUserData(ctx, 12345)
		if err != nil {
			if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
				return
			}
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusOK)
		_, _ = w.Write(res)
	})
}
```

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: Chi v5 Strict Context Deadline Propagation, Shedding, and Cooperative Goroutine Termination

Chi v5 Strict Context Deadline Propagation, Shedding, and Cooperative Goroutine Termination defines an industrial-grade behavioral standard for backend engineering. Enforces strict context deadline propagation and cooperative goroutine cancellation across Go Chi v5 middleware pipelines, downstream I/O calls, and asynchronous worker queues. Mandates immediate early load-shedding via bounded concurrency limiters and early context expiration checks to prevent goroutine leaks, unbounded memory growth, and cascading connection pool saturation. 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: Spawning detached unbuffered goroutines or continuing downstream I/O across Chi middleware after client context cancellation. 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 DriftSpawning detached unbuffered goroutines or continuing downstream I/O across Chi middleware after client context cancellation.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() down every layer of the call stack (database queries, external HTTP clients, cache lookups, and transaction blocks) without decoupling.

Engineers MUST ALWAYS pass r.Context() down every layer of the call stack (database queries, external HTTP clients, cache lookups, and transaction blocks) without decoupling.

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 initialize background work using context.Background() or context.TODO() inside an active HTTP request handler

Engineers MUST NOT initialize background work using context.Background() or context.TODO() inside an active HTTP request handler; decoupled tasks must clone explicit telemetry attributes and utilize dedicated worker pools with application shutdown lifecycles.

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 implement bounded admission control (e.g., using a buffered channel semaphore or token bucket middleware) that immediately returns HTTP 503 or 429 when concurrency limits are breached, shedding requests prior to handler dispatch.

Engineers MUST ALWAYS implement bounded admission control (e.g., using a buffered channel semaphore or token bucket middleware) that immediately returns HTTP 503 or 429 when concurrency limits are breached, shedding requests prior to handler dispatch.

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

Engineers MUST ALWAYS monitor select { case <-ctx.Done()

Engineers MUST ALWAYS monitor select { case <-ctx.Done(): ... } prior to executing expensive operations and whenever interacting with non-cancellable APIs or long-running computations.

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

Middleware chains MUST NEVER proceed to next.ServeHTTP(w, r) if r.Context().Err() is already non-nil (context.Canceled or context.DeadlineExceeded).

Middleware chains MUST NEVER proceed to next.ServeHTTP(w, r) if r.Context().Err() is already non-nil (context.Canceled or context.DeadlineExceeded).

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

Services MUST wrap HTTP servers with chi/middleware.Timeout and configure net/http.Server ReadHeaderTimeout, IdleTimeout, and BaseContext with unified lifecycle management.

Services MUST wrap HTTP servers with chi/middleware.Timeout and configure net/http.Server ReadHeaderTimeout, IdleTimeout, and BaseContext with unified lifecycle management.

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 Chi v5 Strict Context Deadline Propagation, Shedding, and Cooperative Goroutine Termination critical for AI coding assistants?

Enforces strict context deadline propagation and cooperative goroutine cancellation across Go Chi v5 middleware pipelines, downstream I/O calls, and asynchronous worker queues. Mandates immediate early load-shedding via bounded concurrency limiters and early context expiration checks to prevent goroutine leaks, unbounded memory growth, and cascading connection pool saturation. 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 (Spawning detached unbuffered goroutines or continuing downstream I/O across Chi middleware after client context cancellation.) 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

Chi