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

Go 1.24 Chi HTTP/3 QUIC Resilient Session Migration Architecture

Enforces transport-agnostic authenticated session lifecycles for Go 1.24 Chi HTTP/3 architectures across network transitions. Eliminates socket reset storms and unauthorized session invalidation during cellular and Wi-Fi handoffs through connection ID stability, stateless reset token configuration, and IP-independent RPC context binding.

Prohibited Anti-Pattern: Pinning Session Authentication and RPC Contexts to Ephemeral Socket 4-Tuples Under HTTP/3 QUIC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Chi HTTP/3 QUIC Resilient Session Migration Architecture - Enforces transport-agnostic authenticated session lifecycles for Go 1.24 Chi HTTP/3 architectures across network transitions. Eliminates socket reset storms and unauthorized session invalidation during cellular and Wi-Fi handoffs through connection ID stability, stateless reset token configuration, and IP-independent RPC context binding.
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-session-migration-invariants"
---

# Go 1.24 Chi HTTP/3 QUIC Resilient Session Migration Architecture

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Pinning Session Authentication and RPC Contexts to Ephemeral Socket 4-Tuples Under HTTP/3 QUIC

## System Constraints
You are a Principal Software Architect enforcing Go 1.24 Chi HTTP/3 QUIC invariants. You mandate strict decoupling of transport-level remote IP/port 4-tuples from application RPC authentication contexts, robust quic.Config lifecycle settings (StatelessResetKey, ConnectionID handling), and graceful Alt-Svc advertisement in Chi middleware to ensure zero-downtime client network handoffs without connection resets.

## Strict Guidelines
- Engineers MUST NEVER bind authenticated RPC session tokens, rate-limit buckets, or client identity directly to `http.Request.RemoteAddr` when serving HTTP/3 traffic.
- Engineers MUST initialize `quic.Config` with an explicit `StatelessResetKey` and non-zero `ConnectionIDLength` to support active QUIC connection migration across distinct NAT/IP routes.
- Services MUST inject an `Alt-Svc` header middleware in the Chi router pipeline advertising HTTP/3 UDP endpoints alongside standard TCP HTTP/1.1 and HTTP/2 listeners.
- Chi middleware MUST extract cryptographic, replay-resistant session identifiers from mutual headers or TLS exporter state rather than raw network connection properties.
- Components NEVER terminate in-flight streaming RPCs or abort context execution trees solely because the underlying UDP packet origin mutated during a verified QUIC connection migration event.

## Bad vs Good Implementations
### Anti-Pattern: IP-Pinned Auth Middleware and Naive HTTP/3 Listener in Chi

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Pinning session validity to `r.RemoteAddr` causes immediate 401 Unauthorized errors as soon as a client migrates between Wi-Fi and LTE/5G. Initializing `http3.Server` without `quic.Config.StatelessResetKey` and dynamic connection ID negotiation causes silent socket disconnects, unroutable stateless resets, and socket reset storms on client handoff.
```go
package transport

import (
	"context"
	"net/http"
	"github.com/go-chi/chi/v5"
	"github.com/quic-go/quic-go/http3"
)

// Bad: Ties session auth to RemoteAddr and leaves QUIC transport unconfigured
func SetupRouter() *chi.Mux {
	r := chi.NewRouter()
	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			ip := req.RemoteAddr // Anti-pattern: Fails on cellular -> Wi-Fi switch
			token := req.Header.Get("X-Session-ID")
			if !ValidateSessionWithIP(token, ip) {
				http.Error(w, "Session invalid for network path", http.StatusUnauthorized)
				return
			}
			next.ServeHTTP(w, req)
		})
	})
	r.Get("/rpc/stream", HandleStream)
	return r
}

func RunServer(r *chi.Mux) error {
	server := &http3.Server{Addr: ":443", Handler: r} // Anti-pattern: Missing StatelessResetKey & Alt-Svc
	return server.ListenAndServeTLS("cert.pem", "key.pem")
}

func ValidateSessionWithIP(token, ip string) bool { return false }
func HandleStream(w http.ResponseWriter, r *http.Request) {}
```

