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

Go Chi Context Cancellation & Strict Deadline Propagation

Enforces strict downstream context propagation, client disconnect detection, and boundary timeouts across Go Chi HTTP middleware and handlers. Prevents orphaned goroutine leaks, uncancelable long-running transactions, and database pool starvation during premature client termination.

Prohibited Anti-Pattern: Discarding r.Context() or spawning background goroutines with context.Background() in HTTP middleware pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Cancellation & Strict Deadline Propagation - Enforces strict downstream context propagation, client disconnect detection, and boundary timeouts across Go Chi HTTP middleware and handlers. Prevents orphaned goroutine leaks, uncancelable long-running transactions, and database pool starvation during premature client termination.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-cancellation-deadline-propagation"
---

# Go Chi Context Cancellation & Strict Deadline Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Discarding r.Context() or spawning background goroutines with context.Background() in HTTP middleware pipelines

## System Constraints
You are a Principal Backend Architect enforcing strict Go Chi context cancellation semantics, timeout propagation, and resource cleanup across HTTP middleware stacks. Ensure no goroutines are orphaned, database queries respect r.Context(), and custom middleware properly detects client disconnects.

## Strict Guidelines
- Handlers and middleware MUST ALWAYS pass `r.Context()` to all downstream blocking operations, including SQL queries, gRPC calls, Redis operations, and channel receives.
- Engineers MUST NOT instantiate `context.Background()` or `context.TODO()` inside HTTP request life cycles unless explicitly detached for an asynchronous background task with dedicated tracing and timeout isolation.
- Middleware that enforces deadlines MUST derive a child context using `context.WithTimeout(r.Context(), timeout)` or `context.WithDeadline` and pass `r.WithContext(ctx)` to the next handler, always ensuring `cancel()` is deferred.
- Asynchronous tasks spawned from a request MUST NEVER reuse `r.Context()` directly after the response has been written, as the Chi server cancels the request context once the connection closes.
- Long-running iterations or pipeline stages MUST explicitly check `ctx.Err()` or `select { case <-ctx.Done(): ... }` before executing subsequent costly operations.
- Database access layer interfaces MUST accept `context.Context` as their first parameter and utilize Chi's request lifecycle to abort dead connections instantly.

## Bad vs Good Implementations
### Timeout Middleware and Downstream Database Execution in Go Chi

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using context.Background() detaches the query from the HTTP request lifecycle. If the client disconnects or times out, the database pool remains saturated. Additionally, using db.Query without context ignores r.Context(), causing orphaned work and connection leaks.
```go
package middleware

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

func LeakProneHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Ignoring request context and launching unmonitored goroutine
		go func() {
			// context.Background() causes query to execute even if client disconnects,
			// holding pool connections hostage under heavy client dropouts.
			_, err := db.ExecContext(context.Background(), "UPDATE user_stats SET visits = visits + 1")
			if err != nil {
				return
			}
		}()

		// ANTI-PATTERN: db.Query does not respect request cancellation
		rows, err := db.Query("SELECT id, name FROM large_table")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()
		w.WriteHeader(http.StatusOK)
	}
}
```

#### Production Standard (Correct)
> **Standard**: Derives a deadline context correctly from r.Context(), passes it downstream via r.WithContext(), uses db.QueryContext to abort immediately upon client termination, and inspects context errors to return appropriate status codes.
```go
package middleware

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

func TimeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx, cancel := context.WithTimeout(r.Context(), timeout)
			defer cancel()

			r = r.WithContext(ctx)
			next.ServeHTTP(w, r)
		})
	}
}

func RobustHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		// Enforce strict downstream context inheritance
		rows, err := db.QueryContext(ctx, "SELECT id, name FROM large_table")
		if err != nil {
			if errors.Is(err, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) {
				// Client disconnected early; abort gracefully without writing to socket
				return
			}
			if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) {
				http.Error(w, "Gateway Timeout", http.StatusGatewayTimeout)
				return
			}
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		defer rows.Close()
		w.WriteHeader(http.StatusOK)
	}
}
```

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 Cancellation & Strict Deadline Propagation

Go Chi Context Cancellation & Strict Deadline Propagation defines an industrial-grade behavioral standard for backend engineering. Enforces strict downstream context propagation, client disconnect detection, and boundary timeouts across Go Chi HTTP middleware and handlers. Prevents orphaned goroutine leaks, uncancelable long-running transactions, and database pool starvation during premature client termination. 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: Discarding r.Context() or spawning background goroutines with context.Background() in HTTP middleware pipelines 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 DriftDiscarding r.Context() or spawning background goroutines with context.Background() in HTTP middleware pipelinesCritical
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

Handlers and middleware MUST ALWAYS pass `r.Context()` to all downstream blocking operations, including SQL queries, gRPC calls, Redis operations, and channel receives.

Handlers and middleware MUST ALWAYS pass `r.Context()` to all downstream blocking operations, including SQL queries, gRPC calls, Redis operations, and channel receives.

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 instantiate `context.Background()` or `context.TODO()` inside HTTP request life cycles unless explicitly detached for an asynchronous background task with dedicated tracing and timeout isolation.

Engineers MUST NOT instantiate `context.Background()` or `context.TODO()` inside HTTP request life cycles unless explicitly detached for an asynchronous background task with dedicated tracing and timeout isolation.

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

Middleware that enforces deadlines MUST derive a child context using `context.WithTimeout(r.Context(), timeout)` or `context.WithDeadline` and pass `r.WithContext(ctx)` to the next handler, always ensuring `cancel()` is deferred.

Middleware that enforces deadlines MUST derive a child context using `context.WithTimeout(r.Context(), timeout)` or `context.WithDeadline` and pass `r.WithContext(ctx)` to the next handler, always ensuring `cancel()` is deferred.

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 tasks spawned from a request MUST NEVER reuse `r.Context()` directly after the response has been written, as the Chi server cancels the request context once the connection closes.

Asynchronous tasks spawned from a request MUST NEVER reuse `r.Context()` directly after the response has been written, as the Chi server cancels the request context once the connection closes.

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

Long-running iterations or pipeline stages MUST explicitly check `ctx.Err()` or `select { case <-ctx.Done()

Long-running iterations or pipeline stages MUST explicitly check `ctx.Err()` or `select { case <-ctx.Done(): ... }` before executing subsequent costly 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

Database access layer interfaces MUST accept `context.Context` as their first parameter and utilize Chi's request lifecycle to abort dead connections instantly.

Database access layer interfaces MUST accept `context.Context` as their first parameter and utilize Chi's request lifecycle to abort dead connections instantly.

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 Cancellation & Strict Deadline Propagation critical for AI coding assistants?

Enforces strict downstream context propagation, client disconnect detection, and boundary timeouts across Go Chi HTTP middleware and handlers. Prevents orphaned goroutine leaks, uncancelable long-running transactions, and database pool starvation during premature client termination. 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 (Discarding r.Context() or spawning background goroutines with context.Background() in HTTP middleware pipelines) 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