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

Go Chi v5 HTTP/2 Graceful Stream Drainage & Context Invariants

Enforces deterministic HTTP/2 GOAWAY stream drainage and structured hierarchical context propagation during rolling node terminations. Prevents connection resets (RST_STREAM) and dropped in-flight multiplexed client streams in Go Chi v5 services by synchronizing readiness unpublishing with staged server shutdown deadlines.

Prohibited Anti-Pattern: Immediate http.Server.Shutdown execution and detached request contexts causing abrupt HTTP/2 connection resets.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi v5 HTTP/2 Graceful Stream Drainage & Context Invariants - Enforces deterministic HTTP/2 GOAWAY stream drainage and structured hierarchical context propagation during rolling node terminations. Prevents connection resets (RST_STREAM) and dropped in-flight multiplexed client streams in Go Chi v5 services by synchronizing readiness unpublishing with staged server shutdown deadlines.
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-http2-stream-drainage-lifecycle"
---

# Go Chi v5 HTTP/2 Graceful Stream Drainage & Context Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Immediate http.Server.Shutdown execution and detached request contexts causing abrupt HTTP/2 connection resets.

## System Constraints
You are a Principal Engineer enforcing Go Chi v5 Structured Context-Aware HTTP/2 In-Flight Stream Drainage. Mandate invariants that eliminate client connection drops (RST_STREAM / ERR_HTTP2_PING_FAILED) during zero-downtime rolling node terminations. You must guarantee: 1) Load-balancer readiness detachment precedes server shutdown by at least one health-check cycle, 2) HTTP/2 transport configurations enforce explicit GOAWAY frame drainage windows, 3) Chi HTTP handlers strictly derive child spans and database calls from `r.Context()`, never `context.Background()`, and 4) `http.Server.BaseContext` binds listener lifecycles to structured root contexts.

## Strict Guidelines
- Engineers MUST ALWAYS set `http.Server.BaseContext` to propagate the root cancellation lifecycle to incoming Chi requests.
- Engineers MUST ALWAYS implement a two-stage rolling termination: toggle readiness probes to 503/unhealthy and sleep for external ingress propagation before invoking `server.Shutdown()`.
- Engineers MUST NOT call `context.Background()` or `context.TODO()` inside Chi middleware or route handlers for I/O operations.
- Services MUST configure `golang.org/x/net/http2.Server` or standard `net/http` timeouts (`IdleTimeout`, `ReadHeaderTimeout`) to prevent hanging multiplexed streams during shutdown.
- Services MUST cap the drain context timeout using `context.WithTimeout` to an upper bound matching the maximum downstream SLA plus transport grace.
- Components NEVER call `os.Exit` directly inside signal handlers before `server.Shutdown()` completes its wait group on active HTTP/2 streams.

## Bad vs Good Implementations
### HTTP/2 Graceful Drainage with Chi v5, Readiness Latching, and Context Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The server immediately calls Shutdown without a drain grace period, sending abrupt GOAWAY frames and severing in-flight HTTP/2 streams before upstream load balancers deregister the endpoint. Handlers spawn detached goroutines using context.Background(), losing cancellation signals and connection visibility.
```go
package main

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

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

func main() {
	r := chi.NewRouter()
	r.Get("/data", func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Detaching from r.Context() prevents graceful stream cancellation
		go func() {
			ctx := context.Background()
			_ = processData(ctx)
		}()
		w.WriteHeader(http.StatusOK)
	})

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

	// ANTI-PATTERN: Immediate shutdown on SIGTERM triggers instant RST_STREAM on in-flight HTTP/2 streams
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	_ = srv.Shutdown(context.Background())
	os.Exit(0)
}

func processData(ctx context.Context) error { return nil }
```

