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

Go 1.24 Weak Pointer Cache Eviction and Memory Reclamation Guardrails

Mandates deterministic key reclamation and lifecycle coordination using Go 1.24's weak.Pointer and runtime.AddCleanup within high-churn routing tables. Prevents mark-sweep pointer-chasing GC stalls and unbounded map-entry leaks by decoupling entry lifetime from GC root sets.

Prohibited Anti-Pattern: Retaining strong routing targets in canonicalization caches or failing to evict dead weak.Pointer entries from concurrent maps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Eviction and Memory Reclamation Guardrails - Mandates deterministic key reclamation and lifecycle coordination using Go 1.24's weak.Pointer and runtime.AddCleanup within high-churn routing tables. Prevents mark-sweep pointer-chasing GC stalls and unbounded map-entry leaks by decoupling entry lifetime from GC root sets.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-1-24-weak-pointer-cache-eviction-invariants"
---

# Go 1.24 Weak Pointer Cache Eviction and Memory Reclamation Guardrails

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining strong routing targets in canonicalization caches or failing to evict dead weak.Pointer entries from concurrent maps

## System Constraints
You are a Principal Software Architect enforcing Go 1.24 weak pointer memory invariants in high-throughput, low-latency microsecond gateways. Mandate strict adherence to weak.Pointer[T] canonicalization patterns combined with runtime.AddCleanup. Ensure no strong references leak into global cache maps, dead weak keys are eagerly scrubbed without stop-the-world GC intervention, and dereferencing weak pointers is performed atomically with nil validation.

## Strict Guidelines
- Engineers MUST ALWAYS pair weak.Pointer[T] entries in routing maps with runtime.AddCleanup to purge dangling map keys once target objects are collected.
- Engineers MUST NOT use runtime.SetFinalizer on types managed by weak.Pointer due to object resurrection risks and heap-escape overhead.
- Code SHOULD atomically snapshot wp.Value() into a single stack-allocated variable and perform immediate nil verification before accessing route metadata.
- Services MUST NEVER create cyclic strong references back from a cached route target to the parent route cache or its eviction registry.
- Components MUST ensure cleanup closures passed to runtime.AddCleanup do not capture the target object itself, which would permanently prevent reclamation.

## Bad vs Good Implementations
### Go 1.24 Route Cache Eviction via weak.Pointer and runtime.AddCleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining strong pointers (*RouteTarget) in high-churn lookup tables anchors objects into the GC root graph indefinitely, ballooning heap scan times and causing latency spikes during GC mark phases.
```go
package gateway

import "sync"

type RouteTarget struct {
	Endpoint string
	Metadata map[string]string
}

type RouteCache struct {
	mu     sync.RWMutex
	routes map[string]*RouteTarget // Strong references prevent GC and cause mark-sweep stalls
}

func (c *RouteCache) GetOrStore(key string, target *RouteTarget) *RouteTarget {
	c.mu.Lock()
	defer c.mu.Unlock()

	if existing, ok := c.routes[key]; ok {
		return existing
	}

	c.routes[key] = target // Unbounded growth: churned ephemeral routes leak memory
	return target
}
```

#### Production Standard (Correct)
> **Standard**: Go 1.24 weak.Make stores a non-owning pointer allowing target reclamation, while runtime.AddCleanup deletes the dead key cleanly once the underlying memory is freed, maintaining zero GC pause impact.
```go
package gateway

import (
	"runtime"
	"sync"
	"weak"
)

type RouteTarget struct {
	Endpoint string
	Metadata map[string]string
}

type WeakRouteCache struct {
	mu     sync.RWMutex
	routes map[string]weak.Pointer[RouteTarget]
}

func NewWeakRouteCache() *WeakRouteCache {
	return &WeakRouteCache{
		routes: make(map[string]weak.Pointer[RouteTarget]),
	}
}

func (c *WeakRouteCache) GetOrStore(key string, target *RouteTarget) *RouteTarget {
	c.mu.RLock()
	if wp, ok := c.routes[key]; ok {
		if val := wp.Value(); val != nil {
			c.mu.RUnlock()
			return val
		}
	}
	c.mu.RUnlock()

	c.mu.Lock()
	defer c.mu.Unlock()

	// Double-check under write lock
	if wp, ok := c.routes[key]; ok {
		if val := wp.Value(); val != nil {
			return val
		}
	}

	c.routes[key] = weak.Make(target)

	// Coordinate deterministic map cleanup on allocator free without capturing target
	runtime.AddCleanup(target, func(cleanupKey string) {
		c.mu.Lock()
		defer c.mu.Unlock()
		if curWp, ok := c.routes[cleanupKey]; ok && curWp.Value() == nil {
			delete(c.routes, cleanupKey)
		}
	}, key)

	return target
}
```

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 Cache Eviction and Memory Reclamation Guardrails

Go 1.24 Weak Pointer Cache Eviction and Memory Reclamation Guardrails defines an industrial-grade behavioral standard for backend engineering. Mandates deterministic key reclamation and lifecycle coordination using Go 1.24's weak.Pointer and runtime.AddCleanup within high-churn routing tables. Prevents mark-sweep pointer-chasing GC stalls and unbounded map-entry leaks by decoupling entry lifetime from GC root sets. 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: Retaining strong routing targets in canonicalization caches or failing to evict dead weak.Pointer entries from concurrent maps 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 DriftRetaining strong routing targets in canonicalization caches or failing to evict dead weak.Pointer entries from concurrent mapsCritical
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 pair weak.Pointer[T] entries in routing maps with runtime.AddCleanup to purge dangling map keys once target objects are collected.

Engineers MUST ALWAYS pair weak.Pointer[T] entries in routing maps with runtime.AddCleanup to purge dangling map keys once target objects are collected.

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 use runtime.SetFinalizer on types managed by weak.Pointer due to object resurrection risks and heap-escape overhead.

Engineers MUST NOT use runtime.SetFinalizer on types managed by weak.Pointer due to object resurrection risks and heap-escape overhead.

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 atomically snapshot wp.Value() into a single stack-allocated variable and perform immediate nil verification before accessing route metadata.

Code SHOULD atomically snapshot wp.Value() into a single stack-allocated variable and perform immediate nil verification before accessing route metadata.

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 NEVER create cyclic strong references back from a cached route target to the parent route cache or its eviction registry.

Services MUST NEVER create cyclic strong references back from a cached route target to the parent route cache or its eviction registry.

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 MUST ensure cleanup closures passed to runtime.AddCleanup do not capture the target object itself, which would permanently prevent reclamation.

Components MUST ensure cleanup closures passed to runtime.AddCleanup do not capture the target object itself, which would permanently prevent reclamation.

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 Cache Eviction and Memory Reclamation Guardrails critical for AI coding assistants?

Mandates deterministic key reclamation and lifecycle coordination using Go 1.24's weak.Pointer and runtime.AddCleanup within high-churn routing tables. Prevents mark-sweep pointer-chasing GC stalls and unbounded map-entry leaks by decoupling entry lifetime from GC root sets. 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 (Retaining strong routing targets in canonicalization caches or failing to evict dead weak.Pointer entries from concurrent maps) 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