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

Go Chi Context-Tree Deadline Propagation & Goroutine Leak Guardrail

Enforces strict context tree inheritance and cancellation propagation across HTTP/2 and HTTP/3 Chi handlers to eliminate zombie goroutines. Guarantees client disconnects, socket resets, and stream cancellations cascade instantly to downstream I/O calls, while ensuring post-response tasks utilize explicit decoupled bounded workers instead of orphaned goroutines.

Prohibited Anti-Pattern: Spawning Untracked Goroutines from Chi Handler Contexts Causing Zombie Sockets and Memory Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context-Tree Deadline Propagation & Goroutine Leak Guardrail - Enforces strict context tree inheritance and cancellation propagation across HTTP/2 and HTTP/3 Chi handlers to eliminate zombie goroutines. Guarantees client disconnects, socket resets, and stream cancellations cascade instantly to downstream I/O calls, while ensuring post-response tasks utilize explicit decoupled bounded workers instead of orphaned goroutines.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-deadline-propagation-leak-prevention"
---

# Go Chi Context-Tree Deadline Propagation & Goroutine Leak Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning Untracked Goroutines from Chi Handler Contexts Causing Zombie Sockets and Memory Leaks

## System Constraints
You are a Principal Software Architect enforcing production-grade Go Chi concurrency semantics. Your mission is to eradicate goroutine leaks, unbounded socket exhaustion, and orphan worker routines caused by mishandling HTTP request contexts in Go Chi microservices. You MUST strictly enforce context propagation, errgroup-managed child contexts, bounded decouple mechanisms, and explicit handling of client connection drops across all HTTP/2 and HTTP/3 handlers.

## Strict Guidelines
- Engineers MUST ALWAYS pass `r.Context()` directly to database, RPC, and downstream outbound HTTP calls initiated by Chi handlers.
- Engineers MUST NOT spawn detached `go func()` routines that capture `r.Context()` without integrating `ctx.Done()` listener checks on every blocking channel send, receive, or I/O loop.
- Engineers MUST NEVER instantiate unbounded `go func(context.Background())` closures directly within a request handler to perform post-request background work; an isolated, bounded worker queue or an explicit `context.WithoutCancel` with strict deadline MUST be used instead.
- Concurrent child tasks spawned during a single request MUST be orchestrated using `errgroup.WithContext(r.Context())` to ensure immediate short-circuiting and cancellation cascade upon client disconnection or failure.
- All persistent loops or channel receivers within worker goroutines MUST evaluate `select { case <-ctx.Done(): return ctx.Err() ... }` to avoid permanent blocking on unbuffered channels when HTTP/2 RST_STREAM frames arrive.
- Code MUST verify and log `context.Canceled` versus `context.DeadlineExceeded` at the edge to distinguish genuine upstream timeouts from client-initiated disconnects without polluting alerting systems.

## Bad vs Good Implementations
### Chi Handler Goroutine Dispatch: Fire-and-Forget Anti-Pattern vs. Context-Managed Errgroup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an untracked goroutine using context.Background() and attempts an unbuffered write to a channel. If the client disconnects before the goroutine completes, the handler exits on r.Context().Done(), abandoning the channel receiver and permanently leaking the worker goroutine and network socket.
```go
package handlers

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

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

	// LEAK: Unbounded goroutine capturing r.Context() without select on ctx.Done()
	// If client closes HTTP/2 stream, this goroutine hangs indefinitely writing to results.
	go func() {
		res := queryExternalVendor(context.Background())
		results <- res // Hangs forever if handler exits early
	}()

	select {
	case data := <-results:
		w.Write([]byte(data[0]))
	case <-r.Context().Done():
		w.WriteHeader(http.StatusRequestTimeout)
	}
}
```

