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-pooling-guardrail

Go Chi Zero-Allocation Context Pooling Lifecycle Guardrail

Enforces strict lifecycle boundaries and sync.Pool reuse semantics for go-chi/chi/v5 URL context objects (chi.Context). High-throughput endpoints must recycle contexts back into the pool while preventing use-after-free, concurrent mutation, and context reference escapes across asynchronous goroutine boundaries.

Prohibited Anti-Pattern: Escaping Chi Context References Across Goroutine Spawns or Missing Context Reset in Middleware Pools

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Zero-Allocation Context Pooling Lifecycle Guardrail - Enforces strict lifecycle boundaries and sync.Pool reuse semantics for go-chi/chi/v5 URL context objects (chi.Context). High-throughput endpoints must recycle contexts back into the pool while preventing use-after-free, concurrent mutation, and context reference escapes across asynchronous goroutine boundaries.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-zero-alloc-context-pooling-guardrail"
---

# Go Chi Zero-Allocation Context Pooling Lifecycle Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Escaping Chi Context References Across Goroutine Spawns or Missing Context Reset in Middleware Pools

## System Constraints
You are a Principal Engineer enforcing Go Chi Zero-Allocation Context Pooling Guardrails. Mandate strict memory recycling invariants using sync.Pool for request-scoped chi.Context structures. Ensure contexts are safely reclaimed after ServeHTTP returns, cleanly reset to avoid dirty state contamination, and never passed by reference to background goroutines or decoupled asynchronous workers.

## Strict Guidelines
- Engineers MUST ALWAYS reset the pooled chi.Context struct via `rctx.Reset()` before putting it back into the sync.Pool.
- Engineers MUST NEVER pass a pooled `*chi.Context` or a request containing a pooled `chi.RouteContextKey` into asynchronous goroutines without copying or deep-cloning values.
- Engineers MUST ensure that any custom router or middleware using pooled contexts releases the context in a deferred block tied strictly to the synchronous handler execution stack.
- Code SHOULD clone route parameters into isolated primitives or detached structs if asynchronous background processing requires URL parameters extracted via `chi.URLParam`.
- Services MUST compile and validate context pooling logic under `-race` to ensure no data races or use-after-free anomalies occur when contexts return to `sync.Pool`.
- Components NEVER hold onto a borrowed `chi.Context` reference beyond the lifetime of the active HTTP request-response cycle.

## Bad vs Good Implementations
### Unsafe Asynchronous Escaping of Pooled Chi Context vs. Detached Parameter Extraction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: chi.Context instances are recycled into sync.Pool by Chi's internal routing engine or custom pooled wrappers upon HTTP handler return. Passing r.Context() to a background goroutine causes a severe data race and reads mutated memory as the pooled context is reused for subsequent incoming requests.
```go
package server

import (
	"net/http"
	"github.com/go-chi/chi/v5"
)

func AsyncJobHandler(w http.ResponseWriter, r *http.Request) {
	// ANTI-PATTERN: r.Context() encapsulates chi.RouteCtxKey pointing to a pooled chi.Context.
	// Spawning a goroutine with the request context causes a race and use-after-free
	// when chi returns the route context to sync.Pool after ServeHTTP completes.
	go func(ctx context.Context) {
		userID := chi.URLParamFromCtx(ctx, "userID")
		processAuditLog(userID)
	}(r.Context())

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

#### Production Standard (Correct)
> **Standard**: By extracting the required route parameters as immutable scalar types (e.g. string) prior to goroutine instantiation, the background process eliminates any dependency on the pooled `chi.Context`. The request context lifecycle cleanly completes without data races.
```go
package server

import (
	"context"
	"net/http"
	"github.com/go-chi/chi/v5"
)

