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

Go 1.24 Weak Pointer In-Memory Cache Reclamation and Finalizer Safety

Go 1.24 introduced native weak pointers via the 'weak' package, enabling GC-cooperative in-memory caches that safely release heap allocations without periodic TTL sweeper overhead. Implementing this pattern requires strict enforcement of dereference validation invariants, avoiding intermediate pointer pinning during cache reads, and preventing phantom memory leaks across concurrent map reads.

Prohibited Anti-Pattern: Unchecked Weak Pointer Dereference and Strong Reference Pinning Inside In-Memory Caches

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer In-Memory Cache Reclamation and Finalizer Safety - Go 1.24 introduced native weak pointers via the 'weak' package, enabling GC-cooperative in-memory caches that safely release heap allocations without periodic TTL sweeper overhead. Implementing this pattern requires strict enforcement of dereference validation invariants, avoiding intermediate pointer pinning during cache reads, and preventing phantom memory leaks across concurrent map reads.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-cache-reclamation-invariant"
---

# Go 1.24 Weak Pointer In-Memory Cache Reclamation and Finalizer Safety

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unchecked Weak Pointer Dereference and Strong Reference Pinning Inside In-Memory Caches

## System Constraints
You are a Principal Go Systems Architect enforcing strict memory and concurrency invariants under Go 1.24+. You must ensure all in-memory caching mechanisms utilizing Go 1.24 weak pointers (weak.Pointer) correctly handle GC collection race conditions, avoid resurrecting or pinning unneeded pointer targets, and prevent dead key retention in concurrent cache structures.

## Strict Guidelines
- Engineers MUST ALWAYS dereference weak.Pointer with .Value() and immediately perform a nil check before accessing underlying memory.
- Engineers MUST NOT store raw pointers alongside weak.Pointer values in cache entry structs, as this resurrects strong references and disables GC reclamation.
- Code MUST ensure that the key cleanup routine for collected weak pointer values utilizes synchronization primitives (e.g., sync.Map.CompareAndDelete or RWMutex) to avoid removing newly placed concurrent entries.
- Services MUST compile with Go 1.24+ (go >= 1.24 in go.mod) and target heap-allocated pointer types; weak.Make cannot be invoked on non-pointer types or stack-escaped values whose lifetime is unbounded.
- Components NEVER assume weak.Pointer.Value() will remain non-nil between consecutive invocations without holding a local strong reference.

## Bad vs Good Implementations
### Go 1.24 Weak Pointer Cache Read and Eviction Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding a strong reference alongside weak.Pointer completely nullifies GC cooperative reclamation. Calling wp.Value() repeatedly without capturing a single local strong reference introduces a data race with the GC cycle, where the pointer can transition to nil between checks.
```go
package cache

import (
	"sync"
	"weak" // Go 1.24+
)

type Cache struct {
	mu    sync.Mutex
	items map[string]weak.Pointer[Payload]
	// ANTI-PATTERN: Holding strong reference alongside weak pointer
	strong map[string]*Payload
}
type Payload struct { Data []byte }

func (c *Cache) Get(key string) *Payload {
	c.mu.Lock()
	defer c.mu.Unlock()

	wp, ok := c.items[key]
	if !ok {
		return nil
	}
	// ANTI-PATTERN: Repeated Value() call assumes non-nil stability,
	// and direct return without nil check may cause runtime panic downstream.
	if wp.Value() != nil {
		return wp.Value()
	}
	// ANTI-PATTERN: Blind delete without verifying whether a new pointer was placed
	delete(c.items, key)
	return nil
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation holds only weak pointers in memory, captures wp.Value() in a local variable before nil-checking to prevent mid-flight GC reclamation, and performs double-checked locking before evicting tombstone keys.
```go
package cache

import (
	"sync"
	"weak" // Go 1.24+
)

type Payload struct { Data []byte }

type WeakCache struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[Payload]
}

func NewWeakCache() *WeakCache {
	return &WeakCache{
		items: make(map[string]weak.Pointer[Payload]),
	}
}

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

	// INVARIANT: Capture strong reference locally once to ensure GC does not collect mid-read
	val := wp.Value()
	if val == nil {
		c.mu.Lock()
		// Double-checked eviction: Ensure entry wasn't replaced concurrently
		if current, stillExists := c.items[key]; stillExists && current.Value() == nil {
			delete(c.items, key)
		}
		c.mu.Unlock()
		return nil, false
	}
	return val, true
}

func (c *WeakCache) Put(key string, val *Payload) {
	if val == nil {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[key] = weak.Make(val)
}
```

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 In-Memory Cache Reclamation and Finalizer Safety

Go 1.24 Weak Pointer In-Memory Cache Reclamation and Finalizer Safety defines an industrial-grade behavioral standard for backend engineering. Go 1.24 introduced native weak pointers via the 'weak' package, enabling GC-cooperative in-memory caches that safely release heap allocations without periodic TTL sweeper overhead. Implementing this pattern requires strict enforcement of dereference validation invariants, avoiding intermediate pointer pinning during cache reads, and preventing phantom memory leaks across concurrent map reads. 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: Unchecked Weak Pointer Dereference and Strong Reference Pinning Inside In-Memory Caches 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 DriftUnchecked Weak Pointer Dereference and Strong Reference Pinning Inside In-Memory CachesCritical
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 dereference weak.Pointer with .Value() and immediately perform a nil check before accessing underlying memory.

Engineers MUST ALWAYS dereference weak.Pointer with .Value() and immediately perform a nil check before accessing underlying memory.

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 pointers alongside weak.Pointer values in cache entry structs, as this resurrects strong references and disables GC reclamation.

Engineers MUST NOT store raw pointers alongside weak.Pointer values in cache entry structs, as this resurrects strong references and disables GC 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.
3

Code MUST ensure that the key cleanup routine for collected weak pointer values utilizes synchronization primitives (e.g., sync.Map.CompareAndDelete or RWMutex) to avoid removing newly placed concurrent entries.

Code MUST ensure that the key cleanup routine for collected weak pointer values utilizes synchronization primitives (e.g., sync.Map.CompareAndDelete or RWMutex) to avoid removing newly placed concurrent entries.

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 compile with Go 1.24+ (go >= 1.24 in go.mod) and target heap-allocated pointer types

Services MUST compile with Go 1.24+ (go >= 1.24 in go.mod) and target heap-allocated pointer types; weak.Make cannot be invoked on non-pointer types or stack-escaped values whose lifetime is unbounded.

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 assume weak.Pointer.Value() will remain non-nil between consecutive invocations without holding a local strong reference.

Components NEVER assume weak.Pointer.Value() will remain non-nil between consecutive invocations without holding a local strong reference.

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 In-Memory Cache Reclamation and Finalizer Safety critical for AI coding assistants?

Go 1.24 introduced native weak pointers via the 'weak' package, enabling GC-cooperative in-memory caches that safely release heap allocations without periodic TTL sweeper overhead. Implementing this pattern requires strict enforcement of dereference validation invariants, avoiding intermediate pointer pinning during cache reads, and preventing phantom memory leaks across concurrent map reads. 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 (Unchecked Weak Pointer Dereference and Strong Reference Pinning Inside In-Memory Caches) 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