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

Go 1.24 Chi Context-Bound Goroutine Pool Drain Invariant

Enforces deterministic cancellation propagation from Chi HTTP request contexts into all bounded goroutine pools and fan-out worker pipelines. Prevents orphaned database transactions, lingering connection leases, and hung upstream sockets by mandating context-aware dispatching, select-guarded channel writes, and strict errgroup drain mechanics on client disconnect.

Prohibited Anti-Pattern: Spawning uncoordinated goroutines or enqueuing work with detached contexts inside Chi HTTP request lifecycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Chi Context-Bound Goroutine Pool Drain Invariant - Enforces deterministic cancellation propagation from Chi HTTP request contexts into all bounded goroutine pools and fan-out worker pipelines. Prevents orphaned database transactions, lingering connection leases, and hung upstream sockets by mandating context-aware dispatching, select-guarded channel writes, and strict errgroup drain mechanics on client disconnect.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-bound-pool-drain-invariant"
---

# Go 1.24 Chi Context-Bound Goroutine Pool Drain Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning uncoordinated goroutines or enqueuing work with detached contexts inside Chi HTTP request lifecycles

## System Constraints
You are a Principal Go Architect enforcing strict context lifecycle management and goroutine leak prevention under Go 1.24 and Chi router. You must reject any concurrency model where goroutines outlive request boundaries or fail to terminate synchronously upon downstream HTTP client disconnects.

## Strict Guidelines
- Engineers MUST ALWAYS derive all concurrency lifecycles directly from chi's `r.Context()` using `errgroup.WithContext(r.Context())` or bounded worker pools that inspect `ctx.Done()` at every blocking point.
- Engineers MUST NOT pass `context.Background()` or `context.TODO()` to asynchronous tasks spawned within an HTTP handler unless explicitly annotated with a proven background job queue boundary.
- Code SHOULD leverage Go 1.24 context features and structured concurrency constructs to ensure that when a downstream client closes a connection, active database queries and socket I/O abort immediately.
- Services MUST select against `ctx.Done()` on every worker channel send and receive operation to guarantee instantaneous worker pool drain without deadlock.
- Components NEVER leak goroutines: all spawned concurrent subroutines must be joined, drained, and completed before the top-level Chi handler returns its HTTP response.

## Bad vs Good Implementations
### Uncoordinated Goroutine Fan-Out Leaking Connections on Disconnect

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler launches uncoordinated goroutines using sync.WaitGroup without binding to r.Context(). If the client terminates the HTTP connection early, database queries remain executing in orphaned goroutines, monopolizing database connection leases and memory.
```go
package handlers

import (
	"database/sql"
	"net/http"
	"sync"
)

func ProcessBatchHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ids := []string{"1", "2", "3", "4", "5"}
		var wg sync.WaitGroup

		for _, id := range ids {
			wg.Add(1)
			go func(id string) {
				defer wg.Done()
				// ANTI-PATTERN: Ignores r.Context(); query continues even if client aborts.
				// If the client disconnects, this continues to consume db connection pool leases.
				_, err := db.Exec("UPDATE records SET processed = true WHERE id = $1", id)
				if err != nil {
					return
				}
			}(id)
		}

		wg.Wait()
		w.WriteHeader(http.StatusOK)
	}
}
```

#### Production Standard (Correct)
> **Standard**: Uses errgroup.WithContext initialized with r.Context() and SetLimit to bound concurrency. All database queries pass ctx, ensuring immediate transaction abort and connection release upon downstream client disconnection.
```go
package handlers

import (
	"database/sql"
	"errors"
	"net/http"

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

func ProcessBatchHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ids := []string{"1", "2", "3", "4", "5"}
		
		// INVARIANT: Bind sub-task lifecycle directly to Chi HTTP request context
		g, ctx := errgroup.WithContext(r.Context())
		g.SetLimit(3) // Bounded concurrency guard

		for _, id := range ids {
			id := id
			g.Go(func() error {
				// Fast exit check prior to lease acquisition
				select {
				case <-ctx.Done():
					return ctx.Err()
				default:
				}

				// ExecContext propagates cancel instantly, releasing the db connection
				_, err := db.ExecContext(ctx, "UPDATE records SET processed = true WHERE id = $1", id)
				return err
			})
		}

		if err := g.Wait(); err != nil {
			if errors.Is(err, r.Context().Err()) {
				// Downstream client disconnected; pipeline drained deterministically
				return
			}
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusOK)
	}
}
```

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 Goroutine Pool Drain Invariant

Go 1.24 Chi Context-Bound Goroutine Pool Drain Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation propagation from Chi HTTP request contexts into all bounded goroutine pools and fan-out worker pipelines. Prevents orphaned database transactions, lingering connection leases, and hung upstream sockets by mandating context-aware dispatching, select-guarded channel writes, and strict errgroup drain mechanics on client 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 or enqueuing work with detached contexts inside Chi HTTP request lifecycles 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 or enqueuing work with detached contexts inside Chi HTTP request lifecyclesCritical
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 all concurrency lifecycles directly from chi's `r.Context()` using `errgroup.WithContext(r.Context())` or bounded worker pools that inspect `ctx.Done()` at every blocking point.

Engineers MUST ALWAYS derive all concurrency lifecycles directly from chi's `r.Context()` using `errgroup.WithContext(r.Context())` or bounded worker pools that inspect `ctx.Done()` at every blocking point.

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 pass `context.Background()` or `context.TODO()` to asynchronous tasks spawned within an HTTP handler unless explicitly annotated with a proven background job queue boundary.

Engineers MUST NOT pass `context.Background()` or `context.TODO()` to asynchronous tasks spawned within an HTTP handler unless explicitly annotated with a proven background job queue boundary.

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 SHOULD leverage Go 1.24 context features and structured concurrency constructs to ensure that when a downstream client closes a connection, active database queries and socket I/O abort immediately.

Code SHOULD leverage Go 1.24 context features and structured concurrency constructs to ensure that when a downstream client closes a connection, active database queries and socket I/O abort immediately.

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 select against `ctx.Done()` on every worker channel send and receive operation to guarantee instantaneous worker pool drain without deadlock.

Services MUST select against `ctx.Done()` on every worker channel send and receive operation to guarantee instantaneous worker pool drain without deadlock.

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 leak goroutines

Components NEVER leak goroutines: all spawned concurrent subroutines must be joined, drained, and completed before the top-level Chi handler returns its HTTP response.

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 Goroutine Pool Drain Invariant critical for AI coding assistants?

Enforces deterministic cancellation propagation from Chi HTTP request contexts into all bounded goroutine pools and fan-out worker pipelines. Prevents orphaned database transactions, lingering connection leases, and hung upstream sockets by mandating context-aware dispatching, select-guarded channel writes, and strict errgroup drain mechanics on client 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 or enqueuing work with detached contexts inside Chi HTTP request lifecycles) 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