This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: go-124-weak-pointer-ephemeral-cache-routing

Go 1.24 Weak Pointer Invalidation for Ephemeral Routing Caches

Mandates the use of Go 1.24 weak pointers (package weak) for transient routing and middleware cache registries. Prevents unbounded heap growth and circular reference retention where long-lived router caches retain short-lived HTTP request contexts and payloads past lifecycle termination.

Prohibited Anti-Pattern: Strong Reference Pinning of Ephemeral Request Payloads in Long-Lived Routing Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Invalidation for Ephemeral Routing Caches - Mandates the use of Go 1.24 weak pointers (package weak) for transient routing and middleware cache registries. Prevents unbounded heap growth and circular reference retention where long-lived router caches retain short-lived HTTP request contexts and payloads past lifecycle termination.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-ephemeral-cache-routing"
---

# Go 1.24 Weak Pointer Invalidation for Ephemeral Routing Caches

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Strong Reference Pinning of Ephemeral Request Payloads in Long-Lived Routing Pipelines

## System Constraints
You are a Principal Go Architect enforcing Go 1.24 runtime memory safety invariants. Long-lived routing infrastructure, middleware chains, and cross-request caches MUST NOT hold strong pointers to per-request structures, context values, or session tokens. Mandate the usage of Go 1.24's 'weak' package (weak.Pointer, weak.Make) to enable automatic runtime garbage collection of ephemeral pipeline state, eliminating memory leaks and manual eviction desynchronization.

## Strict Guidelines
- Engineers MUST ALWAYS use weak.Pointer[T] when caching short-lived request metadata, parsed claims, or request payloads in long-lived middleware or router singletons.
- Engineers MUST NOT store raw strong pointers (*T) to request-scoped structures in global or long-lived shared map registries.
- Code MUST verify the result of weak.Pointer[T].Value() for nil on every read to handle runtime garbage collection gracefully before accessing cached references.
- Services MUST lazily purge expired or collected keys from internal router maps when weak.Pointer[T].Value() returns nil to prevent key-space map bloat.
- Components NEVER store context.Context instances or structs containing context.Context directly or indirectly inside weak pointer targets or shared cache instances.

## Bad vs Good Implementations
### Ephemeral Route State Invalidation via Go 1.24 weak.Pointer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining strong pointers (*SessionContext) inside a persistent router struct prevents the Go garbage collector from reclaiming request metadata, leading to memory bloat under high throughput and unbounded heap consumption.
```go
package router

import (
	"net/http"
	"sync"
)

type SessionContext struct {
	UserID string
	Scope  []string
}

type PipelineCache struct {
	mu    sync.RWMutex
	store map[string]*SessionContext // ANTI-PATTERN: Strong pointer pins request state across cycles
}

func (c *PipelineCache) Put(token string, sc *SessionContext) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.store[token] = sc // Causes heap retention long after HTTP request completes
}

func (c *PipelineCache) Get(token string) *SessionContext {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.store[token]
}
```

#### Production Standard (Correct)
> **Standard**: Leveraging Go 1.24's weak.Pointer allows the GC to reclaim SessionContext when the active HTTP request scope drops its strong reference. PipelineCache dereferences via Value(), cleans up reclaimed keys lazily, and prevents memory retention.
```go
package router

import (
	"net/http"
	"sync"
	"weak" // Go 1.24+ standard library
)

type SessionContext struct {
	UserID string
	Scope  []string
}

type PipelineCache struct {
	mu    sync.RWMutex
	store map[string]weak.Pointer[SessionContext]
}

func (c *PipelineCache) Put(token string, sc *SessionContext) {
	c.mu.Lock()
	defer c.mu.Unlock()
	// Store weak reference; GC collects sc when request stack/context releases it
	c.store[token] = weak.Make(sc)
}

func (c *PipelineCache) Get(token string) (*SessionContext, bool) {
	c.mu.RLock()
	wp, exists := c.store[token]
	c.mu.RUnlock()
	if !exists {
		return nil, false
	}

	val := wp.Value()
	if val == nil {
		// GC collected the target; eagerly clean up the tombstoned key
		c.mu.Lock()
		delete(c.store, token)
		c.mu.Unlock()
		return nil, false
	}

	return val, true
}
```

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 1.24 Weak Pointer Invalidation for Ephemeral Routing Caches

Go 1.24 Weak Pointer Invalidation for Ephemeral Routing Caches defines an industrial-grade behavioral standard for backend engineering. Mandates the use of Go 1.24 weak pointers (package weak) for transient routing and middleware cache registries. Prevents unbounded heap growth and circular reference retention where long-lived router caches retain short-lived HTTP request contexts and payloads past lifecycle termination. 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: Strong Reference Pinning of Ephemeral Request Payloads in Long-Lived Routing 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 DriftStrong Reference Pinning of Ephemeral Request Payloads in Long-Lived Routing 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 ALWAYS use weak.Pointer[T] when caching short-lived request metadata, parsed claims, or request payloads in long-lived middleware or router singletons.

Engineers MUST ALWAYS use weak.Pointer[T] when caching short-lived request metadata, parsed claims, or request payloads in long-lived middleware or router singletons.

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 store raw strong pointers (*T) to request-scoped structures in global or long-lived shared map registries.

Engineers MUST NOT store raw strong pointers (*T) to request-scoped structures in global or long-lived shared map registries.

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 MUST verify the result of weak.Pointer[T].Value() for nil on every read to handle runtime garbage collection gracefully before accessing cached references.

Code MUST verify the result of weak.Pointer[T].Value() for nil on every read to handle runtime garbage collection gracefully before accessing cached 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.
4

Services MUST lazily purge expired or collected keys from internal router maps when weak.Pointer[T].Value() returns nil to prevent key-space map bloat.

Services MUST lazily purge expired or collected keys from internal router maps when weak.Pointer[T].Value() returns nil to prevent key-space map bloat.

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 store context.Context instances or structs containing context.Context directly or indirectly inside weak pointer targets or shared cache instances.

Components NEVER store context.Context instances or structs containing context.Context directly or indirectly inside weak pointer targets or shared cache instances.

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 1.24 Weak Pointer Invalidation for Ephemeral Routing Caches critical for AI coding assistants?

Mandates the use of Go 1.24 weak pointers (package weak) for transient routing and middleware cache registries. Prevents unbounded heap growth and circular reference retention where long-lived router caches retain short-lived HTTP request contexts and payloads past lifecycle termination. 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 (Strong Reference Pinning of Ephemeral Request Payloads in Long-Lived Routing 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