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

Go Chi HTTP/3 QUIC Stream Reset Propagation & Connection Reclamation Invariant

Enforces deterministic cancellation propagation from QUIC stream resets down through Go Chi middleware trees, database transactions, and background goroutines. When an HTTP/3 client issues a QUIC RESET_STREAM frame, the underlying http.Request context must immediately abort active SQL/IO queries and release pooled connection reservations back to the driver without goroutine leaks. Failure to strictly propagate and observe r.Context().Done() creates phantom workload amplification and deadlocked connection pools under packet loss or route flapping.

Prohibited Anti-Pattern: Orphaned SQL Queries and Goroutine Accumulation Due to Detached Contexts on HTTP/3 QUIC Stream Resets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi HTTP/3 QUIC Stream Reset Propagation & Connection Reclamation Invariant - Enforces deterministic cancellation propagation from QUIC stream resets down through Go Chi middleware trees, database transactions, and background goroutines. When an HTTP/3 client issues a QUIC RESET_STREAM frame, the underlying http.Request context must immediately abort active SQL/IO queries and release pooled connection reservations back to the driver without goroutine leaks. Failure to strictly propagate and observe r.Context().Done() creates phantom workload amplification and deadlocked connection pools under packet loss or route flapping.
globs: **/*.go, cmd/**/*.go, internal/**/*.go, pkg/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-quic-stream-reset-propagation-invariant"
---

# Go Chi HTTP/3 QUIC Stream Reset Propagation & Connection Reclamation Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned SQL Queries and Goroutine Accumulation Due to Detached Contexts on HTTP/3 QUIC Stream Resets

## System Constraints
You are a Principal Backend Systems Architect specializing in high-throughput Go networked services over HTTP/3 (quic-go/Chi). You enforce absolute adherence to stream lifecycle bounds, context cancellation propagation, and rapid database connection reclamation. Every downstream resource must abort immediately upon receiving a QUIC stream reset.

## Strict Guidelines
- Engineers MUST ALWAYS pass r.Context() directly to database driver methods (e.g., QueryContext, ExecContext, BeginTx) to ensure immediate connection return upon client QUIC RESET_STREAM.
- Engineers MUST NOT spawn detached background goroutines using context.Background() or context.TODO() to handle client-dependent workloads without explicit, bounded lifecycle governance.
- Middleware pipelines in Chi MUST NOT swallow or mask context cancellation errors (context.Canceled) as generic HTTP 500 internal errors; stream aborts must trigger immediate stack unwinding.
- Services MUST ensure that streaming response loops continuously poll r.Context().Done() between chunk flushes to detect client aborts and release locked pool resources instantly.
- Components NEVER hold acquired pgx/sql connection locks or begin unbounded transactions without deferring a rollback that handles context.Canceled.

## Bad vs Good Implementations
### HTTP/3 Chi Route: Database Query Context Binding and Stream Reset Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler launches queries using context.Background() or context-free db.Query(), ignoring the QUIC request context. If the client drops the connection or sends a RESET_STREAM frame, the database driver continues executing expensive queries and retains connection slots from the pool.
```go
package handlers

import (
	"context"
	"database/sql"
	"encoding/json"
	"net/http"
	"github.com/go-chi/chi/v5"
)

func RegisterRoutes(r chi.Router, db *sql.DB) {
	r.Get("/reports/{id}", func(w http.ResponseWriter, r *http.Request) {
		id := chi.URLParam(r, "id")
		
		// ANTI-PATTERN: Spawning unbound goroutine with context.Background().
		// When a QUIC stream is reset (RESET_STREAM), this query runs to completion,
		// leaking DB connections and exhausting the pool under high load.
		go func() {
			var payload string
			_ = db.QueryRowContext(context.Background(), "SELECT data FROM large_reports WHERE id = $1", id).Scan(&payload)
		}()

		// ANTI-PATTERN: Ignoring r.Context() cancellation during synchronous query
		rows, err := db.Query("SELECT metric, value FROM report_metrics WHERE report_id = " + id)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		var results []map[string]any
		for rows.Next() {
			var k string
			var v float64
			_ = rows.Scan(&k, &v)
			results = append(results, map[string]any{k: v})
		}
		_ = json.NewEncoder(w).Encode(results)
	})
}
```

