This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-v5-middleware-graceful-shutdown-standard

Chi v5 Router Composition, Context Cancellation, and Graceful Shutdown

Enforces deterministic HTTP server lifecycles, sub-router isolation, and context-cancellation propagation in Go Chi v5 microservices. Mandates signal-driven shutdown deadlines with http.ErrServerClosed handling and prevents goroutine or database connection leaks across downstream I/O boundaries.

Prohibited Anti-Pattern: Unbounded HTTP servers lacking SIGTERM shutdown deadlines and ignoring request context cancellation in sub-router handlers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Chi v5 Router Composition, Context Cancellation, and Graceful Shutdown - Enforces deterministic HTTP server lifecycles, sub-router isolation, and context-cancellation propagation in Go Chi v5 microservices. Mandates signal-driven shutdown deadlines with http.ErrServerClosed handling and prevents goroutine or database connection leaks across downstream I/O boundaries.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, **/*server*.go, **/*router*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-v5-middleware-graceful-shutdown-standard"
---

# Chi v5 Router Composition, Context Cancellation, and Graceful Shutdown

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded HTTP servers lacking SIGTERM shutdown deadlines and ignoring request context cancellation in sub-router handlers.

## System Constraints
You are a Principal Go Architect enforcing strict Chi v5 router conventions, middleware isolation, context cancellation handling, and zero-downtime signal-driven graceful shutdown. Reject any code with bare http.ListenAndServe, missing context listening in handlers, or unisolated sub-router middlewares.

## Strict Guidelines
- Services MUST execute http.Server.Shutdown using a distinct shutdown context with a bounded deadline (e.g., 10-30s) upon receiving SIGINT or SIGTERM.
- Engineers MUST ALWAYS filter http.ErrServerClosed when listening on srv.ListenAndServe() to prevent treating routine shutdowns as runtime panics or fatal errors.
- Handlers MUST ALWAYS pass r.Context() to all database queries, external HTTP calls, and asynchronous operations, and actively select on ctx.Done() during long-lived channel waits.
- Engineers MUST use r.Route() with isolated inline sub-routers for path prefixing rather than mutating the parent router with global middleware side-effects.
- Services MUST place chi/middleware.Timeout, chi/middleware.Recoverer, and chi/middleware.RequestID in the correct deterministic order: RequestID -> RealIP -> Logger -> Recoverer -> Timeout.
- Components NEVER execute os.Exit() before srv.Shutdown returns and all deferred resource closures (database connection pools, message broker publishers, telemetry providers) complete.

## Bad vs Good Implementations
### Chi v5 Sub-Routing, Context-Aware Handlers, and Signal Shutdown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example utilizes bare http.ListenAndServe without a signal trap, abruptly severing in-flight connections on SIGTERM. The handler ignores r.Context(), causing long-running database queries and sleep operations to waste CPU and connection pool resources even after the client disconnects.
```go
package main

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

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

func RunServer(db *sql.DB) {
	r := chi.NewRouter()

	// Anti-pattern: Indiscriminate global middleware order and unisolated mounting
	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			next.ServeHTTP(w, r)
		})
	})

	r.Get("/api/v1/orders", func(w http.ResponseWriter, r *http.Request) {
		// Anti-pattern: Ignores request context, causing query leaks if client cancels
		rows, _ := db.Query("SELECT id, amount FROM orders")
		defer rows.Close()
		time.Sleep(5 * time.Second) // Uncancellable blocking operation
		w.Write([]byte("orders"))
	})

	// Anti-pattern: Bare ListenAndServe blocks indefinitely; process termination drops in-flight requests abruptly
	_ = http.ListenAndServe(":8080", r)
}
```

