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-standard-go-chi-structure-947

Go Chi Structured Context Deadline Propagation & Goroutine Leak Prevention

Enforces strict parent context propagation across Chi HTTP middleware, downstream gRPC/SQL boundaries, and fan-out worker goroutines. Prevents catastrophic goroutine accumulation, resource leaks, and orphan RPC execution when client HTTP/3 multiplexed QUIC streams cancel or reset abruptly.

Prohibited Anti-Pattern: Detaching context or launching unmonitored goroutines inside Chi handlers during HTTP/3 stream cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Structured Context Deadline Propagation & Goroutine Leak Prevention - Enforces strict parent context propagation across Chi HTTP middleware, downstream gRPC/SQL boundaries, and fan-out worker goroutines. Prevents catastrophic goroutine accumulation, resource leaks, and orphan RPC execution when client HTTP/3 multiplexed QUIC streams cancel or reset abruptly.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-deadline-propagation-standard-go-chi-structure-947"
---

# Go Chi Structured Context Deadline Propagation & Goroutine Leak Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detaching context or launching unmonitored goroutines inside Chi handlers during HTTP/3 stream cancellation

## System Constraints
You are a Principal Backend Systems Architect enforcing zero-leak concurrency patterns in Go web services using the Chi router. You MUST enforce that all downstream database calls, external microservice RPCs, and internal async fan-outs derive directly from `r.Context()`. You MUST flag any invocation of `context.Background()` or `context.TODO()` in request lifecycles, enforce structured error groups (`golang.org/x/sync/errgroup`) with request-bound context, and ensure worker loops explicitly handle `ctx.Done()` to withstand rapid HTTP/3 multiplexed stream resets.

## Strict Guidelines
- Engineers MUST ALWAYS derive downstream contexts directly from `r.Context()` using `context.WithTimeout` or `context.WithDeadlineCause`.
- Engineers MUST NOT spawn detached goroutines inside Chi HTTP handlers without structured synchronization primitives such as `errgroup.WithContext(r.Context())`.
- Engineers MUST NEVER use `context.Background()` or `context.TODO()` to execute downstream database queries (e.g., `QueryContext`, `ExecContext`) or outbound gRPC calls originating from an active HTTP request.
- Code MUST select on `ctx.Done()` when performing blocking channel operations or long-polling loops within the request path to immediately terminate work on HTTP/3 stream cancellation.
- Services MUST configure Chi's `middleware.Timeout` upstream of business logic to guarantee deterministic upper bounds on all child operations.
- If asynchronous post-processing (e.g., non-critical telemetry, audit logging) must survive stream cancellation, engineers MUST use `context.WithoutCancel(r.Context())` paired with a strict, bounded deadline rather than raw `context.Background()`.

## Bad vs Good Implementations
### HTTP/3 Fan-Out and Database Query Execution in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `context.Background()` severs the connection between the client's HTTP/3 stream lifecycle and the database query. An HTTP/3 client reset will leave the database query executing indefinitely, and sending on an unbuffered channel without selecting on `r.Context().Done()` leaks the goroutine forever.
```go
package handler

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

func HandleSearch(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Detaching from r.Context() using context.Background()
		// When HTTP/3 client cancels the stream, DB query and goroutines orphan
		ctx := context.Background()
		resChan := make(chan []string)

		go func() {
			rows, _ := db.QueryContext(ctx, "SELECT name FROM items WHERE tenant_id = $1", r.URL.Query().Get("tid"))
			defer rows.Close()
			var items []string
			for rows.Next() {
				var name string
				_ = rows.Scan(&name)
				items = append(items, name)
			}
			resChan <- items // Leak risk: blocks forever if client disconnects before read
		}()

		items := <-resChan
		w.Write([]byte(items[0]))
	}
}
```

