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

Go Chi HTTP/3 Early Hints QUIC Stream Lifecycle Synchronizer

Mandates deterministic propagation of QUIC stream terminations (e.g., client STOP_SENDING, stream reset) to all asynchronous HTTP 103 Early Hints pipelines within Go Chi services. Eliminates phantom worker routines, goroutine leaks, and wasted compute by binding worker lifecycles strictly to the request context and verifying stream health prior to non-blocking 103 header flushes.

Prohibited Anti-Pattern: Detached Early Hint Dispatch Yielding Phantom Compute and Resource Starvation on Aborted QUIC Streams

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi HTTP/3 Early Hints QUIC Stream Lifecycle Synchronizer - Mandates deterministic propagation of QUIC stream terminations (e.g., client STOP_SENDING, stream reset) to all asynchronous HTTP 103 Early Hints pipelines within Go Chi services. Eliminates phantom worker routines, goroutine leaks, and wasted compute by binding worker lifecycles strictly to the request context and verifying stream health prior to non-blocking 103 header flushes.
globs: **/*.go, internal/transport/http/**/*.go, internal/middleware/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-early-hints-quic-lifecycle"
---

# Go Chi HTTP/3 Early Hints QUIC Stream Lifecycle Synchronizer

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Detached Early Hint Dispatch Yielding Phantom Compute and Resource Starvation on Aborted QUIC Streams

## System Constraints
You are a Principal Software Architect enforcing zero-leak concurrency, QUIC stream lifecycle synchronization, and strict RFC 8297 (HTTP 103 Early Hints) semantics in Go Chi HTTP/3 servers. You must ensure that any asynchronous asset resolution or early header generation respects QUIC stream resets, preempts uncommitted I/O, and enforces cancellation across all child goroutines via context synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS bind asynchronous Early Hints workers to `r.Context()` and terminate execution immediately upon `<-ctx.Done()`.
- Engineers MUST NOT invoke `rc.WriteHeader(http.StatusEarlyHints)` without evaluating the error returned by the `http.ResponseController` write/flush pipeline.
- Code MUST employ `http.NewResponseController(w)` or QUIC-native flusher interfaces to write intermediate 103 responses, immediately aborting execution on `net.ErrClosed`, `context.Canceled`, or QUIC stream reset errors.
- Services MUST suppress detached, fire-and-forget goroutines (`go func() { ... }()`) when computing early asset preloads; all concurrent hinting MUST be bounded by errgroups or synchronous lifecycle managers.
- Components NEVER buffer heavy compute or state mutations prior to intermediate 103 flushes without checking whether the underlying QUIC stream has been closed by client navigation or cancellation.

## Bad vs Good Implementations
### QUIC Early Hints Synchronization with Chi and ResponseController

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The goroutine executes without referencing `r.Context()`. If the client navigates away or resets the HTTP/3 QUIC stream (`STOP_SENDING`), the goroutine remains active in memory, computes costly assets, and attempts to write to an abandoned stream. This creates thread contention, resource leakage, and suppresses backpressure.
```go
package handlers

import (
	"net/http"
	"time"
	"github.com/go-chi/chi/v5"
)

func RegisterBadRoute(r chi.Router) {
	r.Get("/dashboard", func(w http.ResponseWriter, r *http.Request) {
		// ANTI-PATTERN: Fire-and-forget goroutine detached from QUIC stream lifecycle.
		// If the client aborts the QUIC stream, this worker continues running,
		// executes expensive queries, and leaks goroutines attempting to write to a closed stream.
		go func() {
			time.Sleep(50 * time.Millisecond) // Simulating asset pre-computation
			w.Header().Add("Link", "</assets/dash.css>; rel=preload; as=style")
			w.WriteHeader(http.StatusEarlyHints) // Panic or silent leak on reset stream
		}()

		// Proceed with expensive DB query regardless of QUIC stream health
		time.Sleep(200 * time.Millisecond)
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`{"status":"ready"}`))
	})
}
```

