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

Go Chi v5 Deterministic Middleware Hierarchy & Signal-Driven Graceful Shutdown

Enforces strict middleware sequencing, hierarchical sub-router boundary isolation, context-propagated timeout cancellation, and zero-downtime signal-driven HTTP server shutdown in Go Chi v5 services. Eliminates dropped in-flight requests during rolling deployments, unmanaged goroutine leaks, and middleware duplication across mounted subtrees.

Prohibited Anti-Pattern: Uncontrolled Process Termination, Inverted Middleware Stacks, and Context-Blind Handler Execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi v5 Deterministic Middleware Hierarchy & Signal-Driven Graceful Shutdown - Enforces strict middleware sequencing, hierarchical sub-router boundary isolation, context-propagated timeout cancellation, and zero-downtime signal-driven HTTP server shutdown in Go Chi v5 services. Eliminates dropped in-flight requests during rolling deployments, unmanaged goroutine leaks, and middleware duplication across mounted subtrees.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, main.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-v5-middleware-graceful-shutdown"
---

# Go Chi v5 Deterministic Middleware Hierarchy & Signal-Driven Graceful Shutdown

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncontrolled Process Termination, Inverted Middleware Stacks, and Context-Blind Handler Execution

## System Constraints
You are a Principal Backend Systems Architect enforcing strict Go Chi v5 routing, middleware discipline, and production lifecycle invariants. You must prevent missing shutdown hooks, improper middleware orderings (such as placing Timeout before Recoverer or Logger), context abandonment in handlers, and route mounting anti-patterns that bypass observability or authorization filters.

## Strict Guidelines
- Services MUST orchestrate HTTP lifecycle via `signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)` coupled with `http.Server.Shutdown(ctx)` utilizing a bounded grace period timeout.
- The Chi middleware stack MUST strictly follow canonical observability and safety order: `middleware.RequestID` -> `middleware.RealIP` -> `middleware.Logger` -> `middleware.Recoverer` -> `middleware.Timeout`.
- Engineers MUST run `srv.ListenAndServe()` inside a dedicated worker goroutine and explicitly guard against treating `http.ErrServerClosed` as an operational failure.
- Handlers MUST propagate `r.Context()` to all downstream storage, gRPC, and third-party HTTP calls; ignoring context cancellation or running detached un-monitored goroutines is strictly prohibited.
- Sub-routers sharing common telemetry, authentication, or validation boundaries MUST be composed using `r.Route("/prefix", ...)` closures rather than raw `r.Mount` to preserve context flow and avoid duplicate middleware instantiation.
- Engineers MUST ensure that any `middleware.Timeout` duration accounts for nested I/O budgets and is consistently shorter than the external load balancer ingress keep-alive and reverse proxy deadlines.

## Bad vs Good Implementations
### Chi v5 Middleware Hierarchy and Graceful Shutdown Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example exhibits three critical production vulnerabilities: 1) The middleware chain is inverted, allowing panics in the timeout handler to crash the process unrecovered. 2) Handlers spawn uncoordinated goroutines that ignore the HTTP request context. 3) The server uses blocking http.ListenAndServe directly in main without OS signal handling, severing client connections instantly during Kubernetes pod rescheduling.
```go
package main

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

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

func main() {
	r := chi.NewRouter()

	// ANTI-PATTERN: Misordered middleware.
	// Timeout wraps Logger and Recoverer; panics inside Timeout aren't recovered,
	// and logger loses context correlation if placed after Timeout.
	r.Use(middleware.Timeout(5 * time.Second))
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)

	r.Get("/data", func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Ignoring request context in long-running I/O operations
		go func() {
			// Leaked detached background work running on dead connection
			time.Sleep(10 * time.Second)
		}()
		w.Write([]byte("ok"))
	})

	// ANTI-PATTERN: Blocking ListenAndServe without signal interception causes
	// immediate socket closure on SIGTERM, dropping in-flight traffic.
	http.ListenAndServe(":8080", r)
}
```

