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 Context Deadline Propagation and Client Abort Sentinel Guardrail

Mandates the strict propagation of Chi HTTP request contexts (`r.Context()`) across database drivers, cache layers, and fan-out worker goroutines. Prevents thread pool exhaustion, unmonitored orphan executions, and phantom database transactions caused by client dropouts.

Prohibited Anti-Pattern: Discarding request contexts in handlers or detaching goroutines, leading to orphaned database workloads and connection pool starvation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Deadline Propagation and Client Abort Sentinel Guardrail - Mandates the strict propagation of Chi HTTP request contexts (`r.Context()`) across database drivers, cache layers, and fan-out worker goroutines. Prevents thread pool exhaustion, unmonitored orphan executions, and phantom database transactions caused by client dropouts.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, **/*_handler.go, **/*_router.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 Context Deadline Propagation and Client Abort Sentinel Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Discarding request contexts in handlers or detaching goroutines, leading to orphaned database workloads and connection pool starvation.

## System Constraints
You are a Principal Software Architect enforcing production-grade Go concurrency and Chi HTTP router standards. Your primary objective is to eliminate dead resource leaks by guaranteeing that every HTTP request context cancellation or deadline is propagated down through IO operations, worker fan-outs, and database drivers. Reject any code creating unattached goroutines, discarding `r.Context()`, or using `context.Background()` within request lifecycles without explicit decoupled timeout bounds.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` from Chi routing handlers down to all I/O boundaries (SQL, pgx, Redis, external HTTP clients).
- Engineers MUST NOT use `context.Background()` or `context.TODO()` inside HTTP handler scopes or child execution paths.
- Engineers MUST check for `errors.Is(err, context.Canceled)` and `errors.Is(err, context.DeadlineExceeded)` and handle them as clean client abort sentinels rather than 500 Internal Server Errors.
- Worker pools and fan-out operations invoked within an HTTP request MUST select on `ctx.Done()` alongside worker channel operations to abort immediately when the client disconnects.
- Asynchronous background tasks that intentionally outlive the request MUST use `context.WithoutCancel(r.Context())` combined with an explicit, bounded `context.WithTimeout()`, and NEVER an unbounded `context.Background()`.
- Services MUST ensure database transactions (e.g., `tx, err := db.BeginTx(ctx, opts)`) use the request context to guarantee immediate rollback on client connection drops.

## Bad vs Good Implementations
### Chi Request Context Propagation with SQL and Worker Pool Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler discards `r.Context()`, using `context.Background()` for the query. If the client disconnects or times out, the database query continues running, starving connection pool slots. Additionally, an unbounded goroutine is fired without cancellation context or panic safety.
```go
package handlers

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

type OrderHandler struct {
	DB *sql.DB
}

func (h *OrderHandler) ProcessOrder(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: Discarding r.Context() and using background context for DB operations
	row := h.DB.QueryRowContext(context.Background(), "SELECT id, total FROM orders WHERE id = $1", 123)
	
	var id int
	var total float64
	if err := row.Scan(&id, &total); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// ANTI-PATTERN: Fire-and-forget goroutine leaking execution if client disconnects
	go func() {
		h.DB.Exec("UPDATE analytics SET processed_count = processed_count + 1")
	}()

	w.WriteHeader(http.StatusOK)
}
```

#### Production Standard (Correct)
> **Standard**: The handler strictly binds all database access to `r.Context()`. Client cancellations abort the SQL query immediately. Disconnections (`context.Canceled`) avoid false 500 alerts, and asynchronous work intentionally outliving the request uses `context.WithoutCancel` wrapped in a deterministic 5-second deadline.
```go
package handlers

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

type OrderHandler struct {
	DB     *sql.DB
	Logger *slog.Logger
}

