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

Go Chi Structured Context Cancellation and Downstream IO Deadline Standard

Enforces deterministic lifecycle binding between inbound HTTP requests in Go Chi routers and all downstream database, RPC, and goroutine operations. Prevents resource exhaustion, connection pool starvation, and runaway zombie computations by ensuring that client disconnections and middleware deadlines strictly propagate through request contexts.

Prohibited Anti-Pattern: Orphaned Execution via context.Background() and Unchecked HTTP Disconnection

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Structured Context Cancellation and Downstream IO Deadline Standard - Enforces deterministic lifecycle binding between inbound HTTP requests in Go Chi routers and all downstream database, RPC, and goroutine operations. Prevents resource exhaustion, connection pool starvation, and runaway zombie computations by ensuring that client disconnections and middleware deadlines strictly propagate through request contexts.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-cancellation-io-timeout-standard"
---

# Go Chi Structured Context Cancellation and Downstream IO Deadline Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned Execution via context.Background() and Unchecked HTTP Disconnection

## System Constraints
You are a Principal Backend Architect enforcing strict context propagation and timeout standards for Go Chi microservices. Inbound HTTP requests in Chi must strictly bind their request context (`r.Context()`) to all downstream operations, including database transactions, cache lookups, and outbound network calls. You must aggressively eliminate `context.Background()` or `context.TODO()` in request lifecycles, require `chi/middleware.Timeout`, prevent goroutine leaks on client cancellations, and properly map `context.Canceled` and `context.DeadlineExceeded` to accurate HTTP status codes.

## Strict Guidelines
- Engineers MUST ALWAYS pass `r.Context()` directly to database queries, cache operations, and outbound RPC/HTTP clients rather than instantiating detached contexts.
- Engineers MUST NOT call `context.Background()` or `context.TODO()` within Chi handler execution paths unless explicitly spawning non-blocking background workers using `context.WithoutCancel(r.Context())` paired with dedicated bounded timeouts.
- Services MUST mount `middleware.Timeout` or per-route deadline constraints before resource-intensive handlers to establish deterministic upper bounds on I/O execution.
- Goroutines spawned during an HTTP request MUST select on `ctx.Done()` or leverage worker pools to prevent unbounded leakage when clients abort connections prematurely.
- Handlers MUST check `errors.Is(err, context.Canceled)` and `errors.Is(err, context.DeadlineExceeded)` to return appropriate HTTP status codes (HTTP 499 or HTTP 504) rather than generic internal server errors (HTTP 500).
- Database transactions MUST be initiated using `BeginTx(ctx, ...)` instead of `Begin()` to ensure zombie locks are rolled back immediately upon context cancellation.

## Bad vs Good Implementations
### Context Disconnection and Zombie Database Querying in Chi Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `context.Background()` severs the link between the HTTP client's connection and the database query. If the client closes the connection, the expensive SQL query continues executing on the database engine, wasting CPU/IO and holding pool connections.
```go
package handlers

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

func RegisterRoutes(r chi.Router, db *sql.DB) {
	r.Get("/reports/{id}", func(w http.ResponseWriter, r *http.Request) {
		id := chi.URLParam(r, "id")

		// ANTI-PATTERN: Ignores r.Context(); query continues even if client disconnects.
		// Database locks and pool resources are held indefinitely for dead clients.
		var report string
		err := db.QueryRowContext(context.Background(), "SELECT data FROM expensive_reports WHERE id = $1", id).Scan(&report)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"report": report})
	})
}
```

