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

Go Chi Deterministic Graceful Shutdown & In-Flight Stream Drain Invariant

Enforces deterministic graceful shutdown semantics for Go Chi services handling HTTP/1.1 and HTTP/2 multiplexed streams. Prevents dropped client streams, unbuffered transport frame truncations, and orphan goroutines by unifying BaseContext cascading, explicit stream cancellation listeners, and synchronized drain timeouts.

Prohibited Anti-Pattern: Uncoordinated http.Server.Shutdown with Orphan Streaming Goroutines and Unbound HTTP/2 Truncation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Deterministic Graceful Shutdown & In-Flight Stream Drain Invariant - Enforces deterministic graceful shutdown semantics for Go Chi services handling HTTP/1.1 and HTTP/2 multiplexed streams. Prevents dropped client streams, unbuffered transport frame truncations, and orphan goroutines by unifying BaseContext cascading, explicit stream cancellation listeners, and synchronized drain timeouts.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-graceful-shutdown-stream-drain"
---

# Go Chi Deterministic Graceful Shutdown & In-Flight Stream Drain Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated http.Server.Shutdown with Orphan Streaming Goroutines and Unbound HTTP/2 Truncation

## System Constraints
You are a Principal Go Architect enforcing deterministic lifecycle and graceful shutdown invariants in Go Chi services. You must reject any HTTP server configuration that uses uncoordinated background goroutines, ignores server.BaseContext propagation, terminates streaming handlers without checking r.Context().Done(), or calls os.Exit() without draining transport buffers.

## Strict Guidelines
- Engineers MUST ALWAYS initialize http.Server with BaseContext mapped to an application root context derived from signal.NotifyContext.
- Engineers MUST ALWAYS monitor r.Context().Done() inside long-running Chi handlers (SSE, WebSockets, chunked streams) and release associated resources immediately.
- Engineers MUST NOT spawn detached, un-tracked goroutines (go func()) within Chi route handlers without binding them to an errgroup.Group or context-aware worker pool.
- Services MUST execute server.Shutdown(drainCtx) with an independent drain timeout, distinct from the root signal context, to allow active in-flight multiplexed streams to conclude.
- Streaming endpoints MUST verify transport flush capabilities via http.Flusher and emit explicit termination trailers or control events prior to exiting upon context cancellation.

## Bad vs Good Implementations
### Naive Shutdown with Leaked Streaming Goroutine vs Structured BaseContext Drain

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The server omits BaseContext configuration, allowing streaming handlers to continue running indefinitely when the server stops accepting new connections. srv.Shutdown(nil) triggers a panic or immediate socket tear-down without flushing HTTP/2 frames, leaking goroutines and corrupting client connections.
```go
package main

import (
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

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

func main() {
	r := chi.NewRouter()
	// ANTI-PATTERN: Detached background worker and unhandled r.Context()
	r.Get("/events", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream")
		for {
			// Leaks goroutine when client or server aborts without base context wiring
			fmt.Fprintf(w, "data: %s\n\n", time.Now().Format(time.RFC3339))
			time.Sleep(1 * time.Second)
		}
	})

	srv := &http.Server{Addr: ":8080", Handler: r}
	go srv.ListenAndServe()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
	<-stop

	// ANTI-PATTERN: Abrupt shutdown with zero-wait context, truncating streams
	srv.Shutdown(nil)
}
```

#### Production Standard (Correct)
> **Standard**: The server sets BaseContext to tie all inbound connection lifetimes to rootCtx. The streaming endpoint selects on r.Context().Done(), flushes a termination frame using http.Flusher, and exits cleanly. The shutdown procedure allocates a bounded 10-second drain context ensuring in-flight streams terminate deterministically.
```go
package main

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

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

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

	r := chi.NewRouter()
	r.Get("/events", func(w http.ResponseWriter, r *http.Request) {
		flusher, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")

		ticker := time.NewTicker(1 * time.Second)
		defer ticker.Stop()

		ctx := r.Context()
		for {
			select {
			case <-ctx.Done():
				// INVARIANT: Drain and flush before exiting handler
				fmt.Fprintf(w, "event: close\ndata: server shutdown\n\n")
				flusher.Flush()
				return
			case t := <-ticker.C:
				fmt.Fprintf(w, "data: %s\n\n", t.Format(time.RFC3339))
				flusher.Flush()
			}
		}
	})

	srv := &http.Server{
		Addr:    ":8080",
		Handler: r,
		BaseContext: func(_ net.Listener) context.Context {
			return rootCtx
		},
	}

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

	select {
	case <-rootCtx.Done():
	case err := <-serverErr:
		os.Exit(1)
	}

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

	if err := srv.Shutdown(drainCtx); err != nil {
		srv.Close()
	}
}
```

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 Deterministic Graceful Shutdown & In-Flight Stream Drain Invariant

Go Chi Deterministic Graceful Shutdown & In-Flight Stream Drain Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic graceful shutdown semantics for Go Chi services handling HTTP/1.1 and HTTP/2 multiplexed streams. Prevents dropped client streams, unbuffered transport frame truncations, and orphan goroutines by unifying BaseContext cascading, explicit stream cancellation listeners, and synchronized drain timeouts. 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: Uncoordinated http.Server.Shutdown with Orphan Streaming Goroutines and Unbound HTTP/2 Truncation 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 DriftUncoordinated http.Server.Shutdown with Orphan Streaming Goroutines and Unbound HTTP/2 TruncationCritical
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 initialize http.Server with BaseContext mapped to an application root context derived from signal.NotifyContext.

Engineers MUST ALWAYS initialize http.Server with BaseContext mapped to an application root context derived from signal.NotifyContext.

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 monitor r.Context().Done() inside long-running Chi handlers (SSE, WebSockets, chunked streams) and release associated resources immediately.

Engineers MUST ALWAYS monitor r.Context().Done() inside long-running Chi handlers (SSE, WebSockets, chunked streams) and release associated resources immediately.

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 NOT spawn detached, un-tracked goroutines (go func()) within Chi route handlers without binding them to an errgroup.Group or context-aware worker pool.

Engineers MUST NOT spawn detached, un-tracked goroutines (go func()) within Chi route handlers without binding them to an errgroup.Group or context-aware worker pool.

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 execute server.Shutdown(drainCtx) with an independent drain timeout, distinct from the root signal context, to allow active in-flight multiplexed streams to conclude.

Services MUST execute server.Shutdown(drainCtx) with an independent drain timeout, distinct from the root signal context, to allow active in-flight multiplexed streams to conclude.

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

Streaming endpoints MUST verify transport flush capabilities via http.Flusher and emit explicit termination trailers or control events prior to exiting upon context cancellation.

Streaming endpoints MUST verify transport flush capabilities via http.Flusher and emit explicit termination trailers or control events prior to exiting upon context cancellation.

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 Deterministic Graceful Shutdown & In-Flight Stream Drain Invariant critical for AI coding assistants?

Enforces deterministic graceful shutdown semantics for Go Chi services handling HTTP/1.1 and HTTP/2 multiplexed streams. Prevents dropped client streams, unbuffered transport frame truncations, and orphan goroutines by unifying BaseContext cascading, explicit stream cancellation listeners, and synchronized drain timeouts. 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 (Uncoordinated http.Server.Shutdown with Orphan Streaming Goroutines and Unbound HTTP/2 Truncation) 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