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

Deterministic Child Goroutine and Channel Teardown on QUIC Stream Reset in Go Chi HTTP/3

Guarantees immediate and deterministic teardown of child worker goroutines, fan-out pipelines, and unbuffered channel interactions when receiving client-initiated QUIC stream resets (RESET_STREAM/STOP_SENDING). Mandates strict context propagation from Chi HTTP/3 request contexts and forbids unmultiplexed channel operations that cause permanent goroutine leaks.

Prohibited Anti-Pattern: Permanent Goroutine Leaks and Channel Deadlocks via Unguarded HTTP/3 QUIC Stream Resets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Child Goroutine and Channel Teardown on QUIC Stream Reset in Go Chi HTTP/3 - Guarantees immediate and deterministic teardown of child worker goroutines, fan-out pipelines, and unbuffered channel interactions when receiving client-initiated QUIC stream resets (RESET_STREAM/STOP_SENDING). Mandates strict context propagation from Chi HTTP/3 request contexts and forbids unmultiplexed channel operations that cause permanent goroutine leaks.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-quic-stream-cancellation-standard"
---

# Deterministic Child Goroutine and Channel Teardown on QUIC Stream Reset in Go Chi HTTP/3

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Permanent Goroutine Leaks and Channel Deadlocks via Unguarded HTTP/3 QUIC Stream Resets

## System Constraints
You are a Principal Backend Architect enforcing strict concurrency safety and QUIC stream cancellation propagation in Go Chi HTTP/3 services. HTTP/3 connections permit clients to cancel individual streams asynchronously via RESET_STREAM or STOP_SENDING frames, causing net/http and quic-go to immediately cancel r.Context(). You must mandate deterministic teardown of all asynchronous child tasks, prohibit unguarded unbuffered channel sends, and enforce errgroup or select-driven context termination across all Chi routing handlers.

## Strict Guidelines
- Engineers MUST ALWAYS pass r.Context() directly to child worker goroutines or derive child contexts using context.WithCancelCause(r.Context()).
- Engineers MUST NEVER perform raw, unselected channel sends (e.g., ch <- val) or unselected receives (<-ch) inside goroutines spawned within Chi HTTP/3 handlers.
- Engineers MUST multiplex all channel sends and receives with select blocks against ctx.Done() to abort execution instantly when a client cancels a QUIC stream.
- Services MUST orchestrate concurrent child tasks via golang.org/x/sync/errgroup bound to r.Context() to guarantee that subroutines terminate before the outer HTTP handler exits.
- Code SHOULD inspect errors returned by http.ResponseWriter.Write() and http.Flusher.Flush(); upon error or QUIC stream reset, the handler MUST abort pipeline processing immediately.
- Components NEVER use context.Background() or context.TODO() in Chi HTTP/3 request handlers unless explicitly dispatching detached background jobs via an isolated worker pool or queue.

## Bad vs Good Implementations
### QUIC Stream Cancellation Propagation with ErrGroup and Multiplexed Channels

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The producer goroutine communicates via an unbuffered channel without checking r.Context().Done(). If the QUIC client issues a RESET_STREAM, the Chi handler's context cancels, the consumer loop terminates on write error, and the producer goroutine deadlocks indefinitely trying to send to the orphaned unbuffered channel.
```go
package handlers

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

func StreamPipeline(r chi.Router) {
	r.Get("/events", func(w http.ResponseWriter, r *http.Request) {
		ch := make(chan []byte) // Unbuffered channel

		// ANTI-PATTERN: Goroutine does not bind sends to r.Context().Done().
		// When a QUIC client resets the stream, the handler exits, the consumer dies,
		// and this goroutine blocks on 'ch <- chunk' forever, leaking memory and workers.
		go func() {
			defer close(ch)
			for i := 0; i < 1000; i++ {
				chunk := generateData(i)
				ch <- chunk // Deadlocks here upon client QUIC RESET_STREAM
			}
		}()

		flusher, _ := w.(http.Flusher)
		for chunk := range ch {
			_, err := w.Write(chunk)
			if err != nil {
				return // Exits handler, abandoning producer goroutine
			}
			flusher.Flush()
		}
	})
}
```