#### Production Standard (Correct)
> **Standard**: Derives a bounded deadline from `r.Context()`, uses structured concurrency via `errgroup.WithContext`, verifies `gctx.Err()` during iteration, and handles `context.Canceled` without emitting corrupt responses on dead HTTP/3 streams.
```go
package handler

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"net/http"
	"time"

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

func HandleSearch(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Enforce derived bounded context from request
		ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
		defer cancel()

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

		g.Go(func() error {
			rows, err := db.QueryContext(gctx, "SELECT name FROM items WHERE tenant_id = $1", r.URL.Query().Get("tid"))
			if err != nil {
				return err
			}
			defer rows.Close()

			for rows.Next() {
				if err := gctx.Err(); err != nil {
					return err
				}
				var name string
				if err := rows.Scan(&name); err != nil {
					return err
				}
				items = append(items, name)
			}
			return rows.Err()
		})

		if err := g.Wait(); err != nil {
			if errors.Is(err, context.Canceled) {
				// Client stream reset or canceled upstream; avoid writing broken headers
				return
			}
			http.Error(w, "Query failed", http.StatusInternalServerError)
			return
		}

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

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 Structured Context Deadline Propagation & Goroutine Leak Prevention

Go Chi Structured Context Deadline Propagation & Goroutine Leak Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces strict parent context propagation across Chi HTTP middleware, downstream gRPC/SQL boundaries, and fan-out worker goroutines. Prevents catastrophic goroutine accumulation, resource leaks, and orphan RPC execution when client HTTP/3 multiplexed QUIC streams cancel or reset abruptly. 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: Detaching context or launching unmonitored goroutines inside Chi handlers during HTTP/3 stream cancellation 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 DriftDetaching context or launching unmonitored goroutines inside Chi handlers during HTTP/3 stream cancellationCritical
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 downstream contexts directly from `r.Context()` using `context.WithTimeout` or `context.WithDeadlineCause`.

Engineers MUST ALWAYS derive downstream contexts directly from `r.Context()` using `context.WithTimeout` or `context.WithDeadlineCause`.

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 inside Chi HTTP handlers without structured synchronization primitives such as `errgroup.WithContext(r.Context())`.

Engineers MUST NOT spawn detached goroutines inside Chi HTTP handlers without structured synchronization primitives such as `errgroup.WithContext(r.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.
3

Engineers MUST NEVER use `context.Background()` or `context.TODO()` to execute downstream database queries (e.g., `QueryContext`, `ExecContext`) or outbound gRPC calls originating from an active HTTP request.

Engineers MUST NEVER use `context.Background()` or `context.TODO()` to execute downstream database queries (e.g., `QueryContext`, `ExecContext`) or outbound gRPC calls originating from an active HTTP request.

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

Code MUST select on `ctx.Done()` when performing blocking channel operations or long-polling loops within the request path to immediately terminate work on HTTP/3 stream cancellation.

Code MUST select on `ctx.Done()` when performing blocking channel operations or long-polling loops within the request path to immediately terminate work on HTTP/3 stream cancellation.

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

Services MUST configure Chi's `middleware.Timeout` upstream of business logic to guarantee deterministic upper bounds on all child operations.

Services MUST configure Chi's `middleware.Timeout` upstream of business logic to guarantee deterministic upper bounds on all child operations.

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

If asynchronous post-processing (e.g., non-critical telemetry, audit logging) must survive stream cancellation, engineers MUST use `context.WithoutCancel(r.Context())` paired with a strict, bounded deadline rather than raw `context.Background()`.

If asynchronous post-processing (e.g., non-critical telemetry, audit logging) must survive stream cancellation, engineers MUST use `context.WithoutCancel(r.Context())` paired with a strict, bounded deadline rather than raw `context.Background()`.

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 Structured Context Deadline Propagation & Goroutine Leak Prevention critical for AI coding assistants?

Enforces strict parent context propagation across Chi HTTP middleware, downstream gRPC/SQL boundaries, and fan-out worker goroutines. Prevents catastrophic goroutine accumulation, resource leaks, and orphan RPC execution when client HTTP/3 multiplexed QUIC streams cancel or reset abruptly. 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 (Detaching context or launching unmonitored goroutines inside Chi handlers during HTTP/3 stream cancellation) 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