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

Go Chi HTTP/3 Connection Migration and Context Cancellation Propagation

Guarantees immediate propagation of cancellation signals and QUIC stream teardowns down to database transactions and worker routines during rapid mobile network migrations. Enforces strict binding to r.Context() and prevents detached context leakage when underlying HTTP/3 UDP 4-tuples shift or fail path validation.

Prohibited Anti-Pattern: Decoupled Context Lifecycles and Goroutine Leaks During QUIC Stream Resets and Network Handoffs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi HTTP/3 Connection Migration and Context Cancellation Propagation - Guarantees immediate propagation of cancellation signals and QUIC stream teardowns down to database transactions and worker routines during rapid mobile network migrations. Enforces strict binding to r.Context() and prevents detached context leakage when underlying HTTP/3 UDP 4-tuples shift or fail path validation.
globs: cmd/**/*.go, internal/**/*.go, pkg/**/*.go, **/*handler*.go, **/*router*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-connection-migration-context-cancellation-invariants"
---

# Go Chi HTTP/3 Connection Migration and Context Cancellation Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Decoupled Context Lifecycles and Goroutine Leaks During QUIC Stream Resets and Network Handoffs

## System Constraints
You are a Principal Backend Architect enforcing strict Go Chi HTTP/3 connection migration and context cancellation propagation invariants. Under HTTP/3 (QUIC), mobile clients frequently migrate across UDP 4-tuples (e.g., Wi-Fi to 5G) or abort streams when path validation fails. You must ensure that HTTP request contexts immediately abort downstream database queries, RPCs, and IO operations upon stream termination, preventing zombie transactions, memory leaks, and goroutine starvation.

## Strict Guidelines
- Engineers MUST ALWAYS propagate r.Context() directly to all downstream database calls, redis pipelines, and outbound HTTP/RPC requests without stripping cancellation signals.
- Engineers MUST NOT spawn detached background goroutines using context.Background() or context.TODO() inside Chi handler chains for client-requested workloads.
- Streaming endpoints (SSE, chunked data, WebTransport) MUST monitor r.Context().Done() concurrently with send operations to detect broken QUIC streams immediately.
- Middleware chains MUST NEVER create child contexts with new cancellation roots that swallow or fail to link to the parent request's Done channel.
- Database transactions MUST be initiated using db.BeginTx(r.Context(), opts) so that any QUIC stream reset or network handoff failure triggers an automatic context rollback.
- Services MUST ensure that response flushers and chunked writers check for context errors before every write to avoid panics on dead QUIC stream handles.

## Bad vs Good Implementations
### Database Transaction and Streaming Under HTTP/3 Chi Router

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using context.Background() detaches the handler from the HTTP/3 request lifecycle. If a mobile device migrates networks and the QUIC stream is reset by peer, the database transaction and lock remain active as zombie processes, exhausting connection pools and causing contention.
```go
package handler

import (
	"context"
	"database/sql"
	"net/http"
	"time"

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

func MountRoutes(r chi.Router, db *sql.DB) {
	r.Post("/process-data", func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Detaching context using Background() prevents cancellation
		// when the client experiences a failed HTTP/3 connection migration.
		ctx := context.Background()
		tx, err := db.BeginTx(ctx, nil)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer tx.Rollback()

		// Spawning unbounded goroutine uncoupled from r.Context().
		// If the QUIC stream resets or client drops, this goroutine and lock persist indefinitely.
		go func() {
			_, _ = tx.ExecContext(ctx, "UPDATE account_balances SET locked = true WHERE id = ?", 1234)
			time.Sleep(5 * time.Second) // Simulating long operation
			_ = tx.Commit()
		}()

		w.WriteHeader(http.StatusAccepted)
	})
}
```

#### Production Standard (Correct)
> **Standard**: Binding db.BeginTx and tx.ExecContext directly to r.Context() guarantees that QUIC stream resets or aborted migrations immediately roll back transactions, release row locks, and avoid leaking database connections.
```go
package handler

import (
	"database/sql"
	"errors"
	"net/http"

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

func MountRoutes(r chi.Router, db *sql.DB) {
	r.Post("/process-data", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		// INVARIANT: Bind transaction directly to r.Context().
		// If the QUIC connection migration fails or stream resets, ctx.Done() cancels tx.
		tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer tx.Rollback() // Safe no-op if successfully committed or canceled

		// Execute synchronously or bounded within the request context
		_, err = tx.ExecContext(ctx, "UPDATE account_balances SET locked = true WHERE id = ?", 1234)
		if err != nil {
			if errors.Is(ctx.Err(), context.Canceled) {
				// Client disconnected during HTTP/3 migration; exit cleanly
				return
			}
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if err := tx.Commit(); err != nil {
			if !errors.Is(ctx.Err(), context.Canceled) {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			return
		}

		w.WriteHeader(http.StatusOK)
	})
}
```

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 HTTP/3 Connection Migration and Context Cancellation Propagation

Go Chi HTTP/3 Connection Migration and Context Cancellation Propagation defines an industrial-grade behavioral standard for backend engineering. Guarantees immediate propagation of cancellation signals and QUIC stream teardowns down to database transactions and worker routines during rapid mobile network migrations. Enforces strict binding to r.Context() and prevents detached context leakage when underlying HTTP/3 UDP 4-tuples shift or fail path validation. 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: Decoupled Context Lifecycles and Goroutine Leaks During QUIC Stream Resets and Network Handoffs 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 DriftDecoupled Context Lifecycles and Goroutine Leaks During QUIC Stream Resets and Network HandoffsCritical
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 propagate r.Context() directly to all downstream database calls, redis pipelines, and outbound HTTP/RPC requests without stripping cancellation signals.

Engineers MUST ALWAYS propagate r.Context() directly to all downstream database calls, redis pipelines, and outbound HTTP/RPC requests without stripping cancellation signals.

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 spawn detached background goroutines using context.Background() or context.TODO() inside Chi handler chains for client-requested workloads.

Engineers MUST NOT spawn detached background goroutines using context.Background() or context.TODO() inside Chi handler chains for client-requested workloads.

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

Streaming endpoints (SSE, chunked data, WebTransport) MUST monitor r.Context().Done() concurrently with send operations to detect broken QUIC streams immediately.

Streaming endpoints (SSE, chunked data, WebTransport) MUST monitor r.Context().Done() concurrently with send operations to detect broken QUIC streams immediately.

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

Middleware chains MUST NEVER create child contexts with new cancellation roots that swallow or fail to link to the parent request's Done channel.

Middleware chains MUST NEVER create child contexts with new cancellation roots that swallow or fail to link to the parent request's Done channel.

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

Database transactions MUST be initiated using db.BeginTx(r.Context(), opts) so that any QUIC stream reset or network handoff failure triggers an automatic context rollback.

Database transactions MUST be initiated using db.BeginTx(r.Context(), opts) so that any QUIC stream reset or network handoff failure triggers an automatic context rollback.

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 ensure that response flushers and chunked writers check for context errors before every write to avoid panics on dead QUIC stream handles.

Services MUST ensure that response flushers and chunked writers check for context errors before every write to avoid panics on dead QUIC stream handles.

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 HTTP/3 Connection Migration and Context Cancellation Propagation critical for AI coding assistants?

Guarantees immediate propagation of cancellation signals and QUIC stream teardowns down to database transactions and worker routines during rapid mobile network migrations. Enforces strict binding to r.Context() and prevents detached context leakage when underlying HTTP/3 UDP 4-tuples shift or fail path validation. 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 (Decoupled Context Lifecycles and Goroutine Leaks During QUIC Stream Resets and Network Handoffs) 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