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

Chi 5.x Context Deadline Propagation & Outbound Transport Poison Fencing

Enforces strict inbound-to-outbound context deadline propagation in Go Chi 5.x handlers paired with deterministic HTTP transport connection fencing. Prevents poisoned or desynchronized TCP sockets from being recycled into the runtime epoll idle pool when client contexts abort mid-flight.

Prohibited Anti-Pattern: Unconditional Body Draining and Default Transport Reuse on Cancelled Inbound Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Chi 5.x Context Deadline Propagation & Outbound Transport Poison Fencing - Enforces strict inbound-to-outbound context deadline propagation in Go Chi 5.x handlers paired with deterministic HTTP transport connection fencing. Prevents poisoned or desynchronized TCP sockets from being recycled into the runtime epoll idle pool when client contexts abort mid-flight.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-context-deadline-transport-poison-fence"
---

# Chi 5.x Context Deadline Propagation & Outbound Transport Poison Fencing

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unconditional Body Draining and Default Transport Reuse on Cancelled Inbound Contexts

## System Constraints
You are a Principal Software Architect enforcing Go Chi 5.x Context Deadline Propagation and HTTP Transport Connection Poison Fencing. Mandate strict context inheritance with bounded timeouts, forbid http.DefaultClient/http.DefaultTransport usage, and mandate deterministic connection eviction when context cancellations occur mid-stream to avoid epoll socket starvation.

## Strict Guidelines
- Engineers MUST ALWAYS derive outbound downstream request contexts from the Chi handler's inbound `r.Context()` using bounded timeouts via `context.WithTimeoutCause` or `context.WithDeadlineCause`.
- Engineers MUST NOT unconditionally drain `resp.Body` via `io.Copy(io.Discard, ...)` if `ctx.Err() != nil` or an I/O error occurred, as attempting to drain cancelled streams stalls goroutines and risks returning desynchronized sockets to the transport pool.
- Engineers MUST ensure `resp.Body.Close()` is executed immediately without body draining whenever `ctx.Err() != nil`, forcing `net/http.Transport` to tear down the underlying TCP connection rather than recycling a tainted socket.
- Services MUST configure custom `*http.Transport` instances with explicit `MaxIdleConns`, `MaxIdleConnsPerHost`, `IdleConnTimeout`, `ResponseHeaderTimeout`, and `TLSHandshakeTimeout` instead of relying on `http.DefaultClient` or `http.DefaultTransport`.
- Components NEVER execute outbound network calls inside Chi handlers without structured telemetry, context cancellation checks, and explicit buffer exhaustion limits.

## Bad vs Good Implementations
### Outbound Service Call within Go Chi 5.x Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using http.DefaultClient shares unbounded epoll connection pools. Draining resp.Body via io.Copy when the context may have aborted can block indefinitely or return corrupted HTTP pipelining state to the transport pool, poisoning subsequent requests across the service.
```go
package handler

import (
	"io"
	"net/http"

	"github.com/go-chi/chi/v5"
)

func RegisterRoutes(r chi.Router) {
	r.Get("/data", FetchDownstreamData)
}

func FetchDownstreamData(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: DefaultClient uses unbounded shared transport.
	// Context is used directly without timeout boundaries.
	req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, "http://downstream.internal/api", nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	// ANTI-PATTERN: Blindly draining body even if context is already aborted,
	// causing epoll hangs and recycling dirty/desynced connections to the pool.
	_, _ = io.Copy(io.Discard, resp.Body)
	w.WriteHeader(http.StatusOK)
}
```