func (h *OrderHandler) ProcessOrder(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	var id int
	var total float64
	err := h.DB.QueryRowContext(ctx, "SELECT id, total FROM orders WHERE id = $1", 123).Scan(&id, &total)
	if err != nil {
		if errors.Is(err, context.Canceled) {
			// Client disconnected early; abort cleanly without 500 noise
			h.Logger.InfoContext(ctx, "client aborted request before completion")
			return
		}
		if errors.Is(err, context.DeadlineExceeded) {
			http.Error(w, "request gateway timeout", http.StatusGatewayTimeout)
			return
		}
		h.Logger.ErrorContext(ctx, "database query failed", "error", err)
		http.Error(w, "internal server error", http.StatusInternalServerError)
		return
	}

	// Decoupled asynchronous audit task with bounded lifetime (Go 1.21+)
	bgCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
	go func(auditCtx context.Context) {
		defer cancel()
		if _, execErr := h.DB.ExecContext(auditCtx, "UPDATE analytics SET processed_count = processed_count + 1"); execErr != nil {
			h.Logger.ErrorContext(auditCtx, "async audit update failed", "error", execErr)
		}
	}(bgCtx)

	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 Deadline Propagation and Client Abort Sentinel Guardrail

Go Chi Context Deadline Propagation and Client Abort Sentinel Guardrail defines an industrial-grade behavioral standard for backend engineering. Mandates the strict propagation of Chi HTTP request contexts (`r.Context()`) across database drivers, cache layers, and fan-out worker goroutines. Prevents thread pool exhaustion, unmonitored orphan executions, and phantom database transactions caused by client dropouts. 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 request contexts in handlers or detaching goroutines, leading to orphaned database workloads and connection pool starvation. 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 request contexts in handlers or detaching goroutines, leading to orphaned database workloads and connection pool starvation.Critical
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 propagate `r.Context()` from Chi routing handlers down to all I/O boundaries (SQL, pgx, Redis, external HTTP clients).

Engineers MUST ALWAYS propagate `r.Context()` from Chi routing handlers down to all I/O boundaries (SQL, pgx, Redis, external HTTP clients).

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 use `context.Background()` or `context.TODO()` inside HTTP handler scopes or child execution paths.

Engineers MUST NOT use `context.Background()` or `context.TODO()` inside HTTP handler scopes or child execution paths.

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 check for `errors.Is(err, context.Canceled)` and `errors.Is(err, context.DeadlineExceeded)` and handle them as clean client abort sentinels rather than 500 Internal Server Errors.

Engineers MUST check for `errors.Is(err, context.Canceled)` and `errors.Is(err, context.DeadlineExceeded)` and handle them as clean client abort sentinels rather than 500 Internal Server Errors.

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

Worker pools and fan-out operations invoked within an HTTP request MUST select on `ctx.Done()` alongside worker channel operations to abort immediately when the client disconnects.

Worker pools and fan-out operations invoked within an HTTP request MUST select on `ctx.Done()` alongside worker channel operations to abort immediately when the client disconnects.

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

Asynchronous background tasks that intentionally outlive the request MUST use `context.WithoutCancel(r.Context())` combined with an explicit, bounded `context.WithTimeout()`, and NEVER an unbounded `context.Background()`.

Asynchronous background tasks that intentionally outlive the request MUST use `context.WithoutCancel(r.Context())` combined with an explicit, bounded `context.WithTimeout()`, and NEVER an unbounded `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.
6

Services MUST ensure database transactions (e.g., `tx, err

Services MUST ensure database transactions (e.g., `tx, err := db.BeginTx(ctx, opts)`) use the request context to guarantee immediate rollback on client connection drops.

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 Client Abort Sentinel Guardrail critical for AI coding assistants?

Mandates the strict propagation of Chi HTTP request contexts (`r.Context()`) across database drivers, cache layers, and fan-out worker goroutines. Prevents thread pool exhaustion, unmonitored orphan executions, and phantom database transactions caused by client dropouts. 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 request contexts in handlers or detaching goroutines, leading to orphaned database workloads and connection pool starvation.) 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