#### Production Standard (Correct)
> **Standard**: Leverages golang.org/x/sync/errgroup with context derivation from r.Context(). If the client closes the connection, gctx is canceled instantly, aborting queryExternalVendor via cancellation tree propagation. No channels are left dangling and no goroutines leak.
```go
package handlers

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

func SearchAggregator(w http.ResponseWriter, r *http.Request) {
	// Establish explicit timeout boundary on top of incoming client context
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	g, gctx := errgroup.WithContext(ctx)
	var vendorData []string

	g.Go(func() error {
		data, err := queryExternalVendor(gctx)
		if err != nil {
			return err
		}
		vendorData = data
		return nil
	})

	if err := g.Wait(); err != nil {
		if errors.Is(err, context.Canceled) {
			// Client disconnected early via HTTP/2 RST_STREAM or socket closure
			w.WriteHeader(499) // Client Closed Request
			return
		}
		http.Error(w, "upstream failure", http.StatusBadGateway)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte(vendorData[0]))
}
```

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-Tree Deadline Propagation & Goroutine Leak Guardrail

Go Chi Context-Tree Deadline Propagation & Goroutine Leak Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict context tree inheritance and cancellation propagation across HTTP/2 and HTTP/3 Chi handlers to eliminate zombie goroutines. Guarantees client disconnects, socket resets, and stream cancellations cascade instantly to downstream I/O calls, while ensuring post-response tasks utilize explicit decoupled bounded workers instead of orphaned goroutines. 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 Untracked Goroutines from Chi Handler Contexts Causing Zombie Sockets and Memory 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 Untracked Goroutines from Chi Handler Contexts Causing Zombie Sockets and Memory 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 pass `r.Context()` directly to database, RPC, and downstream outbound HTTP calls initiated by Chi handlers.

Engineers MUST ALWAYS pass `r.Context()` directly to database, RPC, and downstream outbound HTTP calls initiated by Chi handlers.

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 `go func()` routines that capture `r.Context()` without integrating `ctx.Done()` listener checks on every blocking channel send, receive, or I/O loop.

Engineers MUST NOT spawn detached `go func()` routines that capture `r.Context()` without integrating `ctx.Done()` listener checks on every blocking channel send, receive, or I/O loop.

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 NEVER instantiate unbounded `go func(context.Background())` closures directly within a request handler to perform post-request background work

Engineers MUST NEVER instantiate unbounded `go func(context.Background())` closures directly within a request handler to perform post-request background work; an isolated, bounded worker queue or an explicit `context.WithoutCancel` with strict deadline MUST be used instead.

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

Concurrent child tasks spawned during a single request MUST be orchestrated using `errgroup.WithContext(r.Context())` to ensure immediate short-circuiting and cancellation cascade upon client disconnection or failure.

Concurrent child tasks spawned during a single request MUST be orchestrated using `errgroup.WithContext(r.Context())` to ensure immediate short-circuiting and cancellation cascade upon client disconnection or failure.

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

All persistent loops or channel receivers within worker goroutines MUST evaluate `select { case <-ctx.Done()

All persistent loops or channel receivers within worker goroutines MUST evaluate `select { case <-ctx.Done(): return ctx.Err() ... }` to avoid permanent blocking on unbuffered channels when HTTP/2 RST_STREAM frames arrive.

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

Code MUST verify and log `context.Canceled` versus `context.DeadlineExceeded` at the edge to distinguish genuine upstream timeouts from client-initiated disconnects without polluting alerting systems.

Code MUST verify and log `context.Canceled` versus `context.DeadlineExceeded` at the edge to distinguish genuine upstream timeouts from client-initiated disconnects without polluting alerting systems.

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-Tree Deadline Propagation & Goroutine Leak Guardrail critical for AI coding assistants?

Enforces strict context tree inheritance and cancellation propagation across HTTP/2 and HTTP/3 Chi handlers to eliminate zombie goroutines. Guarantees client disconnects, socket resets, and stream cancellations cascade instantly to downstream I/O calls, while ensuring post-response tasks utilize explicit decoupled bounded workers instead of orphaned goroutines. 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 Untracked Goroutines from Chi Handler Contexts Causing Zombie Sockets and Memory 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