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-barrier

Go Chi Context Deadline Propagation and Goroutine Barrier Standard

Enforces strict bidirectional context cancellation, monotonic deadline propagation, and bounded goroutine pool drainage across Go Chi HTTP middleware chains. Eliminates phantom processing, compute leaks, and connection exhaustion caused by orphaned goroutines continuing work after client disconnection or timeout triggers.

Prohibited Anti-Pattern: Spawning detached goroutines or ignoring request context cancellation in deep Chi middleware and handlers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Deadline Propagation and Goroutine Barrier Standard - Enforces strict bidirectional context cancellation, monotonic deadline propagation, and bounded goroutine pool drainage across Go Chi HTTP middleware chains. Eliminates phantom processing, compute leaks, and connection exhaustion caused by orphaned goroutines continuing work after client disconnection or timeout triggers.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-deadline-propagation-barrier"
---

# Go Chi Context Deadline Propagation and Goroutine Barrier Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached goroutines or ignoring request context cancellation in deep Chi middleware and handlers.

## System Constraints
You are a Principal Software Architect enforcing production-grade Go context lifecycle invariants. In Chi router middleware stacks and request handlers, you must eliminate phantom execution and goroutine leaks by enforcing monotonic context deadline propagation, strict child context inheritance, and synchronized worker pool drainage via context-bound barriers.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` to all downstream I/O operations, database queries, and external RPC clients.
- Engineers MUST NOT spawn detached background goroutines using `context.Background()` or `context.TODO()` within the lifecycle of an HTTP request unless delegating to a decoupled, bounded queue manager.
- Handlers spawning concurrent sub-tasks MUST enforce bounded execution barriers using `golang.org/x/sync/errgroup.WithContext` or deterministic channel join points tied directly to `r.Context()`.
- Middleware stacks utilizing `chi/middleware.Timeout` MUST ensure that child contexts do not extend or overwrite upstream deadlines with larger durations, preserving monotonic deadline decrease.
- Workers and long-running loops MUST explicitly observe `ctx.Done()` at each iterative boundary and abort execution immediately upon context cancellation.
- Components NEVER drop context errors; if an operation terminates due to `ctx.Err()`, the handler MUST exit early, return HTTP 499 (Client Closed Request) or HTTP 504 (Gateway Timeout), and log the cancellation context cause.

## Bad vs Good Implementations
### Orphaned Fan-Out vs Bounded Synchronous Errgroup Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Goroutines are dispatched into the background without synchronization or completion tracking. If the upstream client disconnects or hits Chi's middleware timeout, the handler finishes immediately, but spawned goroutines run unboundedly (phantom processing), exhausting database connections and CPU.
```go
package main

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

func MountRoutes(r chi.Router) {
	r.Post("/process", func(w http.ResponseWriter, r *http.Request) {
		items := []string{"task1", "task2", "task3"}

		// ANTI-PATTERN: Fire-and-forget goroutines with unobserved context.
		// If the client disconnects or Chi timeout fires, these routines continue
		// running, wasting compute and exhausting database/API pools.
		for _, item := range items {
			go func(task string) {
				_ = processItem(r.Context(), task)
			}(item)
		}

		w.WriteHeader(http.StatusAccepted)
	})
}

func processItem(ctx context.Context, task string) error {
	// Heavy DB or external call
	return nil
}
```

#### Production Standard (Correct)
> **Standard**: Wraps concurrent tasks in an errgroup bounded by the request context. Cancellation triggers fail-fast termination across all active sub-tasks, draining the goroutine barrier cleanly and avoiding phantom execution when upstream calls abort.
```go
package main

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

	"github.com/go-chi/chi/v5"
	"golang.org/x/sync/errgroup"
)

func MountRoutes(r chi.Router) {
	r.Post("/process", func(w http.ResponseWriter, r *http.Request) {
		items := []string{"task1", "task2", "task3"}

		// INVARIANT: Bound fan-out to request context with deterministic drainage
		g, ctx := errgroup.WithContext(r.Context())
		g.SetLimit(4) // Bound concurrency pool

		for _, item := range items {
			task := item
			g.Go(func() error {
				select {
				case <-ctx.Done():
					return ctx.Err()
				default:
					return processItem(ctx, task)
				}
			})
		}

		if err := g.Wait(); err != nil {
			if errors.Is(err, context.Canceled) {
				// Upstream client disconnected, cease further processing
				w.WriteHeader(499)
				return
			}
			if errors.Is(err, context.DeadlineExceeded) {
				http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout)
				return
			}
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusOK)
	})
}

func processItem(ctx context.Context, task string) error {
	return nil
}
```

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 Deadline Propagation and Goroutine Barrier Standard

Go Chi Context Deadline Propagation and Goroutine Barrier Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict bidirectional context cancellation, monotonic deadline propagation, and bounded goroutine pool drainage across Go Chi HTTP middleware chains. Eliminates phantom processing, compute leaks, and connection exhaustion caused by orphaned goroutines continuing work after client disconnection or timeout triggers. 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 goroutines or ignoring request context cancellation in deep Chi middleware and handlers. 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 goroutines or ignoring request context cancellation in deep Chi middleware and handlers.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 propagate `r.Context()` to all downstream I/O operations, database queries, and external RPC clients.

Engineers MUST ALWAYS propagate `r.Context()` to all downstream I/O operations, database queries, and external RPC 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 spawn detached background goroutines using `context.Background()` or `context.TODO()` within the lifecycle of an HTTP request unless delegating to a decoupled, bounded queue manager.

Engineers MUST NOT spawn detached background goroutines using `context.Background()` or `context.TODO()` within the lifecycle of an HTTP request unless delegating to a decoupled, bounded queue manager.

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

Handlers spawning concurrent sub-tasks MUST enforce bounded execution barriers using `golang.org/x/sync/errgroup.WithContext` or deterministic channel join points tied directly to `r.Context()`.

Handlers spawning concurrent sub-tasks MUST enforce bounded execution barriers using `golang.org/x/sync/errgroup.WithContext` or deterministic channel join points tied directly to `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.
4

Middleware stacks utilizing `chi/middleware.Timeout` MUST ensure that child contexts do not extend or overwrite upstream deadlines with larger durations, preserving monotonic deadline decrease.

Middleware stacks utilizing `chi/middleware.Timeout` MUST ensure that child contexts do not extend or overwrite upstream deadlines with larger durations, preserving monotonic deadline decrease.

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

Workers and long-running loops MUST explicitly observe `ctx.Done()` at each iterative boundary and abort execution immediately upon context cancellation.

Workers and long-running loops MUST explicitly observe `ctx.Done()` at each iterative boundary and abort execution immediately upon context cancellation.

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

Components NEVER drop context errors

Components NEVER drop context errors; if an operation terminates due to `ctx.Err()`, the handler MUST exit early, return HTTP 499 (Client Closed Request) or HTTP 504 (Gateway Timeout), and log the cancellation context cause.

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 Deadline Propagation and Goroutine Barrier Standard critical for AI coding assistants?

Enforces strict bidirectional context cancellation, monotonic deadline propagation, and bounded goroutine pool drainage across Go Chi HTTP middleware chains. Eliminates phantom processing, compute leaks, and connection exhaustion caused by orphaned goroutines continuing work after client disconnection or timeout triggers. 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 goroutines or ignoring request context cancellation in deep Chi middleware and handlers.) 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