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

Go Chi HTTP/2 SSE Stream Lifecycle and Context Cancellation Standard

Enforces deterministic context cancellation propagation, unbuffered channel drain safeguards, and explicit client termination handling for HTTP/2 and Server-Sent Events (SSE) handlers in Go Chi. Eliminates silent goroutine leaks, orphan producers, and socket descriptor exhaustion triggered by premature client TCP/TLS RST or HTTP/2 stream cancellations.

Prohibited Anti-Pattern: Unbounded Goroutine Spawning and Channel Deadlocks on Abrupt HTTP/2 Stream Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi HTTP/2 SSE Stream Lifecycle and Context Cancellation Standard - Enforces deterministic context cancellation propagation, unbuffered channel drain safeguards, and explicit client termination handling for HTTP/2 and Server-Sent Events (SSE) handlers in Go Chi. Eliminates silent goroutine leaks, orphan producers, and socket descriptor exhaustion triggered by premature client TCP/TLS RST or HTTP/2 stream cancellations.
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-http2-sse-stream-lifecycle-guardrail"
---

# Go Chi HTTP/2 SSE Stream Lifecycle and Context Cancellation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unbounded Goroutine Spawning and Channel Deadlocks on Abrupt HTTP/2 Stream Cancellation

## System Constraints
You are a Principal Backend Architect specializing in resilient Go networked microservices. Mandate strict goroutine lifecycle bounds and context-driven termination semantics across all Go Chi HTTP/2 and Server-Sent Events (SSE) handlers. Reject any code pattern where producer goroutines or streaming loops survive client disconnection or fail to handle stream resets via r.Context().Done().

## Strict Guidelines
- Engineers MUST ALWAYS bind long-lived streaming loops to `r.Context().Done()` to instantly react to HTTP/2 RST_STREAM frames and TCP terminations.
- Engineers MUST NOT spawn unbounded background goroutines inside HTTP stream handlers without tying their lifecycle to the request context or managing them with an explicit cancellation group.
- Engineers MUST ALWAYS use `http.NewResponseController(w)` (Go 1.20+) to handle flushing and deadline management rather than raw, unchecked `http.Flusher` interface assertions.
- Code MUST ensure all channel sends between background producers and the streaming response loop evaluate `select { case <-ctx.Done(): return; case ch <- data: }` to prevent permanent goroutine deadlocks when clients terminate abruptly.
- Services MUST explicitly set SSE transport headers (`Content-Type: text/event-stream`, `Cache-Control: no-cache`, `Connection: keep-alive`, `X-Accel-Buffering: no`) prior to the first response write and flush.
- Components NEVER assume write success without verifying write and flush error returns; broken pipe (`EPIPE`) or connection reset (`ECONNRESET`) errors must immediately terminate handler execution.

## Bad vs Good Implementations
### HTTP/2 SSE Streaming Handler with Goroutine Leak vs. Deterministic Lifecycle Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker goroutine does not listen to `r.Context().Done()`. When a client drops the connection or sends an HTTP/2 RST_STREAM, the handler loop terminates on write error, but the producer goroutine blocks indefinitely attempting to send to `dataChan`, leading to fatal goroutine leakage and memory bloat.
```go
package api

import (
	"fmt"
	"net/http"
	"time"
)

func BadStreamHandler(w http.ResponseWriter, r *http.Request) {
	flusher, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")

	// ANTI-PATTERN: Worker spawned without ctx propagation or bound termination.
	// If the client closes the connection, this goroutine leaks forever on unbuffered send.
	dataChan := make(chan string)
	go func() {
		i := 0
		for {
			time.Sleep(500 * time.Millisecond)
			i++
			dataChan <- fmt.Sprintf("event payload %d", i) // BLOCKS INDEFINITELY ON DISCONNECT
		}
	}()

	for {
		msg := <-dataChan
		_, err := fmt.Fprintf(w, "data: %s\n\n", msg)
		if err != nil {
			// Flusher is never called; broken pipe ignored; goroutine orphaned
			return
		}
		flusher.Flush()
	}
}
```

