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

Go Chi Zero-Allocation Synthetic Arena Context Lease Invariant

Enforces deterministic recycling and life-cycle binding of synthetic memory arenas within Go Chi HTTP request pipelines. By anchoring arena leases directly to request contexts and strictly recycling underlying byte-slice slabs via sync.Pool, this guardrail guarantees zero-allocation request paths and eradicates garbage collection pause spikes during high-concurrency ingress surges.

Prohibited Anti-Pattern: Escaping Ephemeral Allocations and Unbounded Context Values Triggering Stop-The-World GC Pauses

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go Chi Zero-Allocation Synthetic Arena Context Lease Invariant - Enforces deterministic recycling and life-cycle binding of synthetic memory arenas within Go Chi HTTP request pipelines. By anchoring arena leases directly to request contexts and strictly recycling underlying byte-slice slabs via sync.Pool, this guardrail guarantees zero-allocation request paths and eradicates garbage collection pause spikes during high-concurrency ingress surges.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-chi-zero-alloc-synthetic-arena-context-lease"
---

# Go Chi Zero-Allocation Synthetic Arena Context Lease Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Escaping Ephemeral Allocations and Unbounded Context Values Triggering Stop-The-World GC Pauses

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-allocation synthetic arena patterns in Go Chi routing stacks. Ephemeral per-request memory must be leased from deterministic pools, bound exclusively to request life-cycles via context keys, and recycled in deferred cleanup blocks. You must reject any pattern that permits arena pointers or allocated buffers to escape beyond the HTTP request lifecycle or leak across concurrent goroutines.

## Strict Guidelines
- Engineers MUST ALWAYS initialize and lease synthetic request arenas inside Chi middleware using a pooled sync.Pool abstraction and defer release before writer flush.
- Engineers MUST NOT allow pointers allocated from a request arena to escape the request scope, be passed to detached background goroutines, or be stored in persistent caches.
- Code SHOULD extract arenas from context via strongly typed private context keys using unsafe-pointer-free interfaces or specialized direct accessors to prevent boxed context allocations.
- Services MUST enforce arena bounds checks and panic on allocation overflow or automatically allocate unmanaged fallback memory marked explicitly for immediate destruction.
- Components NEVER re-insert an arena back into the sync.Pool without zeroing its internal allocation offset, resetting cursor state, and unlinking active context references.

## Bad vs Good Implementations
### Chi Ingress Synthetic Arena Middleware and Consumer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocates a new 64KB heap slice per request without recycling, boxes the slice into context.Context causing escape analysis failure, and allows the buffer reference to escape into an unmanaged goroutine, defeating garbage collection optimizations and risking data corruption.
```go
package main

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

// Bad: Allocates new buffers on heap per request, creates boxed context interfaces,
// and permits references to escape to background tasks.
type ContextKey string
const ArenaKey ContextKey = "arena"

func BadMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		buf := make([]byte, 65536) // Unbounded heap allocation per request
		ctx := context.WithValue(r.Context(), ArenaKey, buf) // Causes context value boxing
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func BadHandler(w http.ResponseWriter, r *http.Request) {
	buf := r.Context().Value(ArenaKey).([]byte)
	payload := make(map[string]interface{})
	_ = json.NewDecoder(r.Body).Decode(&payload)

	// Escape bug: goroutine captures request-scoped slice pointer
	go func(data []byte) {
		// Retains buffer past HTTP handler lifetime; triggers GC retainment
		_ = len(data)
	}(buf)

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

#### Production Standard (Correct)
> **Standard**: Acquires a pre-allocated slab arena from sync.Pool, tracks allocations via simple sub-slicing with capped capacity, resets the offset deterministically in a deferred block, and ensures memory is strictly unescapable outside the HTTP transaction context.
```go
package main

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

type arenaKey struct{}

var (
	ErrArenaExhausted = errors.New("request arena capacity exceeded")
	arenaContextKey   = arenaKey{}
)

type SyntheticArena struct {
	storage []byte
	offset  int
}

