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

Go Chi HTTP/3 Context Lifeline & Request-Scoped Goroutine Pool Draining

Enforces deterministic cancellation propagation and synchronous goroutine pool draining for Go Chi services serving HTTP/3 (QUIC). Prevents orphaned worker routines, memory bloat, and file descriptor exhaustion triggered by rapid QUIC client stream resets.

Prohibited Anti-Pattern: Detached Goroutine Fan-Out Leaks Workers Under High-Frequency QUIC Stream Resets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi HTTP/3 Context Lifeline & Request-Scoped Goroutine Pool Draining - Enforces deterministic cancellation propagation and synchronous goroutine pool draining for Go Chi services serving HTTP/3 (QUIC). Prevents orphaned worker routines, memory bloat, and file descriptor exhaustion triggered by rapid QUIC client stream resets.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-context-lifeline-draining"
---

# Go Chi HTTP/3 Context Lifeline & Request-Scoped Goroutine Pool Draining

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Goroutine Fan-Out Leaks Workers Under High-Frequency QUIC Stream Resets

## System Constraints
You are a Principal Backend Systems Architect enforcing strict Go Chi HTTP/3 concurrency standards. QUIC stream cancellations (e.g., RESET_STREAM frames) instantly cancel the underlying request context. You must mandate that all parallel sub-tasks derive strictly from r.Context(), execute within deterministic worker groups (such as errgroup with concurrency bounds), and block on explicit draining before Chi handlers return to ensure zero orphaned goroutines.

## Strict Guidelines
- Engineers MUST ALWAYS bind any sub-task goroutine lifecycle directly to `r.Context()` to react instantly to HTTP/3 `RESET_STREAM` wire events.
- Engineers MUST ALWAYS synchronously drain all request-scoped worker goroutines using `errgroup.WithContext` or a bounded `sync.WaitGroup` before the HTTP handler returns.
- Engineers MUST NOT spawn unbounded, detached `go func()` routines within Chi middleware or handlers that outlive the wire stream.
- Workers MUST select on both internal task channels and `ctx.Done()` at every blocking I/O or coordination point to abort immediately on stream reset.
- Background tasks that must outlive client disconnection MUST be dispatched explicitly to an isolated, decouple application-level worker queue or task bus, NEVER to ad-hoc goroutines referencing request state.
- Handlers MUST gracefully handle and silence `context.Canceled` or QUIC application stream reset errors when client cancellation is intentional.

## Bad vs Good Implementations
### Unbounded Detached Fan-Out vs. Context-Bound errgroup Draining

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns unmanaged goroutines that do not observe `r.Context()`. If an HTTP/3 client issues a QUIC `RESET_STREAM`, the handler may exit prematurely or hang, leaving orphaned goroutines consuming CPU and memory. Furthermore, channel writes risk blocking forever if the handler exits early on a panic or reset.
```go
package main

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

type Item struct{ ID string }

func BadBatchHandler(w http.ResponseWriter, r *http.Request) {
	items := []Item{{ID: "1"}, {ID: "2"}, {ID: "3"}}
	resCh := make(chan string, len(items))

	// ANTI-PATTERN: Fire-and-forget goroutines spawned without draining.
	// Under HTTP/3, client cancels with RESET_STREAM; r.Context() cancels,
	// but if handler returns or workers ignore ctx, routines leak and run indefinitely.
	for _, item := range items {
		go func(it Item) {
			// Expensive I/O ignoring context lifecycle
			res := processItem(it.ID)
			resCh <- res
		}(item)
	}

	results := make([]string, 0, len(items))
	for i := 0; i < len(items); i++ {
		results = append(results, <-resCh)
	}

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

func processItem(id string) string { return id }
```