#### Production Standard (Correct)
> **Standard**: Defines an isolated, strictly bounded Transport pool. Attaches a bounded context timeout, and conditionally fences connection recycling: if context cancellation occurred, the body is closed without reading, forcing transport to discard the tainted TCP socket rather than keeping it in epoll idle state.
```go
package handler

import (
	"context"
	"errors"
	"io"
	"net"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"
)

var customTransport = &http.Transport{
	Proxy: http.ProxyFromEnvironment,
	DialContext: (&net.Dialer{
		Timeout:   5 * time.Second,
		KeepAlive: 30 * time.Second,
	}).DialContext,
	MaxIdleConns:          100,
	MaxIdleConnsPerHost:   10,
	IdleConnTimeout:       90 * time.Second,
	TLSHandshakeTimeout:   5 * time.Second,
	ResponseHeaderTimeout: 5 * time.Second,
	ExpectContinueTimeout: 1 * time.Second,
}

var fencedClient = &http.Client{
	Transport: customTransport,
}

func RegisterRoutes(r chi.Router) {
	r.Get("/data", FetchDownstreamData)
}

func FetchDownstreamData(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeoutCause(
		r.Context(),
		3*time.Second,
		errors.New("downstream fetch deadline exceeded"),
	)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://downstream.internal/api", nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	resp, err := fencedClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}

	defer func() {
		// FENCE: If the context was cancelled or expired mid-flight,
		// DO NOT drain the stream. Close immediately to force TCP RST / drop socket,
		// preventing a desynchronized connection from re-entering the epoll idle pool.
		if ctx.Err() != nil {
			_ = resp.Body.Close()
			return
		}
		// Safely drain only if clean context persists, capping drain read limit.
		_, _ = io.CopyN(io.Discard, resp.Body, 64*1024)
		_ = resp.Body.Close()
	}()

	if resp.StatusCode != http.StatusOK {
		http.Error(w, "downstream error", http.StatusBadGateway)
		return
	}
	w.WriteHeader(http.StatusOK)
}
```

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: Chi 5.x Context Deadline Propagation & Outbound Transport Poison Fencing

Chi 5.x Context Deadline Propagation & Outbound Transport Poison Fencing defines an industrial-grade behavioral standard for backend engineering. Enforces strict inbound-to-outbound context deadline propagation in Go Chi 5.x handlers paired with deterministic HTTP transport connection fencing. Prevents poisoned or desynchronized TCP sockets from being recycled into the runtime epoll idle pool when client contexts abort mid-flight. 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: Unconditional Body Draining and Default Transport Reuse on Cancelled Inbound Contexts 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 DriftUnconditional Body Draining and Default Transport Reuse on Cancelled Inbound ContextsCritical
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 derive outbound downstream request contexts from the Chi handler's inbound `r.Context()` using bounded timeouts via `context.WithTimeoutCause` or `context.WithDeadlineCause`.

Engineers MUST ALWAYS derive outbound downstream request contexts from the Chi handler's inbound `r.Context()` using bounded timeouts via `context.WithTimeoutCause` or `context.WithDeadlineCause`.

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 unconditionally drain `resp.Body` via `io.Copy(io.Discard, ...)` if `ctx.Err() != nil` or an I/O error occurred, as attempting to drain cancelled streams stalls goroutines and risks returning desynchronized sockets to the transport pool.

Engineers MUST NOT unconditionally drain `resp.Body` via `io.Copy(io.Discard, ...)` if `ctx.Err() != nil` or an I/O error occurred, as attempting to drain cancelled streams stalls goroutines and risks returning desynchronized sockets to the transport pool.

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 ensure `resp.Body.Close()` is executed immediately without body draining whenever `ctx.Err() != nil`, forcing `net/http.Transport` to tear down the underlying TCP connection rather than recycling a tainted socket.

Engineers MUST ensure `resp.Body.Close()` is executed immediately without body draining whenever `ctx.Err() != nil`, forcing `net/http.Transport` to tear down the underlying TCP connection rather than recycling a tainted socket.

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 configure custom `*http.Transport` instances with explicit `MaxIdleConns`, `MaxIdleConnsPerHost`, `IdleConnTimeout`, `ResponseHeaderTimeout`, and `TLSHandshakeTimeout` instead of relying on `http.DefaultClient` or `http.DefaultTransport`.

Services MUST configure custom `*http.Transport` instances with explicit `MaxIdleConns`, `MaxIdleConnsPerHost`, `IdleConnTimeout`, `ResponseHeaderTimeout`, and `TLSHandshakeTimeout` instead of relying on `http.DefaultClient` or `http.DefaultTransport`.

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 execute outbound network calls inside Chi handlers without structured telemetry, context cancellation checks, and explicit buffer exhaustion limits.

Components NEVER execute outbound network calls inside Chi handlers without structured telemetry, context cancellation checks, and explicit buffer exhaustion limits.

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 Chi 5.x Context Deadline Propagation & Outbound Transport Poison Fencing critical for AI coding assistants?

Enforces strict inbound-to-outbound context deadline propagation in Go Chi 5.x handlers paired with deterministic HTTP transport connection fencing. Prevents poisoned or desynchronized TCP sockets from being recycled into the runtime epoll idle pool when client contexts abort mid-flight. 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 (Unconditional Body Draining and Default Transport Reuse on Cancelled Inbound Contexts) 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

Chi