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

Go Chi Context Deadline Propagation and Goroutine Leak Prevention

Enforces strict HTTP request context propagation, deterministic timeout boundaries, and leak-free concurrency in go-chi microservices. Prohibits detached background goroutines that outlive request scopes without structured cancellation, preventing thread exhaustion, connection pool starvation, and file descriptor leaks.

Prohibited Anti-Pattern: Detaching Goroutines from Request Lifecycles Without Cancellation Channels or Resource Drainage

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Deadline Propagation and Goroutine Leak Prevention - Enforces strict HTTP request context propagation, deterministic timeout boundaries, and leak-free concurrency in go-chi microservices. Prohibits detached background goroutines that outlive request scopes without structured cancellation, preventing thread exhaustion, connection pool starvation, and file descriptor leaks.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-deadline-goroutine-leak-guardrails"
---

# Go Chi Context Deadline Propagation and Goroutine Leak Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detaching Goroutines from Request Lifecycles Without Cancellation Channels or Resource Drainage

## System Constraints
You are a Principal Engineer enforcing Go Chi Context Deadline & Goroutine Leak Guardrails. Mandate non-negotiable context propagation, preemptive cancellation, and strict socket drain boundaries across all HTTP handlers and asynchronous goroutines.

## Strict Guidelines
- Engineers MUST ALWAYS register `middleware.Timeout(duration)` high in the Chi middleware stack before terminal route handlers to establish hard execution deadlines.
- Engineers MUST NEVER launch unbounded goroutines (`go func()`) directly inside an HTTP handler that depend on `r.Context()` without a deterministic `select` on `ctx.Done()`.
- Outbound I/O calls (database queries, Redis calls, external HTTP calls) MUST ALWAYS accept and respect `r.Context()`, using `http.NewRequestWithContext` or equivalent driver context variants.
- Asynchronous background tasks that MUST survive HTTP response completion MUST explicitly decouple using `context.WithoutCancel(r.Context())` (Go 1.21+) or dedicated worker queues, capped with their own independent `context.WithTimeout`.
- Channels read or written across goroutines within a request lifecycle MUST be buffered appropriately or paired with a `ctx.Done()` select branch to prevent permanent goroutine parking upon client disconnection.

## Bad vs Good Implementations
### Unbounded Goroutine Spawning and Context Leaks in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching unmanaged goroutines that reference req.Context() causes unpredictable aborts or goroutine leaks. The unbuffered channel write hangs permanently if the consumer exits early on client cancellation, leaking memory and goroutine stacks.
```go
package server

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

func MountRoutes(r chi.Router, db Database) {
	r.Post("/process", func(w http.ResponseWriter, req *http.Request) {
		// VIOLATION: Spawning detached goroutine bound to req.Context().
		// When the client disconnects or Chi handler returns, req.Context() is canceled,
		// but if db.Execute ignores context or blocks, this leaks a goroutine.
		go func() {
			_ = db.Execute(req.Context(), "INSERT INTO audit_logs VALUES (1)")
		}()

		// VIOLATION: Unbuffered channel without select on req.Context().Done().
		// If client closes connection prematurely, the write hangs forever.
		ch := make(chan int)
		go func() {
			ch <- computePayload(req.Context())
		}()

		result := <-ch
		w.Write([]byte(string(rune(result))))
	})
}
```

#### Production Standard (Correct)
> **Standard**: Middleware enforces an overall timeout deadline. Background tasks are intentionally decoupled via context.WithoutCancel and bound to their own timeout. Channel operations use buffered channels and select against ctx.Done() to guarantee zero goroutine leaks.
```go
package server

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

func MountRoutes(r chi.Router, db Database, queue BackgroundQueue) {
	r.Use(middleware.Timeout(10 * time.Second))

	r.Post("/process", func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()

		// FIX: Safely decouple background work with explicit separate deadline
		bgCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
		queue.Submit(func() {
			defer cancel()
			_ = db.Execute(bgCtx, "INSERT INTO audit_logs VALUES (1)")
		})

		// FIX: Buffered channel + explicit select over ctx.Done() avoids goroutine leaks
		ch := make(chan int, 1)
		go func() {
			select {
			case <-ctx.Done():
				return
			case ch <- computePayload(ctx):
			}
		}()

		select {
		case <-ctx.Done():
			http.Error(w, ctx.Err().Error(), http.StatusGatewayTimeout)
			return
		case result := <-ch:
			w.WriteHeader(http.StatusOK)
			w.Write([]byte(string(rune(result))))
		}
	})
}
```

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 Deadline Propagation and Goroutine Leak Prevention

Go Chi Context Deadline Propagation and Goroutine Leak Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces strict HTTP request context propagation, deterministic timeout boundaries, and leak-free concurrency in go-chi microservices. Prohibits detached background goroutines that outlive request scopes without structured cancellation, preventing thread exhaustion, connection pool starvation, and file descriptor leaks. 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 Goroutines from Request Lifecycles Without Cancellation Channels or Resource Drainage 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 Goroutines from Request Lifecycles Without Cancellation Channels or Resource DrainageCritical
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 register `middleware.Timeout(duration)` high in the Chi middleware stack before terminal route handlers to establish hard execution deadlines.

Engineers MUST ALWAYS register `middleware.Timeout(duration)` high in the Chi middleware stack before terminal route handlers to establish hard execution deadlines.

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 NEVER launch unbounded goroutines (`go func()`) directly inside an HTTP handler that depend on `r.Context()` without a deterministic `select` on `ctx.Done()`.

Engineers MUST NEVER launch unbounded goroutines (`go func()`) directly inside an HTTP handler that depend on `r.Context()` without a deterministic `select` on `ctx.Done()`.

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

Outbound I/O calls (database queries, Redis calls, external HTTP calls) MUST ALWAYS accept and respect `r.Context()`, using `http.NewRequestWithContext` or equivalent driver context variants.

Outbound I/O calls (database queries, Redis calls, external HTTP calls) MUST ALWAYS accept and respect `r.Context()`, using `http.NewRequestWithContext` or equivalent driver context variants.

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

Asynchronous background tasks that MUST survive HTTP response completion MUST explicitly decouple using `context.WithoutCancel(r.Context())` (Go 1.21+) or dedicated worker queues, capped with their own independent `context.WithTimeout`.

Asynchronous background tasks that MUST survive HTTP response completion MUST explicitly decouple using `context.WithoutCancel(r.Context())` (Go 1.21+) or dedicated worker queues, capped with their own independent `context.WithTimeout`.

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

Channels read or written across goroutines within a request lifecycle MUST be buffered appropriately or paired with a `ctx.Done()` select branch to prevent permanent goroutine parking upon client disconnection.

Channels read or written across goroutines within a request lifecycle MUST be buffered appropriately or paired with a `ctx.Done()` select branch to prevent permanent goroutine parking upon client disconnection.

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

Enforces strict HTTP request context propagation, deterministic timeout boundaries, and leak-free concurrency in go-chi microservices. Prohibits detached background goroutines that outlive request scopes without structured cancellation, preventing thread exhaustion, connection pool starvation, and file descriptor leaks. 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 Goroutines from Request Lifecycles Without Cancellation Channels or Resource Drainage) 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