func (a *SyntheticArena) Alloc(size int) ([]byte, error) {
	if a.offset+size > len(a.storage) {
		return nil, ErrArenaExhausted
	}
	res := a.storage[a.offset : a.offset+size : a.offset+size]
	a.offset += size
	return res, nil
}

func (a *SyntheticArena) Reset() {
	a.offset = 0
}

var arenaPool = sync.Pool{
	New: func() any {
		return &SyntheticArena{
			storage: make([]byte, 64*1024), // 64 KiB slab
			offset:  0,
		}
	},
}

func ArenaMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		arena := arenaPool.Get().(*SyntheticArena)
		arena.Reset()
		defer arenaPool.Put(arena)

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

func GetArena(ctx context.Context) *SyntheticArena {
	if arena, ok := ctx.Value(arenaContextKey).(*SyntheticArena); ok {
		return arena
	}
	return nil
}

func IngressHandler(w http.ResponseWriter, r *http.Request) {
	arena := GetArena(r.Context())
	if arena == nil {
		http.Error(w, "Arena missing", http.StatusInternalServerError)
		return
	}

	tempBuf, err := arena.Alloc(2048)
	if err != nil {
		http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
		return
	}

	// Use tempBuf exclusively within request lifecycle without heap escaping
	n, _ := r.Body.Read(tempBuf)
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(tempBuf[:n])
}
```

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 Synthetic Arena Context Lease Invariant

Go Chi Zero-Allocation Synthetic Arena Context Lease Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic recycling and life-cycle binding of synthetic memory arenas within Go Chi HTTP request pipelines. By anchoring arena leases directly to request contexts and strictly recycling underlying byte-slice slabs via sync.Pool, this guardrail guarantees zero-allocation request paths and eradicates garbage collection pause spikes during high-concurrency ingress surges. 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 Ephemeral Allocations and Unbounded Context Values Triggering Stop-The-World GC Pauses 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 Ephemeral Allocations and Unbounded Context Values Triggering Stop-The-World GC PausesCritical
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 initialize and lease synthetic request arenas inside Chi middleware using a pooled sync.Pool abstraction and defer release before writer flush.

Engineers MUST ALWAYS initialize and lease synthetic request arenas inside Chi middleware using a pooled sync.Pool abstraction and defer release before writer flush.

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 allow pointers allocated from a request arena to escape the request scope, be passed to detached background goroutines, or be stored in persistent caches.

Engineers MUST NOT allow pointers allocated from a request arena to escape the request scope, be passed to detached background goroutines, or be stored in persistent caches.

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

Code SHOULD extract arenas from context via strongly typed private context keys using unsafe-pointer-free interfaces or specialized direct accessors to prevent boxed context allocations.

Code SHOULD extract arenas from context via strongly typed private context keys using unsafe-pointer-free interfaces or specialized direct accessors to prevent boxed context 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.
4

Services MUST enforce arena bounds checks and panic on allocation overflow or automatically allocate unmanaged fallback memory marked explicitly for immediate destruction.

Services MUST enforce arena bounds checks and panic on allocation overflow or automatically allocate unmanaged fallback memory marked explicitly for immediate destruction.

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 re-insert an arena back into the sync.Pool without zeroing its internal allocation offset, resetting cursor state, and unlinking active context references.

Components NEVER re-insert an arena back into the sync.Pool without zeroing its internal allocation offset, resetting cursor state, and unlinking active context references.

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 Synthetic Arena Context Lease Invariant critical for AI coding assistants?

Enforces deterministic recycling and life-cycle binding of synthetic memory arenas within Go Chi HTTP request pipelines. By anchoring arena leases directly to request contexts and strictly recycling underlying byte-slice slabs via sync.Pool, this guardrail guarantees zero-allocation request paths and eradicates garbage collection pause spikes during high-concurrency ingress surges. 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 Ephemeral Allocations and Unbounded Context Values Triggering Stop-The-World GC Pauses) 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