This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-context-aware-inflight-request-draining

Deterministic Request Draining and Bounded Context Propagation in Go Chi

Enforces bounded lifecycle fencing and strict context propagation across Go Chi middleware pipelines during rolling pod terminations. Guarantees in-flight HTTP requests complete within a bounded grace period while rejecting ingress traffic and preventing uncoordinated goroutine abandonment during SIGTERM events.

Prohibited Anti-Pattern: Hard Server Teardown and Unbounded Detached Goroutines Causing Dropped Edge Connections During Rolling Updates

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Request Draining and Bounded Context Propagation in Go Chi - Enforces bounded lifecycle fencing and strict context propagation across Go Chi middleware pipelines during rolling pod terminations. Guarantees in-flight HTTP requests complete within a bounded grace period while rejecting ingress traffic and preventing uncoordinated goroutine abandonment during SIGTERM events.
globs: cmd/**/*.go, internal/**/*.go, pkg/server/**/*.go, server.go, main.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-aware-inflight-request-draining"
---

# Deterministic Request Draining and Bounded Context Propagation in Go Chi

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Hard Server Teardown and Unbounded Detached Goroutines Causing Dropped Edge Connections During Rolling Updates

## System Constraints
You are a Principal Backend Systems Architect enforcing absolute zero-downtime rolling deployment invariants for Go Chi services. You must reject abrupt server closes, blind goroutine spawns without context boundaries, uncoordinated SIGTERM handling, and missed heartbeat/readiness flips before the draining sequence.

## Strict Guidelines
- Services MUST capture syscall.SIGTERM and syscall.SIGINT using signal.NotifyContext to initiate graceful HTTP draining via http.Server.Shutdown.
- Engineers MUST NOT call http.Server.Close() during normal lifecycle termination, as it forcibly drops active TCP sockets without allowing middleware pipelines to flush.
- Handlers MUST derive all downstream operations (database queries, network I/O, cache requests) strictly from http.Request.Context().
- Engineers MUST NEVER launch raw background goroutines inside Chi handlers that inherit http.Request.Context() without passing context.WithoutCancel or tracking them via sync.WaitGroup / errgroup.
- Readiness probe endpoints MUST switch to an unhealthy status (HTTP 503) immediately upon SIGTERM receipt and incorporate a pre-stop delay before invoking http.Server.Shutdown to allow service mesh / ingress routing tables to converge.
- Chi middleware stacks MUST NOT swallow or overwrite ctx.Err() or parent cancellation signals during request processing.

## Bad vs Good Implementations
### Graceful Draining with Readiness Probe Deprecation vs Abrupt Server Closure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling srv.Close() drops all active connections instantly without waiting for in-flight requests to complete. Ingress controllers continue routing traffic for several seconds after SIGTERM, causing 502 errors. The spawned goroutine leaks or panics on cancelled request context.
```go
package main

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

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

func main() {
	r := chi.NewRouter()
	r.Get("/order", func(w http.ResponseWriter, r *http.Request) {
		// Flaw 1: Spawning detached goroutine bound to request context
		go func() {
			time.Sleep(2 * time.Second)
			// If request finishes, r.Context() cancels, abandoning write
			doAsyncLog(r.Context())
		}()
		w.WriteHeader(http.StatusOK)
	})

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

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c

	// Flaw 2: Abruptly drops all active TCP connections
	// Flaw 3: Zero ingress deregistration wait time; produces edge 502s
	srv.Close()
}

func doAsyncLog(ctx context.Context) {}
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic two-phase draining: flips readiness probe to fail Kubernetes health checks and delays to allow ingress endpoints to sync before calling srv.Shutdown() with a bounded 15-second context timeout.
```go
package main

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

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

type LifecycleState struct {
	isDraining atomic.Bool
}

