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-context-propagation

Go 1.24 Chi Context-Propagated HTTP/3 Stream Multiplexing Guardrail

Enforces strict context propagation and QUIC stream-cancellation handling in Go 1.24 Chi HTTP/3 services. Prevents orphaned background goroutine leaks and unbounded memory expansion when multiplexed QUIC client streams abruptly reset under heavy ingress load.

Prohibited Anti-Pattern: Spawning detached background workers or unmonitored channels from r.Context() during QUIC stream multiplexing resets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Chi Context-Propagated HTTP/3 Stream Multiplexing Guardrail - Enforces strict context propagation and QUIC stream-cancellation handling in Go 1.24 Chi HTTP/3 services. Prevents orphaned background goroutine leaks and unbounded memory expansion when multiplexed QUIC client streams abruptly reset under heavy ingress load.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-http3-quic-stream-context-propagation"
---

# Go 1.24 Chi Context-Propagated HTTP/3 Stream Multiplexing Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Spawning detached background workers or unmonitored channels from r.Context() during QUIC stream multiplexing resets

## System Constraints
You are a Principal Systems Engineer enforcing strict HTTP/3 (QUIC) stream lifecycle invariants on Go 1.24 Chi services. Mandate zero detached goroutine lifecycles, explicit context inheritance, and proper handling of QUIC stream cancellation signals across all Chi router middlewares and handlers.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` to all downstream I/O operations, database queries, and async workers spawned within a Chi HTTP handler.
- Engineers MUST NOT spawn detached goroutines (`go func()`) that consume `context.Background()` or `context.TODO()` for client-bound workloads, as abrupt HTTP/3 QUIC stream cancellations will fail to abort them.
- Code MUST monitor `ctx.Done()` alongside any blocking channel sends, mutex acquisitions, or multiplexed worker pools to immediately yield execution upon QUIC stream resets.
- Services MUST implement Chi-compatible timeout and cancellation middlewares that explicitly catch QUIC stream reset error frames (e.g., `quic.ApplicationError` or `quic.StreamErrorCode`) and abort cascading downstream requests.
- Components NEVER buffer unbounded streaming responses in memory when writing across HTTP/3 streams without periodically verifying client liveness via `http.ResponseController.Flush()` or `r.Context().Err()`.

## Bad vs Good Implementations
### Preventing Orphaned Goroutine Leaks on HTTP/3 QUIC Stream Reset

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an HTTP/3 client issues a QUIC RESET_STREAM frame or abruptly drops its UDP session, the Chi handler exits, but the spawned goroutine remains alive using context.Background(). Under heavy load, this triggers massive goroutine accumulation, CPU starvation, and memory exhaustion.
```go
package handlers

import (
	"context"
	"encoding/json"
	"net/http"
	"time"
)

func StreamProcessingHandler(w http.ResponseWriter, r *http.Request) {
	// BAD: Detached goroutine with context.Background ignores HTTP/3 stream cancellation
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
		defer cancel()

		result := expensiveComputation(ctx)
		_ = result
	}()

	w.WriteHeader(http.StatusAccepted)
	_ = json.NewEncoder(w).Encode(map[string]string{"status": "processing"})
}

func expensiveComputation(ctx context.Context) string {
	time.Sleep(5 * time.Second)
	return "done"
}
```

#### Production Standard (Correct)
> **Standard**: The worker goroutine receives r.Context() directly and actively monitors ctx.Done(). If the HTTP/3 QUIC stream is reset by the client or network, the context cancellation short-circuits execution instantly, preventing goroutine and memory leaks.
```go
package handlers

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"time"
)

func StreamProcessingHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	resultChan := make(chan string, 1)
	errChan := make(chan error, 1)

	go func() {
		res, err := expensiveComputation(ctx)
		if err != nil {
			errChan <- err
			return
		}
		resultChan <- res
	}()

	select {
	case <-ctx.Done():
		// QUIC stream reset or client disconnect propagates immediately
		return
	case err := <-errChan:
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	case res := <-resultChan:
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(map[string]string{"result": res})
	}
}

func expensiveComputation(ctx context.Context) (string, error) {
	select {
	case <-ctx.Done():
		return "", ctx.Err()
	case <-time.After(500 * time.Millisecond):
		return "done", nil
	}
}
```

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 1.24 Chi Context-Propagated HTTP/3 Stream Multiplexing Guardrail

Go 1.24 Chi Context-Propagated HTTP/3 Stream Multiplexing Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict context propagation and QUIC stream-cancellation handling in Go 1.24 Chi HTTP/3 services. Prevents orphaned background goroutine leaks and unbounded memory expansion when multiplexed QUIC client streams abruptly reset under heavy ingress load. 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: Spawning detached background workers or unmonitored channels from r.Context() during QUIC stream multiplexing 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 DriftSpawning detached background workers or unmonitored channels from r.Context() during QUIC stream multiplexing 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 propagate `r.Context()` to all downstream I/O operations, database queries, and async workers spawned within a Chi HTTP handler.

Engineers MUST ALWAYS propagate `r.Context()` to all downstream I/O operations, database queries, and async workers spawned within a Chi HTTP handler.

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 goroutines (`go func()`) that consume `context.Background()` or `context.TODO()` for client-bound workloads, as abrupt HTTP/3 QUIC stream cancellations will fail to abort them.

Engineers MUST NOT spawn detached goroutines (`go func()`) that consume `context.Background()` or `context.TODO()` for client-bound workloads, as abrupt HTTP/3 QUIC stream cancellations will fail to abort them.

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 monitor `ctx.Done()` alongside any blocking channel sends, mutex acquisitions, or multiplexed worker pools to immediately yield execution upon QUIC stream resets.

Code MUST monitor `ctx.Done()` alongside any blocking channel sends, mutex acquisitions, or multiplexed worker pools to immediately yield execution upon QUIC stream resets.

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 implement Chi-compatible timeout and cancellation middlewares that explicitly catch QUIC stream reset error frames (e.g., `quic.ApplicationError` or `quic.StreamErrorCode`) and abort cascading downstream requests.

Services MUST implement Chi-compatible timeout and cancellation middlewares that explicitly catch QUIC stream reset error frames (e.g., `quic.ApplicationError` or `quic.StreamErrorCode`) and abort cascading downstream requests.

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 unbounded streaming responses in memory when writing across HTTP/3 streams without periodically verifying client liveness via `http.ResponseController.Flush()` or `r.Context().Err()`.

Components NEVER buffer unbounded streaming responses in memory when writing across HTTP/3 streams without periodically verifying client liveness via `http.ResponseController.Flush()` or `r.Context().Err()`.

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 Context-Propagated HTTP/3 Stream Multiplexing Guardrail critical for AI coding assistants?

Enforces strict context propagation and QUIC stream-cancellation handling in Go 1.24 Chi HTTP/3 services. Prevents orphaned background goroutine leaks and unbounded memory expansion when multiplexed QUIC client streams abruptly reset under heavy ingress load. 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 (Spawning detached background workers or unmonitored channels from r.Context() during QUIC stream multiplexing 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