#### Production Standard (Correct)
> **Standard**: Wraps routes with `middleware.Timeout`, passes `r.Context()` directly to `QueryRowContext`, and checks for `context.Canceled` / `context.DeadlineExceeded` to immediately abort downstream queries and report canonical HTTP error codes.
```go
package handlers

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

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func RegisterRoutes(r chi.Router, db *sql.DB) {
	r.Group(func(sub chi.Router) {
		// Enforce deterministic 5-second deadline across all grouped endpoints
		sub.Use(middleware.Timeout(5 * time.Second))

		sub.Get("/reports/{id}", func(w http.ResponseWriter, r *http.Request) {
			ctx := r.Context()
			id := chi.URLParam(r, "id")

			// Invariant: Pass request context directly to database operations
			var report string
			err := db.QueryRowContext(ctx, "SELECT data FROM expensive_reports WHERE id = $1", id).Scan(&report)
			if err != nil {
				switch {
				case errors.Is(err, sql.ErrNoRows):
					http.Error(w, "report not found", http.StatusNotFound)
				case errors.Is(ctx.Err(), context.DeadlineExceeded):
					http.Error(w, "gateway timeout waiting for database", http.StatusGatewayTimeout)
				case errors.Is(ctx.Err(), context.Canceled):
					// Client disconnected early; abort gracefully without emitting 500
					return
				default:
					http.Error(w, "internal server error", http.StatusInternalServerError)
				}
				return
			}

			w.Header().Set("Content-Type", "application/json")
			_ = json.NewEncoder(w).Encode(map[string]string{"report": report})
		})
	})
}
```

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 Cancellation and Downstream IO Deadline Standard

Go Chi Structured Context Cancellation and Downstream IO Deadline Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic lifecycle binding between inbound HTTP requests in Go Chi routers and all downstream database, RPC, and goroutine operations. Prevents resource exhaustion, connection pool starvation, and runaway zombie computations by ensuring that client disconnections and middleware deadlines strictly propagate through request contexts. 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: Orphaned Execution via context.Background() and Unchecked HTTP Disconnection 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 DriftOrphaned Execution via context.Background() and Unchecked HTTP DisconnectionCritical
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 queries, cache operations, and outbound RPC/HTTP clients rather than instantiating detached contexts.

Engineers MUST ALWAYS pass `r.Context()` directly to database queries, cache operations, and outbound RPC/HTTP clients rather than instantiating detached contexts.

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 call `context.Background()` or `context.TODO()` within Chi handler execution paths unless explicitly spawning non-blocking background workers using `context.WithoutCancel(r.Context())` paired with dedicated bounded timeouts.

Engineers MUST NOT call `context.Background()` or `context.TODO()` within Chi handler execution paths unless explicitly spawning non-blocking background workers using `context.WithoutCancel(r.Context())` paired with dedicated bounded timeouts.

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

Services MUST mount `middleware.Timeout` or per-route deadline constraints before resource-intensive handlers to establish deterministic upper bounds on I/O execution.

Services MUST mount `middleware.Timeout` or per-route deadline constraints before resource-intensive handlers to establish deterministic upper bounds on I/O execution.

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

Goroutines spawned during an HTTP request MUST select on `ctx.Done()` or leverage worker pools to prevent unbounded leakage when clients abort connections prematurely.

Goroutines spawned during an HTTP request MUST select on `ctx.Done()` or leverage worker pools to prevent unbounded leakage when clients abort connections prematurely.

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

Handlers MUST check `errors.Is(err, context.Canceled)` and `errors.Is(err, context.DeadlineExceeded)` to return appropriate HTTP status codes (HTTP 499 or HTTP 504) rather than generic internal server errors (HTTP 500).

Handlers MUST check `errors.Is(err, context.Canceled)` and `errors.Is(err, context.DeadlineExceeded)` to return appropriate HTTP status codes (HTTP 499 or HTTP 504) rather than generic internal server errors (HTTP 500).

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

Database transactions MUST be initiated using `BeginTx(ctx, ...)` instead of `Begin()` to ensure zombie locks are rolled back immediately upon context cancellation.

Database transactions MUST be initiated using `BeginTx(ctx, ...)` instead of `Begin()` to ensure zombie locks are rolled back immediately upon context 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.
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 Cancellation and Downstream IO Deadline Standard critical for AI coding assistants?

Enforces deterministic lifecycle binding between inbound HTTP requests in Go Chi routers and all downstream database, RPC, and goroutine operations. Prevents resource exhaustion, connection pool starvation, and runaway zombie computations by ensuring that client disconnections and middleware deadlines strictly propagate through request contexts. 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 (Orphaned Execution via context.Background() and Unchecked HTTP Disconnection) 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