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

Go Chi Graceful HTTP/3 QUIC GOAWAY Connection Draining Standard

Enforces deterministic two-phase QUIC connection and stream draining when running HTTP/3 servers over Go Chi during container lifecycle transitions. Orchestrates initial and final GOAWAY frame emission with synchronized HTTP/1.1, HTTP/2, and HTTP/3 listeners against Kubernetes preStop hooks and SIGTERM grace periods to prevent dropped in-flight UDP RPCs.

Prohibited Anti-Pattern: Abrupt QUIC Context Cancellation Causing CONNECTION_REFUSED and Silent Dropped Streams During Pod Rollouts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Graceful HTTP/3 QUIC GOAWAY Connection Draining Standard - Enforces deterministic two-phase QUIC connection and stream draining when running HTTP/3 servers over Go Chi during container lifecycle transitions. Orchestrates initial and final GOAWAY frame emission with synchronized HTTP/1.1, HTTP/2, and HTTP/3 listeners against Kubernetes preStop hooks and SIGTERM grace periods to prevent dropped in-flight UDP RPCs.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, server/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-quic-graceful-draining-standard"
---

# Go Chi Graceful HTTP/3 QUIC GOAWAY Connection Draining Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Abrupt QUIC Context Cancellation Causing CONNECTION_REFUSED and Silent Dropped Streams During Pod Rollouts

## System Constraints
You are a Principal Backend Infrastructure Architect enforcing zero-downtime rolling deploys for Go Chi microservices serving dual TCP (HTTP/1.1, HTTP/2) and UDP (HTTP/3 via quic-go). You must enforce strict lifecycle sequencing: when receiving SIGTERM or triggering graceful shutdown, HTTP/3 listeners must immediately send an initial GOAWAY frame (stopping new streams), wait for Kubernetes Endpoints/kube-proxy/ingress mesh propagation (sleep/readiness probe failure), process in-flight QUIC streams with a bounded deadline, and close only after all active bidirectional streams complete or the context deadline expires.

## Strict Guidelines
- Engineers MUST ALWAYS run HTTP/3 (quic-go/http3) and standard TCP (http.Server) concurrently with coordinated context cancellation and errgroup orchestration.
- Engineers MUST configure a Kubernetes preStop hook sleep or internal sync barrier (e.g., 5-15 seconds) prior to closing listeners, ensuring ingress controllers and kube-proxy remove the Pod IP from routing tables before draining begins.
- Engineers MUST trigger `http3.Server.CloseGracefully(ctx)` instead of calling raw `Close()` on the HTTP/3 listener or immediately cancelling the parent context upon SIGTERM.
- Engineers MUST set explicit `ReadTimeout`, `WriteTimeout`, and QUIC `MaxIdleTimeout` values on `http3.Server` to prevent deadlocked in-flight streams from blocking container termination.
- Engineers MUST NOT rely solely on standard `http.Server.Shutdown(ctx)` because standard library shutdown routines do not manage QUIC UDP listeners or send HTTP/3 GOAWAY frames.
- Services MUST advertise Alt-Svc headers with non-zero max-age (`ma`) values on standard HTTP/1.1 and HTTP/2 Chi routes to steer clients into HTTP/3 safely, but SHOULD dynamically decrease `ma=0` on shutdown if traffic rerouting is required.

## Bad vs Good Implementations
### Dual-Stack Go Chi HTTP/1.1/2 & HTTP/3 Graceful Draining vs Abrupt Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling h3Server.Close() instantly terminates the underlying UDP socket and destroys active QUIC streams. In-flight requests are hard-reset, causing immediate 5xx drops during Kubernetes rolling deployments because no HTTP/3 GOAWAY frames were dispatched and no propagation delay was observed.
```go
package main

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

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

func main() {
	r := chi.NewRouter()
	r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
	r.Get("/work", func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(2 * time.Second) // In-flight work
		w.Write([]byte("done"))
	})

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

	go func() {
		_ = h3Server.ListenAndServeTLS("cert.pem", "key.pem")
	}()

	sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	<-sigCtx.Done()

	// ANTI-PATTERN: Direct Close() aborts all active QUIC streams instantly,
	// emitting CONNECTION_REFUSED / APPLICATION_ERROR without GOAWAY drainage.
	_ = h3Server.Close()
}
```

