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

Go Chi Context-Bounded Goroutine Tree Termination Invariant

Enforces strict cancellation propagation and deterministic drain guarantees for all worker goroutine trees spawned within Go Chi HTTP handlers. Ensures goroutine hierarchies honor r.Context().Done(), decouple unbuffered channels to eliminate deadlocks, and use sync.WaitGroup or errgroup.Group to guarantee complete sub-task draining prior to handler return when clients abruptly disconnect.

Prohibited Anti-Pattern: Spawning Uncoordinated Goroutines Consuming Chi r.Context() with Unbuffered Channel Writes and Dangling Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context-Bounded Goroutine Tree Termination Invariant - Enforces strict cancellation propagation and deterministic drain guarantees for all worker goroutine trees spawned within Go Chi HTTP handlers. Ensures goroutine hierarchies honor r.Context().Done(), decouple unbuffered channels to eliminate deadlocks, and use sync.WaitGroup or errgroup.Group to guarantee complete sub-task draining prior to handler return when clients abruptly disconnect.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-bounded-goroutine-tree-termination"
---

# Go Chi Context-Bounded Goroutine Tree Termination Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Uncoordinated Goroutines Consuming Chi r.Context() with Unbuffered Channel Writes and Dangling Leaks

## System Constraints
You are a Principal Go Systems Architect enforcing strict concurrency invariants in Go Chi HTTP services. You mandate that any goroutine spawned directly or transitively from an HTTP handler must be bound to r.Context(), propagate cancellation deterministically, guarantee drain completeness via errgroup or sync.WaitGroup, and prevent goroutine deadlocks caused by unbuffered channel writes during client disconnections.

## Strict Guidelines
- Engineers MUST ALWAYS bind child goroutine lifecycles to r.Context() using x/sync/errgroup.WithContext or explicit sync.WaitGroup drain barriers.
- Engineers MUST NEVER write to unbuffered channels from worker goroutines without a select branch monitoring ctx.Done() or providing an adequate channel buffer capacity matching worker concurrency.
- Code MUST ensure that the HTTP handler does NOT return before all spawned worker goroutines have completely terminated or transitioned to a detached, independently managed background context.
- Services MUST implement explicit timeouts via context.WithTimeout derived from r.Context() to prevent slow-loris or hanging upstream dependencies from pinning goroutine trees.
- Components NEVER pass r.Context() directly to asynchronous detached tasks (e.g., background fire-and-forget logging or asynchronous DB flushes); such operations MUST explicitly derive from context.WithoutCancel(r.Context()) or context.Background() with an isolated, bounded timeout.

## Bad vs Good Implementations
### Preventing Goroutine Leaks on Client Disconnection in Chi Handlers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When a client disconnects, r.Context() is cancelled, causing the handler select block to return immediately. The worker goroutine, however, blocks indefinitely on the unbuffered channel write `resultChan <- res` because there is no remaining receiver, leaking memory and goroutine stack frames permanently.
```go
package main

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

func HandleSearch(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: Unbuffered channel and uncoordinated goroutine.
	// If client closes connection prematurely, the handler returns or aborts,
	// but worker goroutines block forever writing to resultChan.
	resultChan := make(chan string)

	go func() {
		res := performExpensiveIO(r.Context())
		resultChan <- res // Deadlocks if reader departs on client disconnect
	}()

	select {
	case <-r.Context().Done():
		http.Error(w, r.Context().Err().Error(), http.StatusGatewayTimeout)
		return
	case res := <-resultChan:
		json.NewEncoder(w).Encode(map[string]string{"result": res})
	}
}

func performExpensiveIO(ctx interface{}) string { return "ok" }
```

#### Production Standard (Correct)
> **Standard**: Uses x/sync/errgroup bound to a derived context with a timeout. The deterministic barrier `g.Wait()` ensures all worker goroutines are drained prior to handler exit. If the client disconnects, `gctx.Done()` cancels downstream work, preventing blocked channel writes and memory leaks.
```go
package main

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

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

func HandleSearch(w http.ResponseWriter, r *http.Request) {
	// CORRECT: Deriving bounded context and tracking lifecycle with errgroup.
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

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

	g.Go(func() error {
		var err error
		res, err = performExpensiveSafeIO(gctx)
		return err
	})

	// Deterministic drain barrier: handler cannot return until goroutines terminate
	if err := g.Wait(); err != nil {
		if ctx.Err() == context.Canceled {
			// Client disconnected; avoid writing to closed socket
			return
		}
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(map[string]string{"result": res})
}

func performExpensiveSafeIO(ctx context.Context) (string, error) {
	select {
	case <-ctx.Done():
		return "", ctx.Err()
	case <-time.After(100 * time.Millisecond):
		return "ok", 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-Bounded Goroutine Tree Termination Invariant

Go Chi Context-Bounded Goroutine Tree Termination Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict cancellation propagation and deterministic drain guarantees for all worker goroutine trees spawned within Go Chi HTTP handlers. Ensures goroutine hierarchies honor r.Context().Done(), decouple unbuffered channels to eliminate deadlocks, and use sync.WaitGroup or errgroup.Group to guarantee complete sub-task draining prior to handler return when clients abruptly disconnect. 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 Uncoordinated Goroutines Consuming Chi r.Context() with Unbuffered Channel Writes and Dangling Leaks 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 Uncoordinated Goroutines Consuming Chi r.Context() with Unbuffered Channel Writes and Dangling LeaksCritical
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 bind child goroutine lifecycles to r.Context() using x/sync/errgroup.WithContext or explicit sync.WaitGroup drain barriers.

Engineers MUST ALWAYS bind child goroutine lifecycles to r.Context() using x/sync/errgroup.WithContext or explicit sync.WaitGroup drain barriers.

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 NEVER write to unbuffered channels from worker goroutines without a select branch monitoring ctx.Done() or providing an adequate channel buffer capacity matching worker concurrency.

Engineers MUST NEVER write to unbuffered channels from worker goroutines without a select branch monitoring ctx.Done() or providing an adequate channel buffer capacity matching worker concurrency.

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 ensure that the HTTP handler does NOT return before all spawned worker goroutines have completely terminated or transitioned to a detached, independently managed background context.

Code MUST ensure that the HTTP handler does NOT return before all spawned worker goroutines have completely terminated or transitioned to a detached, independently managed background 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

Services MUST implement explicit timeouts via context.WithTimeout derived from r.Context() to prevent slow-loris or hanging upstream dependencies from pinning goroutine trees.

Services MUST implement explicit timeouts via context.WithTimeout derived from r.Context() to prevent slow-loris or hanging upstream dependencies from pinning goroutine 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.
5

Components NEVER pass r.Context() directly to asynchronous detached tasks (e.g., background fire-and-forget logging or asynchronous DB flushes)

Components NEVER pass r.Context() directly to asynchronous detached tasks (e.g., background fire-and-forget logging or asynchronous DB flushes); such operations MUST explicitly derive from context.WithoutCancel(r.Context()) or context.Background() with an isolated, bounded timeout.

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-Bounded Goroutine Tree Termination Invariant critical for AI coding assistants?

Enforces strict cancellation propagation and deterministic drain guarantees for all worker goroutine trees spawned within Go Chi HTTP handlers. Ensures goroutine hierarchies honor r.Context().Done(), decouple unbuffered channels to eliminate deadlocks, and use sync.WaitGroup or errgroup.Group to guarantee complete sub-task draining prior to handler return when clients abruptly disconnect. 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 Uncoordinated Goroutines Consuming Chi r.Context() with Unbuffered Channel Writes and Dangling Leaks) 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