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

Go Chi Zero-Allocation Context-Propagated Deadline Enforcement

Enforces strict downstream deadline propagation, zero-allocation context key architectures, and fail-fast cancellation across Go Chi HTTP routing chains. Eliminates runaway background goroutines and thread pool exhaustion during cascading downstream microservice outages. Guarantees that request lifetimes, tracing baggage, and database/RPC calls unconditionally respect parent context deadlines without escaping to the heap.

Prohibited Anti-Pattern: Orphaned Request Contexts, Heap-Allocated Context Keys, and Unbounded Runaway Goroutines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Zero-Allocation Context-Propagated Deadline Enforcement - Enforces strict downstream deadline propagation, zero-allocation context key architectures, and fail-fast cancellation across Go Chi HTTP routing chains. Eliminates runaway background goroutines and thread pool exhaustion during cascading downstream microservice outages. Guarantees that request lifetimes, tracing baggage, and database/RPC calls unconditionally respect parent context deadlines without escaping to the heap.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-zero-alloc-deadline-enforcement"
---

# Go Chi Zero-Allocation Context-Propagated Deadline Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Orphaned Request Contexts, Heap-Allocated Context Keys, and Unbounded Runaway Goroutines

## System Constraints
You are a Principal Go Systems Architect enforcing strict Chi HTTP middleware standards. You must mandate zero-allocation context value patterns, ubiquitous deadline propagation, and absolute cancellation handling on all outbound I/O to prevent cascading goroutine leaks and memory pressure.

## Strict Guidelines
- Engineers MUST ALWAYS propagate `r.Context()` directly to database queries, RPC clients, and outbound HTTP requests without uncoupling the parent deadline.
- Engineers MUST NOT instantiate `context.Background()` or `context.TODO()` inside HTTP handler paths or middleware to perform work tied to an incoming request.
- Engineers MUST define context keys as private, zero-size types (e.g., `type contextKey struct{}`) to guarantee zero heap allocations during `context.WithValue` operations.
- Middlewares MUST establish an absolute ceiling deadline using `context.WithTimeoutCause` or Chi's `middleware.Timeout` and verify cancellation via `context.Cause(ctx)`.
- Asynchronous tasks spawned from handlers MUST leverage structured concurrency (e.g., `errgroup.Group` derived from `r.Context()`), and MUST NEVER outlive parent request budgets unless explicitly offloaded to a persistent worker queue with its own decoupled lifecycle.
- Handlers MUST ALWAYS drain and close incoming request bodies via `io.Copy(io.Discard, r.Body)` and `r.Body.Close()` before timing out to facilitate TCP connection reuse without goroutine starvation.

## Bad vs Good Implementations
### Context Deadline Propagation and Zero-Alloc Context Key

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses an unallocated string key forcing runtime boxing onto the heap, discards the incoming request deadline by substituting `context.Background()`, and spawns an unbounded goroutine that leaks sockets and runtime threads when upstream services degrade.
```go
package handlers

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

// Anti-pattern: string context key causes heap allocation
const UserIDKey = "user_id"

func BadUserHandler(w http.ResponseWriter, r *http.Request) {
	// Anti-pattern: Heap allocation via string key and dynamic boxing
	ctx := context.WithValue(r.Context(), UserIDKey, r.Header.Get("X-User-ID"))

	// Anti-pattern: Unbounded goroutine with detached context.Background()
	go func() {
		// If the client disconnects or times out, this network call hangs indefinitely
		req, _ := http.NewRequestWithContext(context.Background(), "GET", "http://upstream/profile", nil)
		resp, err := http.DefaultClient.Do(req)
		if err == nil {
			defer resp.Body.Close()
		}
	}()

	w.WriteHeader(http.StatusAccepted)
}
```