#### Production Standard (Correct)
> **Standard**: The good implementation configures `quic.Config` with a dedicated `StatelessResetKey` and keep-alive timings, permitting QUIC connection migration without connection dropouts. In addition, the Chi router sets the `Alt-Svc` header and authenticates RPC sessions strictly via signed session tokens rather than ephemeral socket IP addresses.
```go
package transport

import (
	"crypto/rand"
	"fmt"
	"net/http"
	"time"
	"github.com/go-chi/chi/v5"
	"github.com/quic-go/quic-go"
	"github.com/quic-go/quic-go/http3"
)

// SessionContextKey identifies transport-agnostic auth state
type ctxKey string
const SessionKey ctxKey = "auth.session"

func NewSecureChiRouter() *chi.Mux {
	r := chi.NewRouter()
	
	// Alt-Svc advertising HTTP/3 over UDP port 443 with 24h caching
	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.Header().Set("Alt-Svc", `h3=":443"; ma=86400`)
			next.ServeHTTP(w, req)
		})
	})

	// Invariant: Session context survives interface migration by cryptographically verifying tokens
	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			token := req.Header.Get("X-Session-Token")
			session, err := AuthenticateToken(token) // Validates signature, independent of RemoteAddr
			if err != nil {
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}
			ctx := req.Context()
			next.ServeHTTP(w, req.WithContext(SetSession(ctx, session)))
		})
	})

	r.Get("/rpc/stream", HandleStream)
	return r
}

func BuildH3Server(r *chi.Mux, resetKey [32]byte) *http3.Server {
	qConfig := &quic.Config{
		StatelessResetKey:      &resetKey,
		MaxIdleTimeout:         30 * time.Second,
		KeepAlivePeriod:        10 * time.Second,
		AllowConnectionWindow: func(fn func(string) bool) bool { return true },
	}
	return &http3.Server{
		Addr:       ":443",
		Handler:    r,
		QUICConfig: qConfig,
	}
}

type Session struct{ ID string }
func AuthenticateToken(t string) (*Session, error) { return &Session{ID: "usr_123"}, nil }
func SetSession(ctx any, s *Session) any { return ctx }
func HandleStream(w http.ResponseWriter, r *http.Request) {}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 Chi HTTP/3 QUIC Resilient Session Migration Architecture

Go 1.24 Chi HTTP/3 QUIC Resilient Session Migration Architecture defines an industrial-grade behavioral standard for backend engineering. Enforces transport-agnostic authenticated session lifecycles for Go 1.24 Chi HTTP/3 architectures across network transitions. Eliminates socket reset storms and unauthorized session invalidation during cellular and Wi-Fi handoffs through connection ID stability, stateless reset token configuration, and IP-independent RPC context binding. 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: Pinning Session Authentication and RPC Contexts to Ephemeral Socket 4-Tuples Under HTTP/3 QUIC 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 DriftPinning Session Authentication and RPC Contexts to Ephemeral Socket 4-Tuples Under HTTP/3 QUICCritical
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 NEVER bind authenticated RPC session tokens, rate-limit buckets, or client identity directly to `http.Request.RemoteAddr` when serving HTTP/3 traffic.

Engineers MUST NEVER bind authenticated RPC session tokens, rate-limit buckets, or client identity directly to `http.Request.RemoteAddr` when serving HTTP/3 traffic.

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 initialize `quic.Config` with an explicit `StatelessResetKey` and non-zero `ConnectionIDLength` to support active QUIC connection migration across distinct NAT/IP routes.

Engineers MUST initialize `quic.Config` with an explicit `StatelessResetKey` and non-zero `ConnectionIDLength` to support active QUIC connection migration across distinct NAT/IP routes.

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 inject an `Alt-Svc` header middleware in the Chi router pipeline advertising HTTP/3 UDP endpoints alongside standard TCP HTTP/1.1 and HTTP/2 listeners.

Services MUST inject an `Alt-Svc` header middleware in the Chi router pipeline advertising HTTP/3 UDP endpoints alongside standard TCP HTTP/1.1 and HTTP/2 listeners.

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

Chi middleware MUST extract cryptographic, replay-resistant session identifiers from mutual headers or TLS exporter state rather than raw network connection properties.

Chi middleware MUST extract cryptographic, replay-resistant session identifiers from mutual headers or TLS exporter state rather than raw network connection properties.

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

Components NEVER terminate in-flight streaming RPCs or abort context execution trees solely because the underlying UDP packet origin mutated during a verified QUIC connection migration event.

Components NEVER terminate in-flight streaming RPCs or abort context execution trees solely because the underlying UDP packet origin mutated during a verified QUIC connection migration event.

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 1.24 Chi HTTP/3 QUIC Resilient Session Migration Architecture critical for AI coding assistants?

Enforces transport-agnostic authenticated session lifecycles for Go 1.24 Chi HTTP/3 architectures across network transitions. Eliminates socket reset storms and unauthorized session invalidation during cellular and Wi-Fi handoffs through connection ID stability, stateless reset token configuration, and IP-independent RPC context binding. 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 (Pinning Session Authentication and RPC Contexts to Ephemeral Socket 4-Tuples Under HTTP/3 QUIC) 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