#### Production Standard (Correct)
> **Standard**: All database operations strictly propagate r.Context(). When the QUIC client cancels the stream, the Go runtime cancels the context, terminating the database execution and releasing connection pool handles immediately. Row scanning loops also guard against in-flight teardowns.
```go
package handlers

import (
	"database/sql"
	"encoding/json"
	"errors"
	"net/http"
	"github.com/go-chi/chi/v5"
)

func RegisterRoutes(r chi.Router, db *sql.DB) {
	r.Get("/reports/{id}", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		id := chi.URLParam(r, "id")

		// INVARIANT: Bind the incoming request context strictly to transactions and queries.
		// In HTTP/3, a QUIC RESET_STREAM triggers ctx.Done(), instantly aborting the query
		// over the wire and returning the connection to the sql.DB pool.
		rows, err := db.QueryContext(ctx, "SELECT metric, value FROM report_metrics WHERE report_id = $1", id)
		if err != nil {
			if errors.Is(err, ctx.Err()) {
				// Stream reset by client; unwind cleanly without writing invalid response
				return
			}
			http.Error(w, "database query error", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		results := make([]map[string]any, 0)
		for rows.Next() {
			// Guard long scan iterations against stream cancellations
			select {
			case <-ctx.Done():
				return
			default:
			}

			var k string
			var v float64
			if err := rows.Scan(&k, &v); err != nil {
				http.Error(w, "scan error", http.StatusInternalServerError)
				return
			}
			results = append(results, map[string]any{k: v})
		}

		if err := rows.Err(); err != nil {
			if !errors.Is(err, ctx.Err()) {
				http.Error(w, "row iteration error", http.StatusInternalServerError)
			}
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(results)
	})
}
```

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 QUIC Stream Reset Propagation & Connection Reclamation Invariant

Go Chi HTTP/3 QUIC Stream Reset Propagation & Connection Reclamation Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic cancellation propagation from QUIC stream resets down through Go Chi middleware trees, database transactions, and background goroutines. When an HTTP/3 client issues a QUIC RESET_STREAM frame, the underlying http.Request context must immediately abort active SQL/IO queries and release pooled connection reservations back to the driver without goroutine leaks. Failure to strictly propagate and observe r.Context().Done() creates phantom workload amplification and deadlocked connection pools under packet loss or route flapping. 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: Orphaned SQL Queries and Goroutine Accumulation Due to Detached Contexts on HTTP/3 QUIC Stream Resets 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 DriftOrphaned SQL Queries and Goroutine Accumulation Due to Detached Contexts on HTTP/3 QUIC Stream ResetsCritical
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 pass r.Context() directly to database driver methods (e.g., QueryContext, ExecContext, BeginTx) to ensure immediate connection return upon client QUIC RESET_STREAM.

Engineers MUST ALWAYS pass r.Context() directly to database driver methods (e.g., QueryContext, ExecContext, BeginTx) to ensure immediate connection return upon client QUIC RESET_STREAM.

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() to handle client-dependent workloads without explicit, bounded lifecycle governance.

Engineers MUST NOT spawn detached background goroutines using context.Background() or context.TODO() to handle client-dependent workloads without explicit, bounded lifecycle governance.

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

Middleware pipelines in Chi MUST NOT swallow or mask context cancellation errors (context.Canceled) as generic HTTP 500 internal errors

Middleware pipelines in Chi MUST NOT swallow or mask context cancellation errors (context.Canceled) as generic HTTP 500 internal errors; stream aborts must trigger immediate stack unwinding.

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

Services MUST ensure that streaming response loops continuously poll r.Context().Done() between chunk flushes to detect client aborts and release locked pool resources instantly.

Services MUST ensure that streaming response loops continuously poll r.Context().Done() between chunk flushes to detect client aborts and release locked pool resources instantly.

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 hold acquired pgx/sql connection locks or begin unbounded transactions without deferring a rollback that handles context.Canceled.

Components NEVER hold acquired pgx/sql connection locks or begin unbounded transactions without deferring a rollback that handles context.Canceled.

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 QUIC Stream Reset Propagation & Connection Reclamation Invariant critical for AI coding assistants?

Enforces deterministic cancellation propagation from QUIC stream resets down through Go Chi middleware trees, database transactions, and background goroutines. When an HTTP/3 client issues a QUIC RESET_STREAM frame, the underlying http.Request context must immediately abort active SQL/IO queries and release pooled connection reservations back to the driver without goroutine leaks. Failure to strictly propagate and observe r.Context().Done() creates phantom workload amplification and deadlocked connection pools under packet loss or route flapping. 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 (Orphaned SQL Queries and Goroutine Accumulation Due to Detached Contexts on HTTP/3 QUIC Stream Resets) 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