#### Production Standard (Correct)
> **Standard**: Implements a zero-allocation struct key, binds outbound HTTP execution directly to the bounded request context using `WithTimeoutCause`, ensures timely socket release via `defer resp.Body.Close()`, and properly maps context cancellations to HTTP 504 status codes without thread leaks.
```go
package handlers

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

// Zero-allocation context key guaranteed by empty struct
type userIDKey struct{}

var errRequestTimeout = errors.New("request processing deadline exceeded")

func GoodUserHandler(client *http.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Zero-allocation context attachment
		ctx := context.WithValue(r.Context(), userIDKey{}, r.Header.Get("X-User-ID"))

		// Enforce local deadline ceiling if parent context lacks one
		ctx, cancel := context.WithTimeoutCause(ctx, 3*time.Second, errRequestTimeout)
		defer cancel()

		req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://upstream/profile", http.NoBody)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		resp, err := client.Do(req)
		if err != nil {
			if errors.Is(ctx.Err(), context.Canceled) || errors.Is(context.Cause(ctx), errRequestTimeout) {
				http.Error(w, fmt.Sprintf("Gateway Timeout: %v", context.Cause(ctx)), http.StatusGatewayTimeout)
				return
			}
			http.Error(w, "Upstream Unavailable", http.StatusBadGateway)
			return
		}
		defer resp.Body.Close()

		w.WriteHeader(resp.StatusCode)
	}
}
```

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 Zero-Allocation Context-Propagated Deadline Enforcement

Go Chi Zero-Allocation Context-Propagated Deadline Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces strict downstream deadline propagation, zero-allocation context key architectures, and fail-fast cancellation across Go Chi HTTP routing chains. Eliminates runaway background goroutines and thread pool exhaustion during cascading downstream microservice outages. Guarantees that request lifetimes, tracing baggage, and database/RPC calls unconditionally respect parent context deadlines without escaping to the heap. 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 Request Contexts, Heap-Allocated Context Keys, and Unbounded Runaway Goroutines 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 Request Contexts, Heap-Allocated Context Keys, and Unbounded Runaway GoroutinesCritical
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()` directly to database queries, RPC clients, and outbound HTTP requests without uncoupling the parent deadline.

Engineers MUST ALWAYS propagate `r.Context()` directly to database queries, RPC clients, and outbound HTTP requests without uncoupling the parent deadline.

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 instantiate `context.Background()` or `context.TODO()` inside HTTP handler paths or middleware to perform work tied to an incoming request.

Engineers MUST NOT instantiate `context.Background()` or `context.TODO()` inside HTTP handler paths or middleware to perform work tied to an incoming request.

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 define context keys as private, zero-size types (e.g., `type contextKey struct{}`) to guarantee zero heap allocations during `context.WithValue` operations.

Engineers MUST define context keys as private, zero-size types (e.g., `type contextKey struct{}`) to guarantee zero heap allocations during `context.WithValue` operations.

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

Middlewares MUST establish an absolute ceiling deadline using `context.WithTimeoutCause` or Chi's `middleware.Timeout` and verify cancellation via `context.Cause(ctx)`.

Middlewares MUST establish an absolute ceiling deadline using `context.WithTimeoutCause` or Chi's `middleware.Timeout` and verify cancellation via `context.Cause(ctx)`.

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

Asynchronous tasks spawned from handlers MUST leverage structured concurrency (e.g., `errgroup.Group` derived from `r.Context()`), and MUST NEVER outlive parent request budgets unless explicitly offloaded to a persistent worker queue with its own decoupled lifecycle.

Asynchronous tasks spawned from handlers MUST leverage structured concurrency (e.g., `errgroup.Group` derived from `r.Context()`), and MUST NEVER outlive parent request budgets unless explicitly offloaded to a persistent worker queue with its own decoupled lifecycle.

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

Handlers MUST ALWAYS drain and close incoming request bodies via `io.Copy(io.Discard, r.Body)` and `r.Body.Close()` before timing out to facilitate TCP connection reuse without goroutine starvation.

Handlers MUST ALWAYS drain and close incoming request bodies via `io.Copy(io.Discard, r.Body)` and `r.Body.Close()` before timing out to facilitate TCP connection reuse without goroutine starvation.

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 Zero-Allocation Context-Propagated Deadline Enforcement critical for AI coding assistants?

Enforces strict downstream deadline propagation, zero-allocation context key architectures, and fail-fast cancellation across Go Chi HTTP routing chains. Eliminates runaway background goroutines and thread pool exhaustion during cascading downstream microservice outages. Guarantees that request lifetimes, tracing baggage, and database/RPC calls unconditionally respect parent context deadlines without escaping to the heap. 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 Request Contexts, Heap-Allocated Context Keys, and Unbounded Runaway Goroutines) 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