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

Go 1.24 Chi Context-Bound Structured Concurrency & Graceful Cancellation

Enforces strict hierarchical context derivation, explicit lifetime containment, and bounded timeout propagation across concurrent fan-outs within Go 1.24 Chi HTTP routing pipelines. Prevents orphan goroutines, descriptor leaks, and distributed cascading failures by requiring all sub-tasks to bind to request context lifecycle signals.

Prohibited Anti-Pattern: Detached Goroutine Spawning and Context-Agnostic Channel Blocking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Chi Context-Bound Structured Concurrency & Graceful Cancellation - Enforces strict hierarchical context derivation, explicit lifetime containment, and bounded timeout propagation across concurrent fan-outs within Go 1.24 Chi HTTP routing pipelines. Prevents orphan goroutines, descriptor leaks, and distributed cascading failures by requiring all sub-tasks to bind to request context lifecycle signals.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-structured-concurrency-cancellation"
---

# Go 1.24 Chi Context-Bound Structured Concurrency & Graceful Cancellation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Goroutine Spawning and Context-Agnostic Channel Blocking

## System Constraints
You are a Principal Backend Systems Architect enforcing Go 1.24 runtime standards, Chi router idioms, and structured concurrency invariants. Mandate that every concurrent execution flow initiated within an HTTP handler derives directly or indirectly from http.Request.Context(), utilizes bounded errgroup.WithContext trees, guarantees resource termination on parent cancellation, and never leaks detached execution threads.

## Strict Guidelines
- Engineers MUST ALWAYS derive sub-operation contexts from r.Context() using context.WithTimeout, context.WithDeadline, or errgroup.WithContext.
- Engineers MUST NOT spawn detached goroutines using context.Background() or context.TODO() within HTTP request flows.
- Code MUST monitor ctx.Done() across all blocking channel receives, long-running loops, and synchronization points.
- Services MUST drain or cleanly abandon buffered channels when parent contexts are canceled, preventing worker goroutines from blocking indefinitely on channel writes.
- Components NEVER start asynchronous tasks inside Chi middleware or handlers without explicit join points or structured tracking (e.g., sync.WaitGroup or errgroup.Group) that guarantee termination before handler return unless delegated to an asynchronous durable worker queue.

## Bad vs Good Implementations
### Concurrent Fan-Out with Graceful Cancellation in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns a goroutine with detached context.Background(), ignores r.Context(), and performs unbuffered channel writes. If the HTTP client aborts or the handler times out after 2 seconds, the worker goroutine blocks indefinitely on channel transmission, leaking both memory and runtime threads.
```go
package handlers

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

func BadFanoutHandler(w http.ResponseWriter, r *http.Request) {
	results := make(chan string)

	// ANTI-PATTERN: Detached goroutine with context.Background()
	// If the HTTP client disconnects, this goroutine and network call leak.
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		res, _ := fetchExternalService(ctx)
		results <- res // Will block indefinitely if handler exits early
	}()

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

func fetchExternalService(ctx context.Context) (string, error) {
	time.Sleep(3 * time.Second)
	return "payload", nil
}
```

#### Production Standard (Correct)
> **Standard**: Binds execution to r.Context() using golang.org/x/sync/errgroup. Cancellation or client disconnects immediately propagate through gctx to all child RPC requests. errgroup.Wait guarantees that all goroutines terminate before the handler exits, preventing thread leaks and dangling writes.
```go
package handlers

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

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

type ResponseData struct {
	AuthStatus string `json:"auth_status"`
	Profile    string `json:"profile"`
}

func GoodFanoutHandler(w http.ResponseWriter, r *http.Request) {
	// Enforce hierarchical deadline capped at 2.5s within parent request lifecycle
	ctx, cancel := context.WithTimeout(r.Context(), 2500*time.Millisecond)
	defer cancel()

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

	g.Go(func() error {
		var err error
		authStatus, err = queryAuth(gctx)
		return err
	})

	g.Go(func() error {
		var err error
		profile, err = queryProfile(gctx)
		return err
	})

	if err := g.Wait(); err != nil {
		if ctx.Err() == context.DeadlineExceeded {
			http.Error(w, "gateway timeout", http.StatusGatewayTimeout)
			return
		}
		http.Error(w, "internal service error", http.StatusBadGateway)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(ResponseData{
		AuthStatus: authStatus,
		Profile:    profile,
	})
}

func queryAuth(ctx context.Context) (string, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://auth.internal/check", nil)
	if err != nil {
		return "", err
	}
	_ = req
	return "authenticated", nil
}

func queryProfile(ctx context.Context) (string, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://profile.internal/get", nil)
	if err != nil {
		return "", err
	}
	_ = req
	return "user-data", 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 1.24 Chi Context-Bound Structured Concurrency & Graceful Cancellation

Go 1.24 Chi Context-Bound Structured Concurrency & Graceful Cancellation defines an industrial-grade behavioral standard for backend engineering. Enforces strict hierarchical context derivation, explicit lifetime containment, and bounded timeout propagation across concurrent fan-outs within Go 1.24 Chi HTTP routing pipelines. Prevents orphan goroutines, descriptor leaks, and distributed cascading failures by requiring all sub-tasks to bind to request context lifecycle signals. 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: Detached Goroutine Spawning and Context-Agnostic Channel Blocking 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 DriftDetached Goroutine Spawning and Context-Agnostic Channel BlockingCritical
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 sub-operation contexts from r.Context() using context.WithTimeout, context.WithDeadline, or errgroup.WithContext.

Engineers MUST ALWAYS derive sub-operation contexts from r.Context() using context.WithTimeout, context.WithDeadline, or errgroup.WithContext.

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 goroutines using context.Background() or context.TODO() within HTTP request flows.

Engineers MUST NOT spawn detached goroutines using context.Background() or context.TODO() within HTTP request flows.

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() across all blocking channel receives, long-running loops, and synchronization points.

Code MUST monitor ctx.Done() across all blocking channel receives, long-running loops, and synchronization points.

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 drain or cleanly abandon buffered channels when parent contexts are canceled, preventing worker goroutines from blocking indefinitely on channel writes.

Services MUST drain or cleanly abandon buffered channels when parent contexts are canceled, preventing worker goroutines from blocking indefinitely on channel writes.

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 start asynchronous tasks inside Chi middleware or handlers without explicit join points or structured tracking (e.g., sync.WaitGroup or errgroup.Group) that guarantee termination before handler return unless delegated to an asynchronous durable worker queue.

Components NEVER start asynchronous tasks inside Chi middleware or handlers without explicit join points or structured tracking (e.g., sync.WaitGroup or errgroup.Group) that guarantee termination before handler return unless delegated to an asynchronous durable worker queue.

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 1.24 Chi Context-Bound Structured Concurrency & Graceful Cancellation critical for AI coding assistants?

Enforces strict hierarchical context derivation, explicit lifetime containment, and bounded timeout propagation across concurrent fan-outs within Go 1.24 Chi HTTP routing pipelines. Prevents orphan goroutines, descriptor leaks, and distributed cascading failures by requiring all sub-tasks to bind to request context lifecycle signals. 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 (Detached Goroutine Spawning and Context-Agnostic Channel Blocking) 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