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

Go Chi v5 Deterministic HTTP/3 QUIC Dual-Stack Graceful Draining Standard

Enforces deterministic graceful shutdown orchestration for dual-stack HTTP/1.1+HTTP/2 (TCP) and HTTP/3 (QUIC/UDP) Chi v5 microservices. Mandates emission of QUIC GOAWAY frames and closure of early listeners while orchestrating bounded bidirectional stream completion to prevent dropped in-flight UDP RPCs during zero-downtime rolling deployments.

Prohibited Anti-Pattern: Hard Socket Termination of UDP Listeners Dropping In-Flight QUIC Streams During Container SIGTERM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi v5 Deterministic HTTP/3 QUIC Dual-Stack Graceful Draining Standard - Enforces deterministic graceful shutdown orchestration for dual-stack HTTP/1.1+HTTP/2 (TCP) and HTTP/3 (QUIC/UDP) Chi v5 microservices. Mandates emission of QUIC GOAWAY frames and closure of early listeners while orchestrating bounded bidirectional stream completion to prevent dropped in-flight UDP RPCs during zero-downtime rolling deployments.
globs: cmd/**/*.go, internal/server/**/*.go, pkg/transport/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-quic-graceful-draining"
---

# Go Chi v5 Deterministic HTTP/3 QUIC Dual-Stack Graceful Draining Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Hard Socket Termination of UDP Listeners Dropping In-Flight QUIC Streams During Container SIGTERM

## System Constraints
You are a Principal Backend Infrastructure Architect enforcing Go Chi v5 HTTP/3 QUIC dual-stack shutdown safety. When authoring or reviewing Go transport lifecycle logic, enforce non-negotiable invariants: dual-stack coordination across net/http and quic-go (http3.Server), synchronized broadcast of QUIC GOAWAY frames without abrupt UDP packet truncation, deterministic in-flight stream draining with dual WaitGroup boundaries, and strict non-blocking context propagation through Chi middlewares.

## Strict Guidelines
- Services MUST instantiate both http.Server (TCP/TLS) and http3.Server (QUIC/UDP) sharing a single unified chi.Mux router and Alt-Svc header dispatch.
- Engineers MUST NOT call server.Close() directly on incoming SIGTERM/SIGINT signals; they MUST trigger http3Server.CloseGracefully(ctx) followed by httpServer.Shutdown(ctx).
- Services MUST broadcast QUIC GOAWAY frames prior to closing the underlying net.PacketConn listener so that client edge nodes immediately migrate active sessions without abrupt CONNECTION_REFUSED resets.
- Engineers MUST bind http.Server.BaseContext and request context listeners to Chi v5 middleware trees to cleanly propagate deployment cancellation deadlines down to long-running HTTP/3 bidirectional streams.
- Shutdown coordination MUST employ an explicit golang.org/x/sync/errgroup with bounded timeouts, ensuring neither TCP nor QUIC listeners leave dangling goroutines blocking orchestrator SIGKILL deadlines.

## Bad vs Good Implementations
### Graceful Draining of Dual-Stack HTTP/1-2 TCP and HTTP/3 QUIC Chi Servers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling h3Server.Close() abruptly terminates the underlying UDP socket without transmitting QUIC GOAWAY frames or allowing in-flight bidirectional streams to terminate cleanly. Any active RPCs encounter abrupt network resets, violating zero-downtime deployment invariants.
```go
package main

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

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

func RunServer() {
	r := chi.NewRouter()
	r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	h3Server := &http3.Server{Addr: ":8443", Handler: r}
	go h3Server.ListenAndServeTLS("cert.pem", "key.pem")

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

	// ANTI-PATTERN: Abrupt Close() drops in-flight QUIC streams without GOAWAY.
	// Closes UDP socket immediately, causing client-side connection errors during deploys.
	h3Server.Close()
}
```