func main() {
	state := &LifecycleState{}
	r := chi.NewRouter()

	// Readiness probe reflects pod draining state
	r.Get("/healthz/ready", func(w http.ResponseWriter, r *http.Request) {
		if state.isDraining.Load() {
			http.Error(w, "Service Draining", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	r.Post("/order", func(w http.ResponseWriter, r *http.Request) {
		// Invariant: Pass request context to all I/O bounded operations
		ctx := r.Context()
		if err := processOrder(ctx); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusAccepted)
	})

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

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

	shutdownCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
	defer stop()

	select {
	case err := <-serverErrors:
		panic(err)
	case <-shutdownCtx.Done():
		// Step 1: Flip readiness flag to trigger ingress deregistration
		state.isDraining.Store(true)
		time.Sleep(5 * time.Second) // Ingress convergence window

		// Step 2: Gracefully shutdown HTTP server with bounded deadline
		drainCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
		defer cancel()

		if err := srv.Shutdown(drainCtx); err != nil {
			_ = srv.Close() // Force close if bounded timeout exceeded
		}
	}
}

func processOrder(ctx context.Context) error {
	select {
	case <-time.After(50 * 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: Deterministic Request Draining and Bounded Context Propagation in Go Chi

Deterministic Request Draining and Bounded Context Propagation in Go Chi defines an industrial-grade behavioral standard for backend engineering. Enforces bounded lifecycle fencing and strict context propagation across Go Chi middleware pipelines during rolling pod terminations. Guarantees in-flight HTTP requests complete within a bounded grace period while rejecting ingress traffic and preventing uncoordinated goroutine abandonment during SIGTERM events. 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: Hard Server Teardown and Unbounded Detached Goroutines Causing Dropped Edge Connections During Rolling Updates 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 DriftHard Server Teardown and Unbounded Detached Goroutines Causing Dropped Edge Connections During Rolling UpdatesCritical
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 capture syscall.SIGTERM and syscall.SIGINT using signal.NotifyContext to initiate graceful HTTP draining via http.Server.Shutdown.

Services MUST capture syscall.SIGTERM and syscall.SIGINT using signal.NotifyContext to initiate graceful HTTP draining via http.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.
2

Engineers MUST NOT call http.Server.Close() during normal lifecycle termination, as it forcibly drops active TCP sockets without allowing middleware pipelines to flush.

Engineers MUST NOT call http.Server.Close() during normal lifecycle termination, as it forcibly drops active TCP sockets without allowing middleware pipelines to flush.

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 derive all downstream operations (database queries, network I/O, cache requests) strictly from http.Request.Context().

Handlers MUST derive all downstream operations (database queries, network I/O, cache requests) strictly from http.Request.Context().

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 launch raw background goroutines inside Chi handlers that inherit http.Request.Context() without passing context.WithoutCancel or tracking them via sync.WaitGroup / errgroup.

Engineers MUST NEVER launch raw background goroutines inside Chi handlers that inherit http.Request.Context() without passing context.WithoutCancel or tracking them via sync.WaitGroup / errgroup.

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

Readiness probe endpoints MUST switch to an unhealthy status (HTTP 503) immediately upon SIGTERM receipt and incorporate a pre-stop delay before invoking http.Server.Shutdown to allow service mesh / ingress routing tables to converge.

Readiness probe endpoints MUST switch to an unhealthy status (HTTP 503) immediately upon SIGTERM receipt and incorporate a pre-stop delay before invoking http.Server.Shutdown to allow service mesh / ingress routing tables to converge.

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

Chi middleware stacks MUST NOT swallow or overwrite ctx.Err() or parent cancellation signals during request processing.

Chi middleware stacks MUST NOT swallow or overwrite ctx.Err() or parent cancellation signals during request processing.

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 Deterministic Request Draining and Bounded Context Propagation in Go Chi critical for AI coding assistants?

Enforces bounded lifecycle fencing and strict context propagation across Go Chi middleware pipelines during rolling pod terminations. Guarantees in-flight HTTP requests complete within a bounded grace period while rejecting ingress traffic and preventing uncoordinated goroutine abandonment during SIGTERM events. 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 (Hard Server Teardown and Unbounded Detached Goroutines Causing Dropped Edge Connections During Rolling Updates) 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

Deterministic