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

Go Chi 5 Structured Context Propagation, Request Budgeting, and Graceful Concurrency Drain

Enforces strict context cancellation inheritance, timeout budgeting via Chi middleware, and robust worker drain coordination during rolling deployment OS signals. Prevents orphaned goroutines, detached context anti-patterns, and mid-flight connection resets on SIGTERM.

Prohibited Anti-Pattern: Detaching context with context.Background() in Chi handlers and uncoordinated goroutine execution during SIGTERM shutdowns

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi 5 Structured Context Propagation, Request Budgeting, and Graceful Concurrency Drain - Enforces strict context cancellation inheritance, timeout budgeting via Chi middleware, and robust worker drain coordination during rolling deployment OS signals. Prevents orphaned goroutines, detached context anti-patterns, and mid-flight connection resets on SIGTERM.
globs: **/*.go, cmd/**/*.go, internal/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi5-context-propagation-graceful-drain"
---

# Go Chi 5 Structured Context Propagation, Request Budgeting, and Graceful Concurrency Drain

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detaching context with context.Background() in Chi handlers and uncoordinated goroutine execution during SIGTERM shutdowns

## System Constraints
You are a Principal Go Systems Architect enforcing strict Chi 5 HTTP context propagation, deterministic timeout boundaries, and zero-downtime graceful shutdown patterns. You must reject any code that spawns uncoordinated goroutines, uses detached background contexts inside HTTP request scopes, or fails to coordinate worker pool drains with OS shutdown signals.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` to all downstream operations including database queries, external HTTP/RPC requests, and in-request worker pools.
- Engineers MUST NOT spawn detached goroutines inside HTTP handlers using `context.Background()` or `context.TODO()`. Fire-and-forget tasks MUST be enqueued to a supervised, application-scoped worker pool that binds to the application root shutdown context.
- Code MUST configure `middleware.Timeout` and `middleware.RequestID` as foundational Chi router middlewares to enforce deterministic upper bounds on request lifecycles.
- Services MUST trap `syscall.SIGTERM` and `syscall.SIGINT` using `signal.NotifyContext` and execute `http.Server.Shutdown(drainCtx)` with a bounded teardown context.
- Background worker routines MUST coordinate through `sync.WaitGroup` or `golang.org/x/sync/errgroup` to guarantee clean completion or rollback before process termination.

## Bad vs Good Implementations
### Uncoordinated Async Execution and Leaked Handlers vs. Supervised Worker Drain & Chi Context Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The HTTP handler ignores `r.Context()` during database queries, spawns a detached goroutine that cannot be tracked or drained during pod eviction, lacks request timeout middleware, and the server does not handle OS lifecycle signals.
```go
package main

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

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

func MountRoutes(r *chi.Mux, db *sql.DB) {
	// BAD: Missing timeout middleware; vulnerable to unbounded request execution
	r.Post("/process", func(w http.ResponseWriter, r *http.Request) {
		// BAD: Abandoning request context; DB query will not cancel on client disconnect
		_, err := db.Exec("INSERT INTO events (payload) VALUES ('test')")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// BAD: Spawning orphaned goroutine with context.Background(); leaks during SIGTERM
		go func() {
			time.Sleep(5 * time.Second)
			_, _ = db.Exec("UPDATE events SET status = 'complete'")
		}()

		w.WriteHeader(http.StatusAccepted)
	})
}

func main() {
	r := chi.NewRouter()
	// BAD: Plain ListenAndServe; process abruptly terminates in-flight connections on SIGTERM
	_ = http.ListenAndServe(":8080", r)
}
```

#### Production Standard (Correct)
> **Standard**: Middleware enforces a strict 15s timeout budget; database calls use `db.ExecContext(r.Context(), ...)`; asynchronous tasks are managed through a bounded, coordinated worker pool; and SIGTERM triggers an orderly server drain and worker pool flush.
```go
package main

