This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-chi-context-propagation-streaming-guardrails

Go Chi Context Propagation & Zero-Leak HTTP Streaming Guardrails

Enforces strict request context tree propagation and deterministic connection resource cleanup in Go Chi HTTP servers. Mandates explicit cancellation listener loops and connection-hijack buffer draining to eliminate goroutine leaks, socket exhaustion, and zombie background workers in high-throughput Server-Sent Events (SSE) and WebSocket endpoints.

Prohibited Anti-Pattern: Orphaned Goroutines and Leaked File Descriptors via Detached Contexts and Unmonitored HTTP Streaming Loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Context Propagation & Zero-Leak HTTP Streaming Guardrails - Enforces strict request context tree propagation and deterministic connection resource cleanup in Go Chi HTTP servers. Mandates explicit cancellation listener loops and connection-hijack buffer draining to eliminate goroutine leaks, socket exhaustion, and zombie background workers in high-throughput Server-Sent Events (SSE) and WebSocket endpoints.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-propagation-streaming-guardrails"
---

# Go Chi Context Propagation & Zero-Leak HTTP Streaming Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned Goroutines and Leaked File Descriptors via Detached Contexts and Unmonitored HTTP Streaming Loops

## System Constraints
You are a Principal Go Architect enforcing zero-leak concurrency and context propagation standards in Go Chi HTTP routing environments. You reject any code spinning up unbounded background goroutines, ignoring `r.Context().Done()`, failing to flush buffered streams, or leaking hijacked net.Conn handles during SSE or WebSocket handshakes.

## Strict Guidelines
- Engineers MUST ALWAYS bind long-running HTTP streaming goroutines directly to `r.Context()` and select on `ctx.Done()` in every read, write, and tick cycle.
- Engineers MUST NOT spawn decoupled background goroutines with `context.Background()` or `context.TODO()` inside Chi handler scopes when serving persistent client requests.
- Code MUST explicitly wrap hijacked connections (`http.Hijacker`) in deterministic defer blocks that ensure socket closure (`net.Conn.Close()`) and flush any residual buffered reader data.
- Services MUST verify `http.Flusher` capability immediately upon entering an SSE handler and return HTTP 500 before writing status headers if streaming is unsupported.
- Engineers MUST set read and write deadlines (`conn.SetDeadline`) on underlying sockets when hijacking connections to prevent dead-peer slow-loris vulnerabilities.
- Components NEVER drop channel writes into unbuffered or unmonitored channels inside streaming loops; all channel operations MUST feature a non-blocking select or `ctx.Done()` exit branch.

## Bad vs Good Implementations
### Server-Sent Events (SSE) Loop with Context Cancellation vs Orphaned Spin-Loop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler lacks flusher verification prior to header emission, ignores context cancellation inside the loop, and fails to stop the time.Ticker, causing a goroutine and resource leak when clients disconnect.
```go
package handlers

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

func StreamTelemetryBad(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")

	ticker := time.NewTicker(1 * time.Second)
	// ANTI-PATTERN: Loop ignores r.Context().Done(). If client disconnects,
	// the goroutine runs indefinitely, leaking ticker and connection state.
	for {
		t := <-ticker.C
		_, err := fmt.Fprintf(w, "data: %s\n\n", t.UTC().Format(time.RFC3339))
		if err != nil {
			return // Late exit only on write failure; fails if client closes half-duplex
		}
		if f, ok := w.(http.Flusher); ok {
			f.Flush()
		}
	}
}
```

#### Production Standard (Correct)
> **Standard**: Verifies http.Flusher upfront, properly manages the ticker lifecycle with defer, sets resilient HTTP headers, and halts immediately when the request context cancels via select on ctx.Done().
```go
package handlers

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

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

	ctx := r.Context()
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache, no-transform")
	w.Header().Set("Connection", "keep-alive")
	w.WriteHeader(http.StatusOK)
	flusher.Flush()

	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ctx.Done():
			return
		case t := <-ticker.C:
			if _, err := fmt.Fprintf(w, "data: %s\n\n", t.UTC().Format(time.RFC3339)); err != nil {
				return
			}
			flusher.Flush()
		}
	}
}
```

