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

Go Chi Zero-Allocation Context Value Propagation

Enforces single-allocation pointer propagation for request-scoped values in Go Chi HTTP middleware chains. Eliminates heap churn, cache thrashing, and GC pauses caused by nested context.WithValue wrapping and interface boxing of tenant claims and trace IDs.

Prohibited Anti-Pattern: Nested context.WithValue Chaining and Interface Boxing Across HTTP Middleware Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Zero-Allocation Context Value Propagation - Enforces single-allocation pointer propagation for request-scoped values in Go Chi HTTP middleware chains. Eliminates heap churn, cache thrashing, and GC pauses caused by nested context.WithValue wrapping and interface boxing of tenant claims and trace IDs.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-zero-alloc-context-propagation"
---

# Go Chi Zero-Allocation Context Value Propagation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Nested context.WithValue Chaining and Interface Boxing Across HTTP Middleware Pipelines

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-allocation and minimal-heap invariants in Go Chi HTTP pipelines. Mandate that request metadata, trace spans, and tenant claims never trigger repetitive context.WithValue allocations or runtime.convT interface escapes.

## Strict Guidelines
- Engineers MUST NOT chain multiple context.WithValue calls across discrete middleware functions to attach individual values.
- Engineers MUST instantiate a single, strongly-typed RequestContext pointer at the root Chi middleware and store only that pointer in the standard context.Context.
- Downstream middleware and handlers MUST mutate the fields of the pre-existing RequestContext pointer rather than creating new context nodes.
- Context keys MUST ALWAYS be private, zero-sized struct types (struct{}) to prevent key-comparison allocations.
- Engineers MUST NOT store primitives directly as interface{} values in context, which incurs runtime.convT* heap escapes.
- When using sync.Pool for request context containers, engineers MUST NEVER retain references to pooled structs past the lifecycle of the HTTP handler or into uncoordinated background goroutines.
- Code MUST use pointer receivers and compile with -gcflags='-m' to verify that context retrieval does not trigger heap escapes.

## Bad vs Good Implementations
### Naive Nested ValueCtx vs. Unified RequestContext Pointer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Each context.WithValue invocation allocates a context.valueCtx struct on the heap and causes runtime.convTstring heap allocations for the key and value interfaces. In high-throughput pipelines, this triggers severe GC pressure.
```go
package middleware

import (
	"context"
	"net/http"
)

// ANTI-PATTERN: Multiple context.WithValue calls allocate a new valueCtx
// node per layer and force primitive values to escape to the heap via interface{}.
func TraceMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		traceID := r.Header.Get("X-Trace-ID")
		ctx := context.WithValue(r.Context(), "trace_id", traceID) // Heap alloc + string box
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func TenantMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tenantID := r.Header.Get("X-Tenant-ID")
		ctx := context.WithValue(r.Context(), "tenant_id", tenantID) // Additional heap alloc
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
```

#### Production Standard (Correct)
> **Standard**: A single PipelineContext struct is pooled and bound once to the standard context. Subsequent Chi middlewares mutate fields directly on the shared pointer, eliminating valueCtx tree nesting and boxing allocations entirely.
```go
package middleware

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

type contextKey struct{}

// PipelineContext consolidates all request-scoped telemetry and auth data.
type PipelineContext struct {
	TraceID  string
	TenantID string
	UserID   string
}

var pipelineCtxPool = sync.Pool{
	New: func() any {
		return &PipelineContext{}
	},
}

// RootContextMiddleware allocates/retrieves one container struct for the entire pipeline.
func RootContextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		pctx := pipelineCtxPool.Get().(*PipelineContext)
		*pctx = PipelineContext{} // Reset fields without reallocation
		defer pipelineCtxPool.Put(pctx)

		ctx := context.WithValue(r.Context(), contextKey{}, pctx)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func TraceMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if pctx, ok := r.Context().Value(contextKey{}).(*PipelineContext); ok {
			pctx.TraceID = r.Header.Get("X-Trace-ID") // Zero-allocation field mutation
		}
		next.ServeHTTP(w, r)
	})
}

func TenantMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if pctx, ok := r.Context().Value(contextKey{}).(*PipelineContext); ok {
			pctx.TenantID = r.Header.Get("X-Tenant-ID") // Zero-allocation field mutation
		}
		next.ServeHTTP(w, r)
	})
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Zero-Allocation Context Value Propagation

Go Chi Zero-Allocation Context Value Propagation defines an industrial-grade behavioral standard for backend engineering. Enforces single-allocation pointer propagation for request-scoped values in Go Chi HTTP middleware chains. Eliminates heap churn, cache thrashing, and GC pauses caused by nested context.WithValue wrapping and interface boxing of tenant claims and trace IDs. 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: Nested context.WithValue Chaining and Interface Boxing Across HTTP Middleware Pipelines 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 DriftNested context.WithValue Chaining and Interface Boxing Across HTTP Middleware PipelinesCritical
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 NOT chain multiple context.WithValue calls across discrete middleware functions to attach individual values.

Engineers MUST NOT chain multiple context.WithValue calls across discrete middleware functions to attach individual values.

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 instantiate a single, strongly-typed RequestContext pointer at the root Chi middleware and store only that pointer in the standard context.Context.

Engineers MUST instantiate a single, strongly-typed RequestContext pointer at the root Chi middleware and store only that pointer in the standard context.Context.

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

Downstream middleware and handlers MUST mutate the fields of the pre-existing RequestContext pointer rather than creating new context nodes.

Downstream middleware and handlers MUST mutate the fields of the pre-existing RequestContext pointer rather than creating new context nodes.

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

Context keys MUST ALWAYS be private, zero-sized struct types (struct{}) to prevent key-comparison allocations.

Context keys MUST ALWAYS be private, zero-sized struct types (struct{}) to prevent key-comparison allocations.

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 NOT store primitives directly as interface{} values in context, which incurs runtime.convT* heap escapes.

Engineers MUST NOT store primitives directly as interface{} values in context, which incurs runtime.convT* heap escapes.

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

When using sync.Pool for request context containers, engineers MUST NEVER retain references to pooled structs past the lifecycle of the HTTP handler or into uncoordinated background goroutines.

When using sync.Pool for request context containers, engineers MUST NEVER retain references to pooled structs past the lifecycle of the HTTP handler or into uncoordinated background goroutines.

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.
7

Code MUST use pointer receivers and compile with -gcflags='-m' to verify that context retrieval does not trigger heap escapes.

Code MUST use pointer receivers and compile with -gcflags='-m' to verify that context retrieval does not trigger heap escapes.

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 Value Propagation critical for AI coding assistants?

Enforces single-allocation pointer propagation for request-scoped values in Go Chi HTTP middleware chains. Eliminates heap churn, cache thrashing, and GC pauses caused by nested context.WithValue wrapping and interface boxing of tenant claims and trace IDs. 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 (Nested context.WithValue Chaining and Interface Boxing Across HTTP Middleware Pipelines) 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