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

Go Chi Context-Bound Goroutine Lifecycle and Distributed Deadline Propagation

Enforces strict deadline and cancellation propagation across fan-out goroutines spawned within Go Chi HTTP handlers. Requires the use of context-derived error groups (e.g., errgroup.WithContext) and non-blocking channel selects to guarantee zero goroutine leaks and deterministic resource cleanup upon client disconnects or downstream RPC timeouts.

Prohibited Anti-Pattern: Unbounded Goroutine Spawning with context.Background() or Unsynchronized Channel Receives in Chi Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context-Bound Goroutine Lifecycle and Distributed Deadline Propagation - Enforces strict deadline and cancellation propagation across fan-out goroutines spawned within Go Chi HTTP handlers. Requires the use of context-derived error groups (e.g., errgroup.WithContext) and non-blocking channel selects to guarantee zero goroutine leaks and deterministic resource cleanup upon client disconnects or downstream RPC timeouts.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-bound-errgroup-pipeline"
---

# Go Chi Context-Bound Goroutine Lifecycle and Distributed Deadline Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Goroutine Spawning with context.Background() or Unsynchronized Channel Receives in Chi Handlers

## System Constraints
You are a Principal Backend Systems Architect enforcing strict concurrency invariants in Go Chi microservices. You must ensure that all concurrent subtasks initiated within an HTTP request lifecycle are strictly bound to the incoming `r.Context()`, orchestrate fan-out via `errgroup.WithContext`, observe deadline expiration on every blocking operation, and completely eliminate goroutine leaks caused by detached contexts, orphaned channels, or unbuffered synchronizations.

## Strict Guidelines
- Engineers MUST ALWAYS derive concurrent worker contexts directly from `r.Context()` using `errgroup.WithContext(ctx)` or explicit child context cancellation trees.
- Engineers MUST NOT spawn detached background goroutines (`go func()`) that reference `context.Background()` or `context.TODO()` to execute operations required for the current Chi HTTP response lifecycle.
- Engineers MUST ALWAYS ensure channel sends and receives within worker goroutines select on `ctx.Done()` to prevent permanent hangs when a sibling worker fails or the client disconnects.
- Engineers MUST ALWAYS size result channels to the exact concurrency factor (or utilize mutex-protected shared state guarded by the errgroup) when fan-out results are aggregated to avoid blocking terminated workers.
- Services MUST return HTTP 504 (Gateway Timeout) or HTTP 499 (Client Closed Request) explicitly when `errors.Is(ctx.Err(), context.DeadlineExceeded)` or `errors.Is(ctx.Err(), context.Canceled)` occurs during fan-out multiplexing.

## Bad vs Good Implementations
### Multiplexing RPC Fan-Out inside a Go Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The goroutine uses context.Background() instead of propagating r.Context(), decoupling its lifecycle from the client connection. The unbuffered channel resCh causes the worker goroutine to block forever if time.After triggers first, resulting in permanent memory and descriptor leaks.
```go
package handlers

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

func MultiplexBadHandler(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: Spawning unmanaged goroutines with an unbuffered channel
	// and detached background context, leading to permanent goroutine leaks on timeout.
	resCh := make(chan string)

	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()
		res, _ := callDownstreamRPC(ctx, "svc-a")
		resCh <- res // Leaks if receiver stops listening
	}()

	select {
	case res := <-resCh:
		json.NewEncoder(w).Encode(map[string]string{"result": res})
	case <-time.After(1 * time.Second):
		http.Error(w, "timeout", http.StatusGatewayTimeout)
	}
}
```