#### Production Standard (Correct)
> **Standard**: Uses `errgroup.WithContext` tied to `r.Context()` with strict concurrency limits (`SetLimit`). Every worker checks context cancellation, and `g.Wait()` deterministically drains all goroutines before the Chi handler returns, preventing leaks under rapid QUIC stream resets.
```go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"golang.org/x/sync/errgroup"
)

type Item struct{ ID string }

func GoodBatchHandler(w http.ResponseWriter, r *http.Request) {
	items := []Item{{ID: "1"}, {ID: "2"}, {ID: "3"}}
	results := make([]string, len(items))

	// Bind pool directly to wire context and bound concurrency
	g, ctx := errgroup.WithContext(r.Context())
	g.SetLimit(4) // Bound worker pool to prevent resource exhaustion

	for i, item := range items {
		idx, it := i, item
		g.Go(func() error {
			// Abort early if QUIC stream reset occurred
			select {
			case <-ctx.Done():
				return ctx.Err()
			default:
			}

			res, err := processItemWithContext(ctx, it.ID)
			if err != nil {
				return err
			}

			results[idx] = res
			return nil
		})
	}

	// Synchronously drain all goroutines before exiting the handler frame
	if err := g.Wait(); err != nil {
		if errors.Is(err, context.Canceled) {
			// Wire stream was cancelled by client (e.g., QUIC RESET_STREAM)
			return
		}
		http.Error(w, "Internal processing error", http.StatusInternalServerError)
		return
	}

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

func processItemWithContext(ctx context.Context, id string) (string, error) {
	// Simulates context-aware operational call
	select {
	case <-ctx.Done():
		return "", ctx.Err()
	default:
		return id, 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 HTTP/3 Context Lifeline & Request-Scoped Goroutine Pool Draining

Go Chi HTTP/3 Context Lifeline & Request-Scoped Goroutine Pool Draining defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation propagation and synchronous goroutine pool draining for Go Chi services serving HTTP/3 (QUIC). Prevents orphaned worker routines, memory bloat, and file descriptor exhaustion triggered by rapid QUIC client stream resets. 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 Fan-Out Leaks Workers Under High-Frequency QUIC Stream Resets 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 Fan-Out Leaks Workers Under High-Frequency QUIC Stream ResetsCritical
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 any sub-task goroutine lifecycle directly to `r.Context()` to react instantly to HTTP/3 `RESET_STREAM` wire events.

Engineers MUST ALWAYS bind any sub-task goroutine lifecycle directly to `r.Context()` to react instantly to HTTP/3 `RESET_STREAM` wire events.

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 ALWAYS synchronously drain all request-scoped worker goroutines using `errgroup.WithContext` or a bounded `sync.WaitGroup` before the HTTP handler returns.

Engineers MUST ALWAYS synchronously drain all request-scoped worker goroutines using `errgroup.WithContext` or a bounded `sync.WaitGroup` before the HTTP handler returns.

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 NOT spawn unbounded, detached `go func()` routines within Chi middleware or handlers that outlive the wire stream.

Engineers MUST NOT spawn unbounded, detached `go func()` routines within Chi middleware or handlers that outlive the wire stream.

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

Workers MUST select on both internal task channels and `ctx.Done()` at every blocking I/O or coordination point to abort immediately on stream reset.

Workers MUST select on both internal task channels and `ctx.Done()` at every blocking I/O or coordination point to abort immediately on stream reset.

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

Background tasks that must outlive client disconnection MUST be dispatched explicitly to an isolated, decouple application-level worker queue or task bus, NEVER to ad-hoc goroutines referencing request state.

Background tasks that must outlive client disconnection MUST be dispatched explicitly to an isolated, decouple application-level worker queue or task bus, NEVER to ad-hoc goroutines referencing request state.

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

Handlers MUST gracefully handle and silence `context.Canceled` or QUIC application stream reset errors when client cancellation is intentional.

Handlers MUST gracefully handle and silence `context.Canceled` or QUIC application stream reset errors when client cancellation is intentional.

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 HTTP/3 Context Lifeline & Request-Scoped Goroutine Pool Draining critical for AI coding assistants?

Enforces deterministic cancellation propagation and synchronous goroutine pool draining for Go Chi services serving HTTP/3 (QUIC). Prevents orphaned worker routines, memory bloat, and file descriptor exhaustion triggered by rapid QUIC client stream resets. 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 Fan-Out Leaks Workers Under High-Frequency QUIC Stream Resets) 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