#### Production Standard (Correct)
> **Standard**: The child task is governed by an `errgroup` bound to `r.Context()`. Writes to HTTP 103 are performed through `http.NewResponseController(w)` and verified. If the QUIC stream experiences a reset or cancellation, the context cancels immediately, aborting subsequent database/worker allocations and cleanly reclaiming server resources.
```go
package handlers

import (
	"context"
	"errors"
	"net/http"
	"github.com/go-chi/chi/v5"
	"golang.org/x/sync/errgroup"
)

func RegisterGoodRoute(r chi.Router) {
	r.Get("/dashboard", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		rc := http.NewResponseController(w)

		g, gctx := errgroup.WithContext(ctx)

		// Synchronized worker tied to QUIC stream lifecycle
		g.Go(func() error {
			select {
			case <-gctx.Done():
				return gctx.Err()
			default:
				w.Header().Add("Link", "</assets/dash.css>; rel=preload; as=style")
				err := rc.WriteHeader(http.StatusEarlyHints)
				if err != nil {
					// Stream was reset by client; fail fast to abort entire pipeline
					return err
				}
				return nil
			}
		})

		if err := g.Wait(); err != nil {
			if errors.Is(err, context.Canceled) {
				return // Stream aborted; reclaim worker state cleanly
			}
			http.Error(w, "Stream failure", http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte(`{"status":"ready"}`))
	})
}
```

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 Early Hints QUIC Stream Lifecycle Synchronizer

Go Chi HTTP/3 Early Hints QUIC Stream Lifecycle Synchronizer defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic propagation of QUIC stream terminations (e.g., client STOP_SENDING, stream reset) to all asynchronous HTTP 103 Early Hints pipelines within Go Chi services. Eliminates phantom worker routines, goroutine leaks, and wasted compute by binding worker lifecycles strictly to the request context and verifying stream health prior to non-blocking 103 header flushes. 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: Detached Early Hint Dispatch Yielding Phantom Compute and Resource Starvation on Aborted QUIC Streams 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 DriftDetached Early Hint Dispatch Yielding Phantom Compute and Resource Starvation on Aborted QUIC StreamsCritical
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 bind asynchronous Early Hints workers to `r.Context()` and terminate execution immediately upon `<-ctx.Done()`.

Engineers MUST ALWAYS bind asynchronous Early Hints workers to `r.Context()` and terminate execution immediately upon `<-ctx.Done()`.

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 invoke `rc.WriteHeader(http.StatusEarlyHints)` without evaluating the error returned by the `http.ResponseController` write/flush pipeline.

Engineers MUST NOT invoke `rc.WriteHeader(http.StatusEarlyHints)` without evaluating the error returned by the `http.ResponseController` write/flush pipeline.

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

Code MUST employ `http.NewResponseController(w)` or QUIC-native flusher interfaces to write intermediate 103 responses, immediately aborting execution on `net.ErrClosed`, `context.Canceled`, or QUIC stream reset errors.

Code MUST employ `http.NewResponseController(w)` or QUIC-native flusher interfaces to write intermediate 103 responses, immediately aborting execution on `net.ErrClosed`, `context.Canceled`, or QUIC stream reset errors.

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 suppress detached, fire-and-forget goroutines (`go func() { ... }()`) when computing early asset preloads

Services MUST suppress detached, fire-and-forget goroutines (`go func() { ... }()`) when computing early asset preloads; all concurrent hinting MUST be bounded by errgroups or synchronous lifecycle managers.

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 buffer heavy compute or state mutations prior to intermediate 103 flushes without checking whether the underlying QUIC stream has been closed by client navigation or cancellation.

Components NEVER buffer heavy compute or state mutations prior to intermediate 103 flushes without checking whether the underlying QUIC stream has been closed by client navigation or cancellation.

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 Early Hints QUIC Stream Lifecycle Synchronizer critical for AI coding assistants?

Mandates deterministic propagation of QUIC stream terminations (e.g., client STOP_SENDING, stream reset) to all asynchronous HTTP 103 Early Hints pipelines within Go Chi services. Eliminates phantom worker routines, goroutine leaks, and wasted compute by binding worker lifecycles strictly to the request context and verifying stream health prior to non-blocking 103 header flushes. 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 (Detached Early Hint Dispatch Yielding Phantom Compute and Resource Starvation on Aborted QUIC Streams) 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