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

Go Chi Zero-Allocation Typed Context Propagation Standard

Enforces zero-allocation typed context extraction and propagation within high-throughput Go Chi microservices. Prevents severe GC pause spikes and heap fragmentation caused by chaining context.WithValue with boxed primitive or struct values on the HTTP hot path by leveraging pooled pointers and single-key unified state propagation.

Prohibited Anti-Pattern: Heap-Allocating Un-pooled Request State via Chained context.WithValue Invocations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Zero-Allocation Typed Context Propagation Standard - Enforces zero-allocation typed context extraction and propagation within high-throughput Go Chi microservices. Prevents severe GC pause spikes and heap fragmentation caused by chaining context.WithValue with boxed primitive or struct values on the HTTP hot path by leveraging pooled pointers and single-key unified state propagation.
globs: **/*.go, internal/transport/http/**/*.go, pkg/middleware/**/*.go, cmd/server/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-zero-alloc-typed-context-propagation-guardrail"
---

# Go Chi Zero-Allocation Typed Context Propagation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Heap-Allocating Un-pooled Request State via Chained context.WithValue Invocations

## System Constraints
You are a Principal Systems Engineer and Go Performance Specialist enforcing strict zero-allocation request context propagation for Go Chi microservices. Mandate the elimination of interface{} boxing allocations, multiple context wraps per request, and un-pooled request metadata objects on hot execution paths.

## Strict Guidelines
- Engineers MUST NOT call context.WithValue multiple times across middleware chains to attach isolated metadata items.
- Engineers MUST encapsulate per-request lifecycle data (e.g., authentication claims, tenant IDs, trace metadata) within a single typed RequestContext struct.
- Middleware MUST recycle RequestContext struct pointers using a thread-safe sync.Pool to achieve zero heap allocations on the ingress path.
- Engineers MUST reset all fields of recycled RequestContext pointers to their zero-value before returning them to sync.Pool via defer to prevent state contamination and memory leaks.
- Downstream handlers and nested middlewares MUST NOT retain or pass pooled context pointers to background goroutines beyond the HTTP request lifecycle.
- When context propagation to asynchronous background workers is required, engineers MUST copy the data into an independent, non-pooled struct instance.

## Bad vs Good Implementations
### Chained Boxing Allocations vs. sync.Pool Pointer Ingress

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Each context.WithValue invocation allocates a valueCtx struct on the heap and causes escape analysis to box strings and keys into interface{} values. Under 100,000 req/s, this triggers millions of allocations per second, degrading latency with GC stop-the-world pauses.
```go
package middleware

import (
	"context"
	"net/http"
)

type contextKey string

const (
	userKey   contextKey = "user"
	traceKey  contextKey = "trace"
	tenantKey contextKey = "tenant"
)

// Bad: Every WithValue causes 1-2 heap allocations due to interface{} boxing
// and allocates new valueCtx tree nodes per middleware in Chi's pipeline.
func ContextChainingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		ctx = context.WithValue(ctx, userKey, r.Header.Get("X-User-ID"))
		ctx = context.WithValue(ctx, traceKey, r.Header.Get("X-Trace-ID"))
		ctx = context.WithValue(ctx, tenantKey, r.Header.Get("X-Tenant-ID"))
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
```

#### Production Standard (Correct)
> **Standard**: Reuses RequestState allocations using sync.Pool. The context tree is wrapped once with an unexported struct key type, ensuring zero runtime heap allocation during steady-state processing and shielding memory from cross-request pollution via defer-reset.
```go
package middleware

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

type RequestState struct {
	UserID   string
	TraceID  string
	TenantID string
}

type stateContextKey struct{}

var (
	requestStateKey = stateContextKey{}
	statePool       = sync.Pool{
		New: func() any {
			return &RequestState{}
		},
	}
)

// Good: Recycles a single pointer via sync.Pool and injects exactly once.
func ZeroAllocContextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		state := statePool.Get().(*RequestState)
		defer func() {
			*state = RequestState{} // zero-value reset to prevent memory leaks
			statePool.Put(state)
		}()

		state.UserID = r.Header.Get("X-User-ID")
		state.TraceID = r.Header.Get("X-Trace-ID")
		state.TenantID = r.Header.Get("X-Tenant-ID")

		ctx := context.WithValue(r.Context(), requestStateKey, state)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func GetRequestState(ctx context.Context) *RequestState {
	if state, ok := ctx.Value(requestStateKey).(*RequestState); ok {
		return state
	}
	return nil
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go Chi Zero-Allocation Typed Context Propagation Standard

Go Chi Zero-Allocation Typed Context Propagation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces zero-allocation typed context extraction and propagation within high-throughput Go Chi microservices. Prevents severe GC pause spikes and heap fragmentation caused by chaining context.WithValue with boxed primitive or struct values on the HTTP hot path by leveraging pooled pointers and single-key unified state propagation. 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: Heap-Allocating Un-pooled Request State via Chained context.WithValue Invocations 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 DriftHeap-Allocating Un-pooled Request State via Chained context.WithValue InvocationsCritical
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 call context.WithValue multiple times across middleware chains to attach isolated metadata items.

Engineers MUST NOT call context.WithValue multiple times across middleware chains to attach isolated metadata items.

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 encapsulate per-request lifecycle data (e.g., authentication claims, tenant IDs, trace metadata) within a single typed RequestContext struct.

Engineers MUST encapsulate per-request lifecycle data (e.g., authentication claims, tenant IDs, trace metadata) within a single typed RequestContext struct.

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

Middleware MUST recycle RequestContext struct pointers using a thread-safe sync.Pool to achieve zero heap allocations on the ingress path.

Middleware MUST recycle RequestContext struct pointers using a thread-safe sync.Pool to achieve zero heap allocations on the ingress path.

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

Engineers MUST reset all fields of recycled RequestContext pointers to their zero-value before returning them to sync.Pool via defer to prevent state contamination and memory leaks.

Engineers MUST reset all fields of recycled RequestContext pointers to their zero-value before returning them to sync.Pool via defer to prevent state contamination and memory leaks.

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

Downstream handlers and nested middlewares MUST NOT retain or pass pooled context pointers to background goroutines beyond the HTTP request lifecycle.

Downstream handlers and nested middlewares MUST NOT retain or pass pooled context pointers to background goroutines beyond the HTTP request 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

When context propagation to asynchronous background workers is required, engineers MUST copy the data into an independent, non-pooled struct instance.

When context propagation to asynchronous background workers is required, engineers MUST copy the data into an independent, non-pooled struct instance.

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 Typed Context Propagation Standard critical for AI coding assistants?

Enforces zero-allocation typed context extraction and propagation within high-throughput Go Chi microservices. Prevents severe GC pause spikes and heap fragmentation caused by chaining context.WithValue with boxed primitive or struct values on the HTTP hot path by leveraging pooled pointers and single-key unified state propagation. 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 (Heap-Allocating Un-pooled Request State via Chained context.WithValue Invocations) 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