#### Production Standard (Correct)
> **Standard**: The pipeline utilizes errgroup.WithContext tied to the Chi request context. Both the consumer and producer monitor ctx.Done(). When a client triggers a QUIC stream reset, the producer instantly unblocks from the select statement, tears down its stack, and prevents goroutine or memory leaks.
```go
package handlers

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

func StreamPipeline(r chi.Router) {
	r.Get("/events", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		g, groupCtx := errgroup.WithContext(ctx)
		ch := make(chan []byte)

		// Worker routine bounded by errgroup and QUIC stream context
		g.Go(func() error {
			defer close(ch)
			for i := 0; i < 1000; i++ {
				chunk, err := generateDataWithContext(groupCtx, i)
				if err != nil {
					return err
				}

				// INVARIANT: Every channel send is multiplexed with groupCtx.Done()
				select {
				case <-groupCtx.Done():
					return groupCtx.Err()
				case ch <- chunk:
				}
			}
			return nil
		})

		flusher, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/octet-stream")
		for {
			select {
			case <-ctx.Done():
				// QUIC stream reset: wait for child goroutine to cleanly exit
				_ = g.Wait()
				return
			case chunk, open := <-ch:
				if !open {
					_ = g.Wait()
					return
				}
				if _, err := w.Write(chunk); err != nil {
					_ = g.Wait()
					return
				}
				flusher.Flush()
			}
		}
	})
}
```

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: Deterministic Child Goroutine and Channel Teardown on QUIC Stream Reset in Go Chi HTTP/3

Deterministic Child Goroutine and Channel Teardown on QUIC Stream Reset in Go Chi HTTP/3 defines an industrial-grade behavioral standard for backend engineering. Guarantees immediate and deterministic teardown of child worker goroutines, fan-out pipelines, and unbuffered channel interactions when receiving client-initiated QUIC stream resets (RESET_STREAM/STOP_SENDING). Mandates strict context propagation from Chi HTTP/3 request contexts and forbids unmultiplexed channel operations that cause permanent goroutine leaks. 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: Permanent Goroutine Leaks and Channel Deadlocks via Unguarded 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 DriftPermanent Goroutine Leaks and Channel Deadlocks via Unguarded 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 child worker goroutines or derive child contexts using context.WithCancelCause(r.Context()).

Engineers MUST ALWAYS pass r.Context() directly to child worker goroutines or derive child contexts using context.WithCancelCause(r.Context()).

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 NEVER perform raw, unselected channel sends (e.g., ch <- val) or unselected receives (<-ch) inside goroutines spawned within Chi HTTP/3 handlers.

Engineers MUST NEVER perform raw, unselected channel sends (e.g., ch <- val) or unselected receives (<-ch) inside goroutines spawned within Chi HTTP/3 handlers.

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 multiplex all channel sends and receives with select blocks against ctx.Done() to abort execution instantly when a client cancels a QUIC stream.

Engineers MUST multiplex all channel sends and receives with select blocks against ctx.Done() to abort execution instantly when a client cancels a QUIC 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.
4

Services MUST orchestrate concurrent child tasks via golang.org/x/sync/errgroup bound to r.Context() to guarantee that subroutines terminate before the outer HTTP handler exits.

Services MUST orchestrate concurrent child tasks via golang.org/x/sync/errgroup bound to r.Context() to guarantee that subroutines terminate before the outer HTTP handler exits.

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

Code SHOULD inspect errors returned by http.ResponseWriter.Write() and http.Flusher.Flush()

Code SHOULD inspect errors returned by http.ResponseWriter.Write() and http.Flusher.Flush(); upon error or QUIC stream reset, the handler MUST abort pipeline processing 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.
6

Components NEVER use context.Background() or context.TODO() in Chi HTTP/3 request handlers unless explicitly dispatching detached background jobs via an isolated worker pool or queue.

Components NEVER use context.Background() or context.TODO() in Chi HTTP/3 request handlers unless explicitly dispatching detached background jobs via an isolated worker pool or queue.

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 Deterministic Child Goroutine and Channel Teardown on QUIC Stream Reset in Go Chi HTTP/3 critical for AI coding assistants?

Guarantees immediate and deterministic teardown of child worker goroutines, fan-out pipelines, and unbuffered channel interactions when receiving client-initiated QUIC stream resets (RESET_STREAM/STOP_SENDING). Mandates strict context propagation from Chi HTTP/3 request contexts and forbids unmultiplexed channel operations that cause permanent goroutine leaks. 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 (Permanent Goroutine Leaks and Channel Deadlocks via Unguarded 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

Deterministic