import (
	"context"
	"database/sql"
	"errors"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

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

type SupervisedWorkerPool struct {
	wg   sync.WaitGroup
	jobs chan func(ctx context.Context)
}

func (p *SupervisedWorkerPool) Enqueue(job func(ctx context.Context)) bool {
	select {
	case p.jobs <- job:
		return true
	default:
		return false
	}
}

func MountRoutes(r chi.Router, db *sql.DB, pool *SupervisedWorkerPool) {
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Timeout(15 * time.Second))

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

		// GOOD: Passing Chi request context with inherited timeout & cancellation
		_, err := db.ExecContext(ctx, "INSERT INTO events (payload) VALUES ($1)", "test")
		if err != nil {
			http.Error(w, err.Error(), http.StatusRequestTimeout)
			return
		}

		// GOOD: Handing off async jobs to monitored drain worker
		ok := pool.Enqueue(func(appCtx context.Context) {
			_, _ = db.ExecContext(appCtx, "UPDATE events SET status = 'complete'")
		})
		if !ok {
			http.Error(w, "worker queue saturated", http.StatusServiceUnavailable)
			return
		}

		w.WriteHeader(http.StatusAccepted)
	})
}

func main() {
	rootCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	pool := &SupervisedWorkerPool{jobs: make(chan func(context.Context), 100)}
	pool.wg.Add(1)
	go func() {
		defer pool.wg.Done()
		for {
			select {
			case <-rootCtx.Done():
				return
			case job := <-pool.jobs:
				job(rootCtx)
			}
		}
	}()

	r := chi.NewRouter()
	MountRoutes(r, nil, pool)

	srv := &http.Server{
		Addr:         ":8080",
		Handler:      r,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 20 * time.Second,
		IdleTimeout:  60 * time.Second,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			panic(err)
		}
	}()

	<-rootCtx.Done()
	drainCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	_ = srv.Shutdown(drainCtx)
	pool.wg.Wait()
}
```

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 5 Structured Context Propagation, Request Budgeting, and Graceful Concurrency Drain

Go Chi 5 Structured Context Propagation, Request Budgeting, and Graceful Concurrency Drain defines an industrial-grade behavioral standard for backend engineering. Enforces strict context cancellation inheritance, timeout budgeting via Chi middleware, and robust worker drain coordination during rolling deployment OS signals. Prevents orphaned goroutines, detached context anti-patterns, and mid-flight connection resets on SIGTERM. 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 with context.Background() in Chi handlers and uncoordinated goroutine execution during SIGTERM shutdowns 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 with context.Background() in Chi handlers and uncoordinated goroutine execution during SIGTERM shutdownsCritical
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()` to all downstream operations including database queries, external HTTP/RPC requests, and in-request worker pools.

Engineers MUST ALWAYS propagate `r.Context()` to all downstream operations including database queries, external HTTP/RPC requests, and in-request worker pools.

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 HTTP handlers using `context.Background()` or `context.TODO()`. Fire-and-forget tasks MUST be enqueued to a supervised, application-scoped worker pool that binds to the application root shutdown context.

Engineers MUST NOT spawn detached goroutines inside HTTP handlers using `context.Background()` or `context.TODO()`. Fire-and-forget tasks MUST be enqueued to a supervised, application-scoped worker pool that binds to the application root shutdown 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

Code MUST configure `middleware.Timeout` and `middleware.RequestID` as foundational Chi router middlewares to enforce deterministic upper bounds on request lifecycles.

Code MUST configure `middleware.Timeout` and `middleware.RequestID` as foundational Chi router middlewares to enforce deterministic upper bounds on request lifecycles.

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

Services MUST trap `syscall.SIGTERM` and `syscall.SIGINT` using `signal.NotifyContext` and execute `http.Server.Shutdown(drainCtx)` with a bounded teardown context.

Services MUST trap `syscall.SIGTERM` and `syscall.SIGINT` using `signal.NotifyContext` and execute `http.Server.Shutdown(drainCtx)` with a bounded teardown 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.
5

Background worker routines MUST coordinate through `sync.WaitGroup` or `golang.org/x/sync/errgroup` to guarantee clean completion or rollback before process termination.

Background worker routines MUST coordinate through `sync.WaitGroup` or `golang.org/x/sync/errgroup` to guarantee clean completion or rollback before process termination.

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 5 Structured Context Propagation, Request Budgeting, and Graceful Concurrency Drain critical for AI coding assistants?

Enforces strict context cancellation inheritance, timeout budgeting via Chi middleware, and robust worker drain coordination during rolling deployment OS signals. Prevents orphaned goroutines, detached context anti-patterns, and mid-flight connection resets on SIGTERM. 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 with context.Background() in Chi handlers and uncoordinated goroutine execution during SIGTERM shutdowns) 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