#### Production Standard (Correct)
> **Standard**: Leverages errgroup.WithContext bound directly to r.Context(), ensuring that client dropouts, downstream RPC errors, or timeout expiries immediately cancel all sibling goroutines via gctx. Guarantees deterministic barrier synchronization with g.Wait() before handler return, eliminating leaks entirely.
```go
package handlers

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

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

type AggregatedResponse struct {
	ServiceA string `json:"service_a"`
	ServiceB string `json:"service_b"`
}

func MultiplexGoodHandler(w http.ResponseWriter, r *http.Request) {
	// Derive bounded context from Chi request context with upper bound deadline
	ctx, cancel := context.WithTimeout(r.Context(), 1500*time.Millisecond)
	defer cancel()

	g, gctx := errgroup.WithContext(ctx)
	var res AggregatedResponse

	g.Go(func() error {
		val, err := callDownstreamRPC(gctx, "svc-a")
		if err != nil {
			return err
		}
		res.ServiceA = val
		return nil
	})

	g.Go(func() error {
		val, err := callDownstreamRPC(gctx, "svc-b")
		if err != nil {
			return err
		}
		res.ServiceB = val
		return nil
	})

	if err := g.Wait(); err != nil {
		if errors.Is(ctx.Err(), context.DeadlineExceeded) {
			http.Error(w, `{"error":"gateway timeout"}`, http.StatusGatewayTimeout)
			return
		}
		if errors.Is(ctx.Err(), context.Canceled) {
			// Client disconnected early
			w.WriteHeader(499)
			return
		}
		http.Error(w, `{"error":"internal error"}`, http.StatusBadGateway)
		return
	}

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Context-Bound Goroutine Lifecycle and Distributed Deadline Propagation

Go Chi Context-Bound Goroutine Lifecycle and Distributed Deadline Propagation defines an industrial-grade behavioral standard for backend engineering. Enforces strict deadline and cancellation propagation across fan-out goroutines spawned within Go Chi HTTP handlers. Requires the use of context-derived error groups (e.g., errgroup.WithContext) and non-blocking channel selects to guarantee zero goroutine leaks and deterministic resource cleanup upon client disconnects or downstream RPC timeouts. 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: Unbounded Goroutine Spawning with context.Background() or Unsynchronized Channel Receives in Chi 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 DriftUnbounded Goroutine Spawning with context.Background() or Unsynchronized Channel Receives in Chi HandlersCritical
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 derive concurrent worker contexts directly from `r.Context()` using `errgroup.WithContext(ctx)` or explicit child context cancellation trees.

Engineers MUST ALWAYS derive concurrent worker contexts directly from `r.Context()` using `errgroup.WithContext(ctx)` or explicit child context cancellation trees.

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 (`go func()`) that reference `context.Background()` or `context.TODO()` to execute operations required for the current Chi HTTP response lifecycle.

Engineers MUST NOT spawn detached background goroutines (`go func()`) that reference `context.Background()` or `context.TODO()` to execute operations required for the current Chi HTTP response lifecycle.

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 ensure channel sends and receives within worker goroutines select on `ctx.Done()` to prevent permanent hangs when a sibling worker fails or the client disconnects.

Engineers MUST ALWAYS ensure channel sends and receives within worker goroutines select on `ctx.Done()` to prevent permanent hangs when a sibling worker fails or the 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.
4

Engineers MUST ALWAYS size result channels to the exact concurrency factor (or utilize mutex-protected shared state guarded by the errgroup) when fan-out results are aggregated to avoid blocking terminated workers.

Engineers MUST ALWAYS size result channels to the exact concurrency factor (or utilize mutex-protected shared state guarded by the errgroup) when fan-out results are aggregated to avoid blocking terminated workers.

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

Services MUST return HTTP 504 (Gateway Timeout) or HTTP 499 (Client Closed Request) explicitly when `errors.Is(ctx.Err(), context.DeadlineExceeded)` or `errors.Is(ctx.Err(), context.Canceled)` occurs during fan-out multiplexing.

Services MUST return HTTP 504 (Gateway Timeout) or HTTP 499 (Client Closed Request) explicitly when `errors.Is(ctx.Err(), context.DeadlineExceeded)` or `errors.Is(ctx.Err(), context.Canceled)` occurs during fan-out multiplexing.

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-Bound Goroutine Lifecycle and Distributed Deadline Propagation critical for AI coding assistants?

Enforces strict deadline and cancellation propagation across fan-out goroutines spawned within Go Chi HTTP handlers. Requires the use of context-derived error groups (e.g., errgroup.WithContext) and non-blocking channel selects to guarantee zero goroutine leaks and deterministic resource cleanup upon client disconnects or downstream RPC timeouts. 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 (Unbounded Goroutine Spawning with context.Background() or Unsynchronized Channel Receives in Chi 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