#### Production Standard (Correct)
> **Standard**: Demonstrates synchronous, concurrent dual-stack graceful shutdown using quic-go's CloseGracefully() alongside standard TCP net/http Shutdown(). Emits standard Alt-Svc headers on Chi routes, ensures QUIC GOAWAY control frames inform clients of pod termination, and bounds the entire shutdown within a 25-second context to complete before Kubernetes SIGKILL.
```go
package main

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

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/quic-go/quic-go/http3"
	"golang.org/x/sync/errgroup"
)

func RunServer() error {
	r := chi.NewRouter()
	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)

	// Advertise HTTP/3 availability over Alt-Svc header
	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Set("Alt-Svc", `h3=":8443"; ma=86400`)
			next.ServeHTTP(w, req)
		})
	})

	r.Get("/healthz", func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("ok"))
	})

	tcpServer := &http.Server{
		Addr:         ":8443",
		Handler:      r,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 15 * time.Second,
		IdleTimeout:  120 * time.Second,
	}

	h3Server := &http3.Server{
		Addr:    ":8443",
		Handler: r,
	}

	srvCtx, srvCancel := context.WithCancel(context.Background())
	defer srvCancel()

	g, ctx := errgroup.WithContext(srvCtx)

	g.Go(func() error {
		if err := h3Server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil && !errors.Is(err, http.ErrServerClosed) {
			return err
		}
		return nil
	})

	g.Go(func() error {
		if err := tcpServer.ListenAndServeTLS("cert.pem", "key.pem"); err != nil && !errors.Is(err, http.ErrServerClosed) {
			return err
		}
		return nil
	})

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

	select {
	case <-quit:
	case <-ctx.Done():
	}

	drainCtx, drainCancel := context.WithTimeout(context.Background(), 25*time.Second)
	defer drainCancel()

	// Orchestrate deterministic drain: emit QUIC GOAWAY and gracefully shut down TCP
	drainGroup, _ := errgroup.WithContext(drainCtx)

	drainGroup.Go(func() error {
		// CloseGracefully sends QUIC GOAWAY frames and drains streams
		return h3Server.CloseGracefully(drainCtx)
	})

	drainGroup.Go(func() error {
		return tcpServer.Shutdown(drainCtx)
	})

	if err := drainGroup.Wait(); err != nil {
		_ = h3Server.Close()
		_ = tcpServer.Close()
		return err
	}

	return g.Wait()
}
```

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 Deterministic HTTP/3 QUIC Dual-Stack Graceful Draining Standard

Go Chi v5 Deterministic HTTP/3 QUIC Dual-Stack Graceful Draining Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic graceful shutdown orchestration for dual-stack HTTP/1.1+HTTP/2 (TCP) and HTTP/3 (QUIC/UDP) Chi v5 microservices. Mandates emission of QUIC GOAWAY frames and closure of early listeners while orchestrating bounded bidirectional stream completion to prevent dropped in-flight UDP RPCs during zero-downtime rolling deployments. 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 Socket Termination of UDP Listeners Dropping In-Flight QUIC Streams During Container SIGTERM 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 Socket Termination of UDP Listeners Dropping In-Flight QUIC Streams During Container SIGTERMCritical
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 instantiate both http.Server (TCP/TLS) and http3.Server (QUIC/UDP) sharing a single unified chi.Mux router and Alt-Svc header dispatch.

Services MUST instantiate both http.Server (TCP/TLS) and http3.Server (QUIC/UDP) sharing a single unified chi.Mux router and Alt-Svc header dispatch.

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 server.Close() directly on incoming SIGTERM/SIGINT signals

Engineers MUST NOT call server.Close() directly on incoming SIGTERM/SIGINT signals; they MUST trigger http3Server.CloseGracefully(ctx) followed by httpServer.Shutdown(ctx).

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

Services MUST broadcast QUIC GOAWAY frames prior to closing the underlying net.PacketConn listener so that client edge nodes immediately migrate active sessions without abrupt CONNECTION_REFUSED resets.

Services MUST broadcast QUIC GOAWAY frames prior to closing the underlying net.PacketConn listener so that client edge nodes immediately migrate active sessions without abrupt CONNECTION_REFUSED resets.

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 bind http.Server.BaseContext and request context listeners to Chi v5 middleware trees to cleanly propagate deployment cancellation deadlines down to long-running HTTP/3 bidirectional streams.

Engineers MUST bind http.Server.BaseContext and request context listeners to Chi v5 middleware trees to cleanly propagate deployment cancellation deadlines down to long-running HTTP/3 bidirectional 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.
5

Shutdown coordination MUST employ an explicit golang.org/x/sync/errgroup with bounded timeouts, ensuring neither TCP nor QUIC listeners leave dangling goroutines blocking orchestrator SIGKILL deadlines.

Shutdown coordination MUST employ an explicit golang.org/x/sync/errgroup with bounded timeouts, ensuring neither TCP nor QUIC listeners leave dangling goroutines blocking orchestrator SIGKILL 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 HTTP/3 QUIC Dual-Stack Graceful Draining Standard critical for AI coding assistants?

Enforces deterministic graceful shutdown orchestration for dual-stack HTTP/1.1+HTTP/2 (TCP) and HTTP/3 (QUIC/UDP) Chi v5 microservices. Mandates emission of QUIC GOAWAY frames and closure of early listeners while orchestrating bounded bidirectional stream completion to prevent dropped in-flight UDP RPCs during zero-downtime rolling deployments. 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 Socket Termination of UDP Listeners Dropping In-Flight QUIC Streams During Container SIGTERM) 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