func AsyncJobHandler(w http.ResponseWriter, r *http.Request) {
	// INVARIANT FIX: Extract URL parameters synchronously before spawning async jobs.
	// Pass explicit scalar values or a clean, detached context (e.g., context.WithoutCancel).
	userID := chi.URLParam(r, "userID")

	go func(id string) {
		// Runs safely with an independent context, completely decoupled from chi's sync.Pool
		bgCtx := context.Background()
		processAuditLogWithID(bgCtx, id)
	}(userID)

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

### Custom Chi Router Middleware Context Pooling Lifecycle Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to reset the `chi.Context` retains route params and match history from prior requests (state contamination). Omitting deferred cleanup causes memory leaks when downstream handlers panic.
```go
package middleware

import (
	"net/http"
	"sync"
	"github.com/go-chi/chi/v5"
)

var routePool = sync.Pool{
	New: func() any { return chi.NewRouteContext() },
}

func PooledContextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rctx := routePool.Get().(*chi.Context)
		// ANTI-PATTERN: Missing reset and no defer to guarantee reclamation.
		// If next.ServeHTTP panics, context leaks. Context state from previous requests leaks.
		ctx := context.WithValue(r.Context(), chi.RouteCtxKey, rctx)
		next.ServeHTTP(w, r.WithContext(ctx))
		routePool.Put(rctx)
	})
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly invokes `rctx.Reset()` before injection and inside a deferred return block. Ensures zero state bleeding across invocations and guaranteed return to `sync.Pool` even during downstream handler panics.
```go
package middleware

import (
	"context"
	"net/http"
	"sync"
	"github.com/go-chi/chi/v5"
)

var routePool = sync.Pool{
	New: func() any { return chi.NewRouteContext() },
}

func PooledContextMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rctx := routePool.Get().(*chi.Context)
		rctx.Reset()
		defer func() {
			rctx.Reset()
			routePool.Put(rctx)
		}()

		ctx := context.WithValue(r.Context(), chi.RouteCtxKey, rctx)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
```

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 Pooling Lifecycle Guardrail

Go Chi Zero-Allocation Context Pooling Lifecycle Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict lifecycle boundaries and sync.Pool reuse semantics for go-chi/chi/v5 URL context objects (chi.Context). High-throughput endpoints must recycle contexts back into the pool while preventing use-after-free, concurrent mutation, and context reference escapes across asynchronous goroutine boundaries. 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: Escaping Chi Context References Across Goroutine Spawns or Missing Context Reset in Middleware Pools 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 DriftEscaping Chi Context References Across Goroutine Spawns or Missing Context Reset in Middleware PoolsCritical
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 reset the pooled chi.Context struct via `rctx.Reset()` before putting it back into the sync.Pool.

Engineers MUST ALWAYS reset the pooled chi.Context struct via `rctx.Reset()` before putting it back into the sync.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.
2

Engineers MUST NEVER pass a pooled `*chi.Context` or a request containing a pooled `chi.RouteContextKey` into asynchronous goroutines without copying or deep-cloning values.

Engineers MUST NEVER pass a pooled `*chi.Context` or a request containing a pooled `chi.RouteContextKey` into asynchronous goroutines without copying or deep-cloning 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.
3

Engineers MUST ensure that any custom router or middleware using pooled contexts releases the context in a deferred block tied strictly to the synchronous handler execution stack.

Engineers MUST ensure that any custom router or middleware using pooled contexts releases the context in a deferred block tied strictly to the synchronous handler execution stack.

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

Code SHOULD clone route parameters into isolated primitives or detached structs if asynchronous background processing requires URL parameters extracted via `chi.URLParam`.

Code SHOULD clone route parameters into isolated primitives or detached structs if asynchronous background processing requires URL parameters extracted via `chi.URLParam`.

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

Services MUST compile and validate context pooling logic under `-race` to ensure no data races or use-after-free anomalies occur when contexts return to `sync.Pool`.

Services MUST compile and validate context pooling logic under `-race` to ensure no data races or use-after-free anomalies occur when contexts return to `sync.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.
6

Components NEVER hold onto a borrowed `chi.Context` reference beyond the lifetime of the active HTTP request-response cycle.

Components NEVER hold onto a borrowed `chi.Context` reference beyond the lifetime of the active HTTP request-response 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.
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 Pooling Lifecycle Guardrail critical for AI coding assistants?

Enforces strict lifecycle boundaries and sync.Pool reuse semantics for go-chi/chi/v5 URL context objects (chi.Context). High-throughput endpoints must recycle contexts back into the pool while preventing use-after-free, concurrent mutation, and context reference escapes across asynchronous goroutine boundaries. 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 (Escaping Chi Context References Across Goroutine Spawns or Missing Context Reset in Middleware Pools) 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