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

Chi v5 Context-Aware Middleware Chaining, Safe Route Mounting, and Signal-Driven Graceful Shutdown

Enforces deterministic Chi v5 middleware execution order, strict request context propagation to prevent zombie goroutines, safe sub-router mounting, and non-blocking signal-driven HTTP server shutdown. Guarantees that in-flight requests cleanly drain during deployments without data corruption or abrupt socket drops.

Prohibited Anti-Pattern: Unbounded Context Execution, Hard Process Halts, and Leaked In-Flight Connections in Chi Web Services

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Chi v5 Context-Aware Middleware Chaining, Safe Route Mounting, and Signal-Driven Graceful Shutdown - Enforces deterministic Chi v5 middleware execution order, strict request context propagation to prevent zombie goroutines, safe sub-router mounting, and non-blocking signal-driven HTTP server shutdown. Guarantees that in-flight requests cleanly drain during deployments without data corruption or abrupt socket drops.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, **/*server*.go, **/*router*.go, **/*handler*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-middleware-routing-graceful-shutdown"
---

# Chi v5 Context-Aware Middleware Chaining, Safe Route Mounting, and Signal-Driven Graceful Shutdown

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Context Execution, Hard Process Halts, and Leaked In-Flight Connections in Chi Web Services

## System Constraints
You are a Principal Software Architect enforcing zero-downtime, memory-safe, and context-bound Go HTTP services using go-chi/chi/v5. You ensure every route chain, sub-router mounting, and server lifecycle complies with production reliability standards.

## Strict Guidelines
- Engineers MUST ALWAYS sequence core Chi middleware in this exact order: `middleware.RequestID`, `middleware.RealIP`, `middleware.Logger`, `middleware.Recoverer`, and bounded `middleware.Timeout` before mounting business handlers.
- Engineers MUST ALWAYS run `http.Server.ListenAndServe()` inside an asynchronous goroutine and handle errors by checking `!errors.Is(err, http.ErrServerClosed)` before logging fatal failures.
- Engineers MUST ALWAYS capture termination signals (`os.Interrupt`, `syscall.SIGTERM`) using `signal.NotifyContext` and execute `server.Shutdown(ctx)` with a discrete, bounded drain context timeout (e.g., 10-30 seconds).
- Engineers MUST NEVER use `r.Mount()` with child routers that re-declare overlapping global middleware or strip trailing slashes inconsistently; prefer inline routing with `r.Route()` to preserve middleware inheritance and context trees.
- Handlers MUST ALWAYS pass `r.Context()` to all database queries, downstream RPC calls, and queue operations; creating unlinked background contexts (`context.Background()`) inside handlers is strictly forbidden.
- Services MUST NEVER invoke `os.Exit()` or `log.Fatal()` directly upon signal capture; the server MUST wait for `server.Shutdown()` and any worker sync groups to return before allowing the main routine to exit.
- Code SHOULD define explicit `ReadHeaderTimeout`, `ReadTimeout`, `WriteTimeout`, and `IdleTimeout` on `http.Server` instances to prevent Slowloris resource exhaustion attacks.

## Bad vs Good Implementations
### Anti-Pattern: Naive Chi Server, Abrupt Exit, and Ignored Request Contexts

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The server sets no timeouts on `http.Server`, leaving it vulnerable to slowloris attacks. It omits critical middleware (`Recoverer`, `RequestID`), discards `r.Context()` in favor of `context.Background()` causing database leaks when clients disconnect, and provides no graceful shutdown mechanism when terminated.
```go
package main

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

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

func main() {
	r := chi.NewRouter()
	// BAD: Missing standard observability/recovery middleware chain
	r.Get("/orders/{id}", func(w http.ResponseWriter, r *http.Request) {
		// BAD: Discarding r.Context() leaves queries hanging after client disconnect
		ctx := context.Background()
		var db *sql.DB // assume initialized
		_, err := db.ExecContext(ctx, "UPDATE orders SET viewed_at = NOW() WHERE id = $1", chi.URLParam(r, "id"))
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	// BAD: Default http.Server has no timeouts (vulnerable to Slowloris)
	// BAD: log.Fatal on ListenAndServe terminates process immediately on any signal
	log.Fatal(http.ListenAndServe(":8080", r))
}
```

#### Production Standard (Correct)
> **Standard**: Configures bounded timeouts on `http.Server`, utilizes Chi's canonical middleware sequence, encapsulates sub-routes via `r.Route()`, propagates `r.Context()` to the persistence layer, and uses `signal.NotifyContext()` coupled with `srv.Shutdown()` to cleanly drain connections within a 15-second grace period.
```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 buildRouter(db *sql.DB) chi.Router {
	r := chi.NewRouter()

	// Standard production middleware stack
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.Timeout(30 * time.Second))

	r.Route("/orders", func(ordersRouter chi.Router) {
		ordersRouter.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
			id := chi.URLParam(r, "id")
			// Propagate the request-scoped context with cancellation/timeout
			_, err := db.ExecContext(r.Context(), "UPDATE orders SET viewed_at = NOW() WHERE id = $1", id)
			if err != nil {
				if errors.Is(err, context.Canceled) {
					return // Client disconnected, abort without error log spam
				}
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
				return
			}
			w.WriteHeader(http.StatusOK)
		})
	})

	return r
}

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	var db *sql.DB // Assume connected

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           buildRouter(db),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      35 * time.Second,
		IdleTimeout:       120 * time.Second,
	}

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

	go func() {
		logger.Info("starting server", "addr", srv.Addr)
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			logger.Error("listen and serve failed", "error", err)
			stopServer()
		}
	}()

	<-serverCtx.Done()
	logger.Info("shutdown signal received; draining in-flight requests")

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

	if err := srv.Shutdown(shutdownCtx); err != nil {
		logger.Error("graceful shutdown failed, forcing close", "error", err)
		_ = srv.Close()
	}

	logger.Info("server terminated gracefully")
}
```

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 Context-Aware Middleware Chaining, Safe Route Mounting, and Signal-Driven Graceful Shutdown

Chi v5 Context-Aware Middleware Chaining, Safe Route Mounting, and Signal-Driven Graceful Shutdown defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic Chi v5 middleware execution order, strict request context propagation to prevent zombie goroutines, safe sub-router mounting, and non-blocking signal-driven HTTP server shutdown. Guarantees that in-flight requests cleanly drain during deployments without data corruption or abrupt socket drops. 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 Context Execution, Hard Process Halts, and Leaked In-Flight Connections in Chi Web Services 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 Context Execution, Hard Process Halts, and Leaked In-Flight Connections in Chi Web ServicesCritical
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 sequence core Chi middleware in this exact order

Engineers MUST ALWAYS sequence core Chi middleware in this exact order: `middleware.RequestID`, `middleware.RealIP`, `middleware.Logger`, `middleware.Recoverer`, and bounded `middleware.Timeout` before mounting business handlers.

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 run `http.Server.ListenAndServe()` inside an asynchronous goroutine and handle errors by checking `!errors.Is(err, http.ErrServerClosed)` before logging fatal failures.

Engineers MUST ALWAYS run `http.Server.ListenAndServe()` inside an asynchronous goroutine and handle errors by checking `!errors.Is(err, http.ErrServerClosed)` before logging fatal failures.

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 ALWAYS capture termination signals (`os.Interrupt`, `syscall.SIGTERM`) using `signal.NotifyContext` and execute `server.Shutdown(ctx)` with a discrete, bounded drain context timeout (e.g., 10-30 seconds).

Engineers MUST ALWAYS capture termination signals (`os.Interrupt`, `syscall.SIGTERM`) using `signal.NotifyContext` and execute `server.Shutdown(ctx)` with a discrete, bounded drain context timeout (e.g., 10-30 seconds).

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 NEVER use `r.Mount()` with child routers that re-declare overlapping global middleware or strip trailing slashes inconsistently

Engineers MUST NEVER use `r.Mount()` with child routers that re-declare overlapping global middleware or strip trailing slashes inconsistently; prefer inline routing with `r.Route()` to preserve middleware inheritance and context trees.

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

Handlers MUST ALWAYS pass `r.Context()` to all database queries, downstream RPC calls, and queue operations

Handlers MUST ALWAYS pass `r.Context()` to all database queries, downstream RPC calls, and queue operations; creating unlinked background contexts (`context.Background()`) inside handlers is strictly forbidden.

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 NEVER invoke `os.Exit()` or `log.Fatal()` directly upon signal capture

Services MUST NEVER invoke `os.Exit()` or `log.Fatal()` directly upon signal capture; the server MUST wait for `server.Shutdown()` and any worker sync groups to return before allowing the main routine to exit.

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.
7

Code SHOULD define explicit `ReadHeaderTimeout`, `ReadTimeout`, `WriteTimeout`, and `IdleTimeout` on `http.Server` instances to prevent Slowloris resource exhaustion attacks.

Code SHOULD define explicit `ReadHeaderTimeout`, `ReadTimeout`, `WriteTimeout`, and `IdleTimeout` on `http.Server` instances to prevent Slowloris resource exhaustion attacks.

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 Context-Aware Middleware Chaining, Safe Route Mounting, and Signal-Driven Graceful Shutdown critical for AI coding assistants?

Enforces deterministic Chi v5 middleware execution order, strict request context propagation to prevent zombie goroutines, safe sub-router mounting, and non-blocking signal-driven HTTP server shutdown. Guarantees that in-flight requests cleanly drain during deployments without data corruption or abrupt socket drops. 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 Context Execution, Hard Process Halts, and Leaked In-Flight Connections in Chi Web Services) 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