#### Production Standard (Correct)
> **Standard**: The production-grade pattern toggles readiness health status first, observes the network route convergence delay, and invokes CloseGracefully with a bounded context. quic-go sends an HTTP/3 GOAWAY frame to indicate no further streams will be accepted while allowing active in-flight UDP RPCs to finish.
```go
package main

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

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

func main() {
	r := chi.NewRouter()
	var isShuttingDown atomic.Bool

	r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
		if isShuttingDown.Load() {
			http.Error(w, "Draining", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	h3Server := &http3.Server{
		Addr:    ":8443",
		Handler: r,
		QUICConfig: &quic.Config{
			MaxIdleTimeout: 15 * time.Second,
		},
	}

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

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

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

	select {
	case <-sigChan:
	case <-gCtx.Done():
	}

	// 1. Mark readiness probe unhealthy; wait for ingress/kube-proxy route eviction
	isShuttingDown.Store(true)
	time.Sleep(5 * time.Second)

	// 2. Bound total graceful shutdown time according to pod terminationGracePeriodSeconds
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
	defer cancel()

	// 3. Orchestrate concurrent HTTP/3 GOAWAY stream drain and TCP shutdown
	var drainGroup errgroup.Group
	drainGroup.Go(func() error {
		return h3Server.CloseGracefully(shutdownCtx.Done())
	})
	drainGroup.Go(func() error {
		return tcpServer.Shutdown(shutdownCtx)
	})

	_ = drainGroup.Wait()
	_ = 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 Graceful HTTP/3 QUIC GOAWAY Connection Draining Standard

Go Chi Graceful HTTP/3 QUIC GOAWAY Connection Draining Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic two-phase QUIC connection and stream draining when running HTTP/3 servers over Go Chi during container lifecycle transitions. Orchestrates initial and final GOAWAY frame emission with synchronized HTTP/1.1, HTTP/2, and HTTP/3 listeners against Kubernetes preStop hooks and SIGTERM grace periods to prevent dropped in-flight UDP RPCs. 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: Abrupt QUIC Context Cancellation Causing CONNECTION_REFUSED and Silent Dropped Streams During Pod Rollouts 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 DriftAbrupt QUIC Context Cancellation Causing CONNECTION_REFUSED and Silent Dropped Streams During Pod RolloutsCritical
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 run HTTP/3 (quic-go/http3) and standard TCP (http.Server) concurrently with coordinated context cancellation and errgroup orchestration.

Engineers MUST ALWAYS run HTTP/3 (quic-go/http3) and standard TCP (http.Server) concurrently with coordinated context cancellation and errgroup orchestration.

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 configure a Kubernetes preStop hook sleep or internal sync barrier (e.g., 5-15 seconds) prior to closing listeners, ensuring ingress controllers and kube-proxy remove the Pod IP from routing tables before draining begins.

Engineers MUST configure a Kubernetes preStop hook sleep or internal sync barrier (e.g., 5-15 seconds) prior to closing listeners, ensuring ingress controllers and kube-proxy remove the Pod IP from routing tables before draining begins.

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 trigger `http3.Server.CloseGracefully(ctx)` instead of calling raw `Close()` on the HTTP/3 listener or immediately cancelling the parent context upon SIGTERM.

Engineers MUST trigger `http3.Server.CloseGracefully(ctx)` instead of calling raw `Close()` on the HTTP/3 listener or immediately cancelling the parent context upon SIGTERM.

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 set explicit `ReadTimeout`, `WriteTimeout`, and QUIC `MaxIdleTimeout` values on `http3.Server` to prevent deadlocked in-flight streams from blocking container termination.

Engineers MUST set explicit `ReadTimeout`, `WriteTimeout`, and QUIC `MaxIdleTimeout` values on `http3.Server` to prevent deadlocked in-flight streams from blocking container termination.

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

Engineers MUST NOT rely solely on standard `http.Server.Shutdown(ctx)` because standard library shutdown routines do not manage QUIC UDP listeners or send HTTP/3 GOAWAY frames.

Engineers MUST NOT rely solely on standard `http.Server.Shutdown(ctx)` because standard library shutdown routines do not manage QUIC UDP listeners or send HTTP/3 GOAWAY frames.

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 advertise Alt-Svc headers with non-zero max-age (`ma`) values on standard HTTP/1.1 and HTTP/2 Chi routes to steer clients into HTTP/3 safely, but SHOULD dynamically decrease `ma=0` on shutdown if traffic rerouting is required.

Services MUST advertise Alt-Svc headers with non-zero max-age (`ma`) values on standard HTTP/1.1 and HTTP/2 Chi routes to steer clients into HTTP/3 safely, but SHOULD dynamically decrease `ma=0` on shutdown if traffic rerouting is required.

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 Graceful HTTP/3 QUIC GOAWAY Connection Draining Standard critical for AI coding assistants?

Enforces deterministic two-phase QUIC connection and stream draining when running HTTP/3 servers over Go Chi during container lifecycle transitions. Orchestrates initial and final GOAWAY frame emission with synchronized HTTP/1.1, HTTP/2, and HTTP/3 listeners against Kubernetes preStop hooks and SIGTERM grace periods to prevent dropped in-flight UDP RPCs. 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 (Abrupt QUIC Context Cancellation Causing CONNECTION_REFUSED and Silent Dropped Streams During Pod Rollouts) 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