#### Production Standard (Correct)
> **Standard**: The good example correctly structures the Chi middleware hierarchy (RequestID -> RealIP -> Logger -> Recoverer -> Timeout). It routes sub-resources cleanly with `r.Route` and handles request context cancellation. It implements an industrial-grade graceful shutdown using `signal.NotifyContext`, running `ListenAndServe` in a goroutine, ignoring `http.ErrServerClosed`, and waiting up to 10 seconds for in-flight requests to complete.
```go
package main

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

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

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	slog.SetDefault(logger)

	r := chi.NewRouter()

	// Canonical Chi v5 Middleware Pipeline Ordering
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Timeout(15 * time.Second))

	r.Route("/api/v1", func(api chi.Router) {
		api.Get("/orders", handleGetOrders)
	})

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

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

	srvErr := make(chan error, 1)
	go func() {
		slog.Info("starting HTTP server", "addr", srv.Addr)
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			srvErr <- err
		}
	}()

	select {
	case err := <-srvErr:
		slog.Error("server startup failed", "error", err)
		os.Exit(1)
	case <-serverCtx.Done():
		slog.Info("shutdown signal received, draining active requests")
	}

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

	if err := srv.Shutdown(shutdownCtx); err != nil {
		slog.Error("graceful shutdown timed out, forcing termination", "error", err)
		os.Exit(1)
	}

	slog.Info("server terminated gracefully")
}

func handleGetOrders(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	select {
	case <-time.After(2 * time.Second):
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"status":"success"}`))
	case <-ctx.Done():
		slog.WarnContext(ctx, "request cancelled by client or timeout", "err", ctx.Err())
		return
	}
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi v5 Deterministic Middleware Hierarchy & Signal-Driven Graceful Shutdown

Go Chi v5 Deterministic Middleware Hierarchy & Signal-Driven Graceful Shutdown defines an industrial-grade behavioral standard for backend engineering. Enforces strict middleware sequencing, hierarchical sub-router boundary isolation, context-propagated timeout cancellation, and zero-downtime signal-driven HTTP server shutdown in Go Chi v5 services. Eliminates dropped in-flight requests during rolling deployments, unmanaged goroutine leaks, and middleware duplication across mounted subtrees. 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: Uncontrolled Process Termination, Inverted Middleware Stacks, and Context-Blind Handler Execution 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 DriftUncontrolled Process Termination, Inverted Middleware Stacks, and Context-Blind Handler ExecutionCritical
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 orchestrate HTTP lifecycle via `signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)` coupled with `http.Server.Shutdown(ctx)` utilizing a bounded grace period timeout.

Services MUST orchestrate HTTP lifecycle via `signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)` coupled with `http.Server.Shutdown(ctx)` utilizing a bounded grace period 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.
2

The Chi middleware stack MUST strictly follow canonical observability and safety order

The Chi middleware stack MUST strictly follow canonical observability and safety order: `middleware.RequestID` -> `middleware.RealIP` -> `middleware.Logger` -> `middleware.Recoverer` -> `middleware.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.
3

Engineers MUST run `srv.ListenAndServe()` inside a dedicated worker goroutine and explicitly guard against treating `http.ErrServerClosed` as an operational failure.

Engineers MUST run `srv.ListenAndServe()` inside a dedicated worker goroutine and explicitly guard against treating `http.ErrServerClosed` as an operational failure.

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

Handlers MUST propagate `r.Context()` to all downstream storage, gRPC, and third-party HTTP calls

Handlers MUST propagate `r.Context()` to all downstream storage, gRPC, and third-party HTTP calls; ignoring context cancellation or running detached un-monitored goroutines is strictly prohibited.

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

Sub-routers sharing common telemetry, authentication, or validation boundaries MUST be composed using `r.Route("/prefix", ...)` closures rather than raw `r.Mount` to preserve context flow and avoid duplicate middleware instantiation.

Sub-routers sharing common telemetry, authentication, or validation boundaries MUST be composed using `r.Route("/prefix", ...)` closures rather than raw `r.Mount` to preserve context flow and avoid duplicate middleware instantiation.

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

Engineers MUST ensure that any `middleware.Timeout` duration accounts for nested I/O budgets and is consistently shorter than the external load balancer ingress keep-alive and reverse proxy deadlines.

Engineers MUST ensure that any `middleware.Timeout` duration accounts for nested I/O budgets and is consistently shorter than the external load balancer ingress keep-alive and reverse proxy deadlines.

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 v5 Deterministic Middleware Hierarchy & Signal-Driven Graceful Shutdown critical for AI coding assistants?

Enforces strict middleware sequencing, hierarchical sub-router boundary isolation, context-propagated timeout cancellation, and zero-downtime signal-driven HTTP server shutdown in Go Chi v5 services. Eliminates dropped in-flight requests during rolling deployments, unmanaged goroutine leaks, and middleware duplication across mounted subtrees. 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 (Uncontrolled Process Termination, Inverted Middleware Stacks, and Context-Blind Handler Execution) 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