#### Production Standard (Correct)
> **Standard**: The implementation decouples shutdown into two phases: first failing readiness checks so upstream load balancers route traffic elsewhere, followed by server.Shutdown with a constrained timeout context. BaseContext passes the root context down, and handlers strictly honor r.Context() to react to GOAWAY stream closures.
```go
package main

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

	"github.com/go-chi/chi/v5"
	"golang.org/x/net/http2"
	"golang.org/x/net/http2/h2c"
)

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

	var isReady atomic.Bool
	isReady.Store(true)

	r := chi.NewRouter()
	r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
		if !isReady.Load() {
			http.Error(w, "Draining", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	r.Get("/api/v1/work", func(w http.ResponseWriter, r *http.Request) {
		// Correct: Handler binds directly to request context
		if err := executeWork(r.Context()); err != nil {
			http.Error(w, err.Error(), http.StatusGatewayTimeout)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	h2Server := &http2.Server{
		IdleTimeout: 120 * time.Second,
	}

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           h2c.NewHandler(r, h2Server),
		ReadHeaderTimeout: 5 * time.Second,
		IdleTimeout:       120 * time.Second,
		BaseContext: func(l net.Listener) context.Context {
			return rootCtx
		},
	}

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

	<-rootCtx.Done()

	// Phase 1: Deregister from ingress traffic
	isReady.Store(false)
	time.Sleep(10 * time.Second) // Match ingress health-check polling interval

	// Phase 2: Drain in-flight HTTP/2 streams within strict deadline
	drainCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
	defer cancel()

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

func executeWork(ctx context.Context) error {
	select {
	case <-time.After(100 * time.Millisecond):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
```

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 v5 HTTP/2 Graceful Stream Drainage & Context Invariants

Go Chi v5 HTTP/2 Graceful Stream Drainage & Context Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic HTTP/2 GOAWAY stream drainage and structured hierarchical context propagation during rolling node terminations. Prevents connection resets (RST_STREAM) and dropped in-flight multiplexed client streams in Go Chi v5 services by synchronizing readiness unpublishing with staged server shutdown deadlines. 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: Immediate http.Server.Shutdown execution and detached request contexts causing abrupt HTTP/2 connection resets. 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 DriftImmediate http.Server.Shutdown execution and detached request contexts causing abrupt HTTP/2 connection resets.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

Engineers MUST ALWAYS set `http.Server.BaseContext` to propagate the root cancellation lifecycle to incoming Chi requests.

Engineers MUST ALWAYS set `http.Server.BaseContext` to propagate the root cancellation lifecycle to incoming Chi requests.

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 implement a two-stage rolling termination

Engineers MUST ALWAYS implement a two-stage rolling termination: toggle readiness probes to 503/unhealthy and sleep for external ingress propagation before invoking `server.Shutdown()`.

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 call `context.Background()` or `context.TODO()` inside Chi middleware or route handlers for I/O operations.

Engineers MUST NOT call `context.Background()` or `context.TODO()` inside Chi middleware or route handlers for I/O operations.

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 configure `golang.org/x/net/http2.Server` or standard `net/http` timeouts (`IdleTimeout`, `ReadHeaderTimeout`) to prevent hanging multiplexed streams during shutdown.

Services MUST configure `golang.org/x/net/http2.Server` or standard `net/http` timeouts (`IdleTimeout`, `ReadHeaderTimeout`) to prevent hanging multiplexed streams during shutdown.

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 cap the drain context timeout using `context.WithTimeout` to an upper bound matching the maximum downstream SLA plus transport grace.

Services MUST cap the drain context timeout using `context.WithTimeout` to an upper bound matching the maximum downstream SLA plus transport grace.

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 call `os.Exit` directly inside signal handlers before `server.Shutdown()` completes its wait group on active HTTP/2 streams.

Components NEVER call `os.Exit` directly inside signal handlers before `server.Shutdown()` completes its wait group on active HTTP/2 streams.

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 HTTP/2 Graceful Stream Drainage & Context Invariants critical for AI coding assistants?

Enforces deterministic HTTP/2 GOAWAY stream drainage and structured hierarchical context propagation during rolling node terminations. Prevents connection resets (RST_STREAM) and dropped in-flight multiplexed client streams in Go Chi v5 services by synchronizing readiness unpublishing with staged server shutdown deadlines. 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 (Immediate http.Server.Shutdown execution and detached request contexts causing abrupt HTTP/2 connection resets.) 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