#### Production Standard (Correct)
> **Standard**: Employs Go 1.20+ `http.NewResponseController`, sets resilient headers for proxy bypass, binds child producers to a derived `producerCtx`, guards all channel sends with `select <-producerCtx.Done()`, and halts cleanly upon client disconnects or broken pipes, guaranteeing zero leaked goroutines.
```go
package api

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"syscall"
	"time"
)

func GoodStreamHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	rc := http.NewResponseController(w)

	h := w.Header()
	h.Set("Content-Type", "text/event-stream")
	h.Set("Cache-Control", "no-cache, no-transform")
	h.Set("Connection", "keep-alive")
	h.Set("X-Accel-Buffering", "no")

	// Flush headers immediately
	if err := rc.Flush(); err != nil {
		return
	}

	dataChan := make(chan string, 16)
	producerCtx, cancel := context.WithCancel(ctx)
	defer cancel()

	go func() {
		ticker := time.NewTicker(500 * time.Millisecond)
		defer ticker.Stop()
		i := 0

		for {
			select {
			case <-producerCtx.Done():
				return
			case <-ticker.C:
				i++
				select {
				case <-producerCtx.Done():
					return
				case dataChan <- fmt.Sprintf("event payload %d", i):
				}
			}
		}
	}()

	for {
		select {
		case <-ctx.Done():
			return
		case msg, ok := <-dataChan:
			if !ok {
				return
			}
			if _, err := fmt.Fprintf(w, "data: %s\n\n", msg); err != nil {
				return
			}
			if err := rc.Flush(); err != nil {
				if errors.Is(err, syscall.EPIPE) || errors.Is(err, syscall.ECONNRESET) {
					return
				}
				return
			}
		}
	}
}
```

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/2 SSE Stream Lifecycle and Context Cancellation Standard

Go Chi HTTP/2 SSE Stream Lifecycle and Context Cancellation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic context cancellation propagation, unbuffered channel drain safeguards, and explicit client termination handling for HTTP/2 and Server-Sent Events (SSE) handlers in Go Chi. Eliminates silent goroutine leaks, orphan producers, and socket descriptor exhaustion triggered by premature client TCP/TLS RST or HTTP/2 stream cancellations. 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: Unbounded Goroutine Spawning and Channel Deadlocks on Abrupt HTTP/2 Stream Cancellation 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 DriftUnbounded Goroutine Spawning and Channel Deadlocks on Abrupt HTTP/2 Stream CancellationCritical
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 long-lived streaming loops to `r.Context().Done()` to instantly react to HTTP/2 RST_STREAM frames and TCP terminations.

Engineers MUST ALWAYS bind long-lived streaming loops to `r.Context().Done()` to instantly react to HTTP/2 RST_STREAM frames and TCP terminations.

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 unbounded background goroutines inside HTTP stream handlers without tying their lifecycle to the request context or managing them with an explicit cancellation group.

Engineers MUST NOT spawn unbounded background goroutines inside HTTP stream handlers without tying their lifecycle to the request context or managing them with an explicit cancellation group.

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 ALWAYS use `http.NewResponseController(w)` (Go 1.20+) to handle flushing and deadline management rather than raw, unchecked `http.Flusher` interface assertions.

Engineers MUST ALWAYS use `http.NewResponseController(w)` (Go 1.20+) to handle flushing and deadline management rather than raw, unchecked `http.Flusher` interface assertions.

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

Code MUST ensure all channel sends between background producers and the streaming response loop evaluate `select { case <-ctx.Done()

Code MUST ensure all channel sends between background producers and the streaming response loop evaluate `select { case <-ctx.Done(): return; case ch <- data: }` to prevent permanent goroutine deadlocks when clients terminate abruptly.

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

Services MUST explicitly set SSE transport headers (`Content-Type

Services MUST explicitly set SSE transport headers (`Content-Type: text/event-stream`, `Cache-Control: no-cache`, `Connection: keep-alive`, `X-Accel-Buffering: no`) prior to the first response write and flush.

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 assume write success without verifying write and flush error returns

Components NEVER assume write success without verifying write and flush error returns; broken pipe (`EPIPE`) or connection reset (`ECONNRESET`) errors must immediately terminate handler execution.

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/2 SSE Stream Lifecycle and Context Cancellation Standard critical for AI coding assistants?

Enforces deterministic context cancellation propagation, unbuffered channel drain safeguards, and explicit client termination handling for HTTP/2 and Server-Sent Events (SSE) handlers in Go Chi. Eliminates silent goroutine leaks, orphan producers, and socket descriptor exhaustion triggered by premature client TCP/TLS RST or HTTP/2 stream cancellations. 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 (Unbounded Goroutine Spawning and Channel Deadlocks on Abrupt HTTP/2 Stream Cancellation) 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