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-invariant

Go 1.24 Weak-Pointer Ephemeral Cache and GC Invariant

Enforces strict memory safety and lifetime boundaries when using Go 1.24 weak pointers (weak.Pointer) for high-throughput route metadata and ephemeral session caches. Weak references must guard against nil dereferencing, prevent premature promotion during lookup, and use runtime-aligned cleanup to eradicate GC mark-phase STW latency spikes.

Prohibited Anti-Pattern: Retaining strong references across cache lookups and using manual finalizers instead of Go 1.24 weak.Pointer and runtime.AddCleanup.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak-Pointer Ephemeral Cache and GC Invariant - Enforces strict memory safety and lifetime boundaries when using Go 1.24 weak pointers (weak.Pointer) for high-throughput route metadata and ephemeral session caches. Weak references must guard against nil dereferencing, prevent premature promotion during lookup, and use runtime-aligned cleanup to eradicate GC mark-phase STW latency spikes.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-ephemeral-cache-invariant"
---

# Go 1.24 Weak-Pointer Ephemeral Cache and GC Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining strong references across cache lookups and using manual finalizers instead of Go 1.24 weak.Pointer and runtime.AddCleanup.

## System Constraints
You are a Principal Systems Engineer enforcing strict Go 1.24 memory and concurrency invariants. All ephemeral route metadata and session caches using Go 1.24 weak pointers must adhere to atomic value extraction, zero accidental heap promotion, and modern runtime cleanup primitives.

## Strict Guidelines
- Engineers MUST ALWAYS wrap weak.Pointer[T].Value() results in immediate nil checks, treating weak dereferences as potentially collected on every single read.
- Engineers MUST NOT leak extracted strong pointers into global or long-lived goroutine scopes, which would unintentionally defeat ephemeral collection.
- Code MUST use runtime.AddCleanup instead of deprecated runtime.SetFinalizer to handle reclamation bookkeeping and hash-table bucket deallocations.
- Services MUST serialize or shard map access via sync.RWMutex or concurrent bucket designs to prevent race conditions during concurrent weak reference evaluation.
- Components NEVER store direct strong pointers in the primary lookup index when designing zero-leak ephemeral tiers; keys or values designated as ephemeral must reside strictly behind weak.Pointer wrappers.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing strong pointers in an ephemeral cache causes unbounded memory retention and ballooning GC mark times. Using runtime.SetFinalizer delays object destruction across multiple GC cycles and introduces severe runtime overhead.
```go
package cache

import (
	"runtime"
	"sync"
)

type RouteMetadata struct {
	Pattern string
	Handler func()
}

type EphemeralCache struct {
	mu    sync.RWMutex
	items map[string]*RouteMetadata // Anti-pattern: Strong references keep values alive indefinitely
}

func (c *EphemeralCache) Set(key string, val *RouteMetadata) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[key] = val
	// Anti-pattern: runtime.SetFinalizer adds GC mark-phase overhead and prevents circular GC
	runtime.SetFinalizer(val, func(m *RouteMetadata) {
		// Flawed attempt to prune map; causes deadlocks or leaks
	})
}

func (c *EphemeralCache) Get(key string) *RouteMetadata {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.items[key] // Never reclaimed by GC; leads to mark-phase latency spikes
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Go 1.24's weak.Make to store non-owning references, allowing the GC to reclaim metadata without mark-phase pauses. Employs runtime.AddCleanup to reliably remove dead cache entries without the overhead and cyclic-dependency hazards of runtime.SetFinalizer.
```go
package cache

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

type RouteMetadata struct {
	Pattern string
	Handler func()
}

type EphemeralCache struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[RouteMetadata]
}

func NewEphemeralCache() *EphemeralCache {
	return &EphemeralCache{
		items: make(map[string]weak.Pointer[RouteMetadata]),
	}
}

func (c *EphemeralCache) Set(key string, val *RouteMetadata) {
	c.mu.Lock()
	defer c.mu.Unlock()

	// Wrap value into a weak reference so GC can reclaim it under pressure
	c.items[key] = weak.Make(val)

	// Go 1.24 runtime.AddCleanup eliminates finalizer overhead and safely evicts tombstone keys
	runtime.AddCleanup(val, func(k string) {
		c.mu.Lock()
		delete(c.items, k)
		c.mu.Unlock()
	}, key)
}

func (c *EphemeralCache) Get(key string) (*RouteMetadata, bool) {
	c.mu.RLock()
	wp, exists := c.items[key]
	c.mu.RUnlock()
	if !exists {
		return nil, false
	}

	// Invariant: Always check for nil immediately; value may have been reclaimed
	val := wp.Value()
	if val == nil {
		c.mu.Lock()
		delete(c.items, key)
		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 Ephemeral Cache and GC Invariant

Go 1.24 Weak-Pointer Ephemeral Cache and GC Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory safety and lifetime boundaries when using Go 1.24 weak pointers (weak.Pointer) for high-throughput route metadata and ephemeral session caches. Weak references must guard against nil dereferencing, prevent premature promotion during lookup, and use runtime-aligned cleanup to eradicate GC mark-phase STW latency spikes. 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 references across cache lookups and using manual finalizers instead of Go 1.24 weak.Pointer and runtime.AddCleanup. 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 references across cache lookups and using manual finalizers instead of Go 1.24 weak.Pointer and runtime.AddCleanup.Critical
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 wrap weak.Pointer[T].Value() results in immediate nil checks, treating weak dereferences as potentially collected on every single read.

Engineers MUST ALWAYS wrap weak.Pointer[T].Value() results in immediate nil checks, treating weak dereferences as potentially collected on every single read.

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 leak extracted strong pointers into global or long-lived goroutine scopes, which would unintentionally defeat ephemeral collection.

Engineers MUST NOT leak extracted strong pointers into global or long-lived goroutine scopes, which would unintentionally defeat ephemeral collection.

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 use runtime.AddCleanup instead of deprecated runtime.SetFinalizer to handle reclamation bookkeeping and hash-table bucket deallocations.

Code MUST use runtime.AddCleanup instead of deprecated runtime.SetFinalizer to handle reclamation bookkeeping and hash-table bucket deallocations.

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 serialize or shard map access via sync.RWMutex or concurrent bucket designs to prevent race conditions during concurrent weak reference evaluation.

Services MUST serialize or shard map access via sync.RWMutex or concurrent bucket designs to prevent race conditions during concurrent weak reference evaluation.

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 direct strong pointers in the primary lookup index when designing zero-leak ephemeral tiers

Components NEVER store direct strong pointers in the primary lookup index when designing zero-leak ephemeral tiers; keys or values designated as ephemeral must reside strictly behind weak.Pointer wrappers.

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 Ephemeral Cache and GC Invariant critical for AI coding assistants?

Enforces strict memory safety and lifetime boundaries when using Go 1.24 weak pointers (weak.Pointer) for high-throughput route metadata and ephemeral session caches. Weak references must guard against nil dereferencing, prevent premature promotion during lookup, and use runtime-aligned cleanup to eradicate GC mark-phase STW latency spikes. 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 references across cache lookups and using manual finalizers instead of Go 1.24 weak.Pointer and runtime.AddCleanup.) 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