#### Production Standard (Correct)
> **Standard**: The good example configures deterministic timeouts on http.Server, sequences core Chi middlewares safely, mounts sub-routes via r.Route(), propagates r.Context() to database queries, and manages graceful shutdowns using signal.NotifyContext and srv.Shutdown with an isolated deadline.
```go
package main

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

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

func RunServer(ctx context.Context, db *sql.DB) error {
	r := chi.NewRouter()

	// Correct middleware stack ordering
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Timeout(15 * time.Second))

	// Isolated sub-routing
	r.Route("/api/v1", func(api chi.Router) {
		api.Get("/orders", func(w http.ResponseWriter, r *http.Request) {
			reqCtx := r.Context()

			// Propagate context to prevent pool exhaustion on cancellation
			rows, err := db.QueryContext(reqCtx, "SELECT id, amount FROM orders")
			if err != nil {
				if errors.Is(err, context.Canceled) {
					return
				}
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}
			defer rows.Close()

			w.WriteHeader(http.StatusOK)
			_, _ = w.Write([]byte("[]"))
		})
	})

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

	serverCtx, stopServer := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
	defer stopServer()

	serverErr := make(chan error, 1)
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			serverErr <- err
		}
		close(serverErr)
	}()

	select {
	case <-serverCtx.Done():
		slog.Info("shutdown signal received, draining active connections")
	case err := <-serverErr:
		return err
	}

	shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancelShutdown()

	return srv.Shutdown(shutdownCtx)
}
```

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: Chi v5 Router Composition, Context Cancellation, and Graceful Shutdown

Chi v5 Router Composition, Context Cancellation, and Graceful Shutdown defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic HTTP server lifecycles, sub-router isolation, and context-cancellation propagation in Go Chi v5 microservices. Mandates signal-driven shutdown deadlines with http.ErrServerClosed handling and prevents goroutine or database connection leaks across downstream I/O boundaries. 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: Unbounded HTTP servers lacking SIGTERM shutdown deadlines and ignoring request context cancellation in sub-router handlers. 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 DriftUnbounded HTTP servers lacking SIGTERM shutdown deadlines and ignoring request context cancellation in sub-router handlers.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

Services MUST execute http.Server.Shutdown using a distinct shutdown context with a bounded deadline (e.g., 10-30s) upon receiving SIGINT or SIGTERM.

Services MUST execute http.Server.Shutdown using a distinct shutdown context with a bounded deadline (e.g., 10-30s) upon receiving SIGINT or SIGTERM.

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 ALWAYS filter http.ErrServerClosed when listening on srv.ListenAndServe() to prevent treating routine shutdowns as runtime panics or fatal errors.

Engineers MUST ALWAYS filter http.ErrServerClosed when listening on srv.ListenAndServe() to prevent treating routine shutdowns as runtime panics or fatal 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.
3

Handlers MUST ALWAYS pass r.Context() to all database queries, external HTTP calls, and asynchronous operations, and actively select on ctx.Done() during long-lived channel waits.

Handlers MUST ALWAYS pass r.Context() to all database queries, external HTTP calls, and asynchronous operations, and actively select on ctx.Done() during long-lived channel waits.

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

Engineers MUST use r.Route() with isolated inline sub-routers for path prefixing rather than mutating the parent router with global middleware side-effects.

Engineers MUST use r.Route() with isolated inline sub-routers for path prefixing rather than mutating the parent router with global middleware side-effects.

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

Services MUST place chi/middleware.Timeout, chi/middleware.Recoverer, and chi/middleware.RequestID in the correct deterministic order

Services MUST place chi/middleware.Timeout, chi/middleware.Recoverer, and chi/middleware.RequestID in the correct deterministic order: RequestID -> RealIP -> Logger -> Recoverer -> Timeout.

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

Components NEVER execute os.Exit() before srv.Shutdown returns and all deferred resource closures (database connection pools, message broker publishers, telemetry providers) complete.

Components NEVER execute os.Exit() before srv.Shutdown returns and all deferred resource closures (database connection pools, message broker publishers, telemetry providers) complete.

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 Chi v5 Router Composition, Context Cancellation, and Graceful Shutdown critical for AI coding assistants?

Enforces deterministic HTTP server lifecycles, sub-router isolation, and context-cancellation propagation in Go Chi v5 microservices. Mandates signal-driven shutdown deadlines with http.ErrServerClosed handling and prevents goroutine or database connection leaks across downstream I/O boundaries. 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 (Unbounded HTTP servers lacking SIGTERM shutdown deadlines and ignoring request context cancellation in sub-router handlers.) 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

Chi