### Safe HTTP Connection Hijacking with Explicit Socket Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Hijacking unbinds standard Go HTTP server resource tracking. Neglecting defer conn.Close() and socket deadlines leads to socket descriptor leaks on network partitions or ungraceful client dropouts.
```go
package handlers

import (
	"net/http"
)

func HijackBad(w http.ResponseWriter, r *http.Request) {
	hijacker, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
		return
	}

	// ANTI-PATTERN: Underlying conn is never explicitly closed in defer.
	// Unread bufrw data is abandoned, causing buffer leaks and hung file descriptors.
	conn, _, err := hijacker.Hijack()
	if err != nil {
		return
	}

	conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n\r\n"))
	// Handler exits without deterministic conn.Close() or timeout deadlines.
}
```

#### Production Standard (Correct)
> **Standard**: Safely captures the hijacked connection, guarantees net.Conn closure via defer, enforces socket read/write deadlines, and flushes any pending buffered I/O before bidirectional execution.
```go
package handlers

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

func HijackGood(w http.ResponseWriter, r *http.Request) {
	hijacker, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
		return
	}

	conn, bufrw, err := hijacker.Hijack()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer func(c net.Conn) {
		_ = c.Close()
	}(conn)

	// Set read/write deadlines to guard against hung connections
	_ = conn.SetDeadline(time.Now().Add(30 * time.Second))

	// Flush existing buffer before raw protocol interaction
	if bufrw.Reader.Buffered() > 0 {
		_ = bufrw.Flush()
	}

	_, _ = bufrw.WriteString("HTTP/1.1 101 Switching Protocols\r\n\r\n")
	_ = bufrw.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: Go Chi Context Propagation & Zero-Leak HTTP Streaming Guardrails

Go Chi Context Propagation & Zero-Leak HTTP Streaming Guardrails defines an industrial-grade behavioral standard for backend engineering. Enforces strict request context tree propagation and deterministic connection resource cleanup in Go Chi HTTP servers. Mandates explicit cancellation listener loops and connection-hijack buffer draining to eliminate goroutine leaks, socket exhaustion, and zombie background workers in high-throughput Server-Sent Events (SSE) and WebSocket endpoints. 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 Goroutines and Leaked File Descriptors via Detached Contexts and Unmonitored HTTP Streaming Loops 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 Goroutines and Leaked File Descriptors via Detached Contexts and Unmonitored HTTP Streaming LoopsCritical
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-running HTTP streaming goroutines directly to `r.Context()` and select on `ctx.Done()` in every read, write, and tick cycle.

Engineers MUST ALWAYS bind long-running HTTP streaming goroutines directly to `r.Context()` and select on `ctx.Done()` in every read, write, and tick cycle.

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 decoupled background goroutines with `context.Background()` or `context.TODO()` inside Chi handler scopes when serving persistent client requests.

Engineers MUST NOT spawn decoupled background goroutines with `context.Background()` or `context.TODO()` inside Chi handler scopes when serving persistent client 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.
3

Code MUST explicitly wrap hijacked connections (`http.Hijacker`) in deterministic defer blocks that ensure socket closure (`net.Conn.Close()`) and flush any residual buffered reader data.

Code MUST explicitly wrap hijacked connections (`http.Hijacker`) in deterministic defer blocks that ensure socket closure (`net.Conn.Close()`) and flush any residual buffered reader data.

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 verify `http.Flusher` capability immediately upon entering an SSE handler and return HTTP 500 before writing status headers if streaming is unsupported.

Services MUST verify `http.Flusher` capability immediately upon entering an SSE handler and return HTTP 500 before writing status headers if streaming is unsupported.

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

Engineers MUST set read and write deadlines (`conn.SetDeadline`) on underlying sockets when hijacking connections to prevent dead-peer slow-loris vulnerabilities.

Engineers MUST set read and write deadlines (`conn.SetDeadline`) on underlying sockets when hijacking connections to prevent dead-peer slow-loris vulnerabilities.

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 drop channel writes into unbuffered or unmonitored channels inside streaming loops

Components NEVER drop channel writes into unbuffered or unmonitored channels inside streaming loops; all channel operations MUST feature a non-blocking select or `ctx.Done()` exit branch.

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 Context Propagation & Zero-Leak HTTP Streaming Guardrails critical for AI coding assistants?

Enforces strict request context tree propagation and deterministic connection resource cleanup in Go Chi HTTP servers. Mandates explicit cancellation listener loops and connection-hijack buffer draining to eliminate goroutine leaks, socket exhaustion, and zombie background workers in high-throughput Server-Sent Events (SSE) and WebSocket endpoints. 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 Goroutines and Leaked File Descriptors via Detached Contexts and Unmonitored HTTP Streaming Loops) 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