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

Go 1.24 Weak Pointer and Non-Resurrecting Cache Cleanup Standard

Standardizes high-throughput in-memory cache architectures to use Go 1.24 weak.Pointer and runtime.AddCleanup instead of legacy runtime.SetFinalizer or strong-reference maps. Prevents object resurrection, eliminates multi-cycle GC retention, and avoids stop-the-world latency spikes by decoupling cleanup tokens from collected heap allocations.

Prohibited Anti-Pattern: Retaining strong references in cache maps or invoking runtime.SetFinalizer with self-referential closures causing object resurrection.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer and Non-Resurrecting Cache Cleanup Standard - Standardizes high-throughput in-memory cache architectures to use Go 1.24 weak.Pointer and runtime.AddCleanup instead of legacy runtime.SetFinalizer or strong-reference maps. Prevents object resurrection, eliminates multi-cycle GC retention, and avoids stop-the-world latency spikes by decoupling cleanup tokens from collected heap allocations.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-non-resurrecting-cache-standard"
---

# Go 1.24 Weak Pointer and Non-Resurrecting Cache Cleanup Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining strong references in cache maps or invoking runtime.SetFinalizer with self-referential closures causing object resurrection.

## System Constraints
You are a Principal Software Architect enforcing the Go 1.24 Weak Pointer Non-Resurrecting Cache Finalization Standard. You must mandate the strict adoption of Go 1.24 weak reference semantics (`weak.Pointer`) and decoupled cleanup registration (`runtime.AddCleanup`). Ensure caches do not cause GC memory retention, object resurrection, or finalizer deadlock loops.

## Strict Guidelines
- Engineers MUST ALWAYS use `weak.Make` and `weak.Pointer[T]` for non-owning cache entries instead of strong pointer stores or manual pointer masking.
- Engineers MUST NOT invoke `runtime.SetFinalizer` on any cacheable entity; all memory-adjacent resource teardown MUST use `runtime.AddCleanup`.
- Cleanup handlers passed to `runtime.AddCleanup` MUST NEVER capture or receive the target pointer `*T`, and MUST accept only decoupled, trivially copiable identifiers (e.g., string keys, uint64 handles, file descriptors).
- Cache lookups MUST dereference `wp.Value()` into a local variable exactly once per operation and verify `nil` before usage to avoid TOCTOU race conditions during concurrent collection.
- Eviction queues and cache lookup tables MUST maintain cleanup idempotency, ensuring that map removal via cleanup handles do not panic if manual eviction occurred prior to collection.

## Bad vs Good Implementations
### Migrating from runtime.SetFinalizer and Strong Maps to Go 1.24 weak.Pointer with runtime.AddCleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using runtime.SetFinalizer resurrects the item during GC collection, forcing the Go GC to postpone memory reclamation to a subsequent cycle. Because the finalizer closure captures or references the pointer itself, it causes memory retention leaks, prevents timely sweeping, and can stall the runtime finalizer goroutine.
```go
package cache

import (
	runtime
	sync
)

type CacheItem struct {
	Key   string
	Data  []byte
}

type ItemCache struct {
	mu    sync.RWMutex
	items map[string]*CacheItem
}

func (c *ItemCache) Store(key string, data []byte) *CacheItem {
	item := &CacheItem{Key: key, Data: data}
	c.mu.Lock()
	c.items[key] = item
	c.mu.Unlock()

	// ANTI-PATTERN: SetFinalizer causes item to resurrect, postponing deallocation
	// across multiple GC sweeps. Passing item creates an internal self-reference cycle.
	runtime.SetFinalizer(item, func(resurrected *CacheItem) {
		c.mu.Lock()
		delete(c.items, resurrected.Key)
		c.mu.Unlock()
	})
	return item
}
```

#### Production Standard (Correct)
> **Standard**: Go 1.24 weak.Pointer allows the garbage collector to immediately sweep the CacheItem when external strong references are gone. runtime.AddCleanup registers a pure identifier ('key') without capturing or resurrecting the allocated object, preventing GC stalls and keeping cache map bookkeeping strictly non-intrusive.
```go
package cache

import (
	runtime
	sync
	"weak"
)

type CacheItem struct {
	Key  string
	Data []byte
}

type ItemCache struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[CacheItem]
}

func NewItemCache() *ItemCache {
	return &ItemCache{
		items: make(map[string]weak.Pointer[CacheItem]),
	}
}

func (c *ItemCache) Store(key string, data []byte) *CacheItem {
	item := &CacheItem{Key: key, Data: data}
	wp := weak.Make(item)

	c.mu.Lock()
	c.items[key] = wp
	c.mu.Unlock()

	// PRODUCTION INVARIANT: Use runtime.AddCleanup with an immutable, decoupled handle.
	// The closure does NOT capture 'item', preventing object resurrection entirely.
	runtime.AddCleanup(item, func(entryKey string) {
		c.mu.Lock()
		defer c.mu.Unlock()
		// Idempotent purge: only delete if stale or weak value is now nil
		if stored, exists := c.items[entryKey]; exists && stored.Value() == nil {
			delete(c.items, entryKey)
		}
	}, key)

	return item
}

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

	// Atomic snapshot evaluation avoids TOCTOU race
	val := wp.Value()
	if val == nil {
		return nil, false
	}
	return val, true
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 Weak Pointer and Non-Resurrecting Cache Cleanup Standard

Go 1.24 Weak Pointer and Non-Resurrecting Cache Cleanup Standard defines an industrial-grade behavioral standard for backend engineering. Standardizes high-throughput in-memory cache architectures to use Go 1.24 weak.Pointer and runtime.AddCleanup instead of legacy runtime.SetFinalizer or strong-reference maps. Prevents object resurrection, eliminates multi-cycle GC retention, and avoids stop-the-world latency spikes by decoupling cleanup tokens from collected heap allocations. 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 in cache maps or invoking runtime.SetFinalizer with self-referential closures causing object resurrection. 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 in cache maps or invoking runtime.SetFinalizer with self-referential closures causing object resurrection.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 use `weak.Make` and `weak.Pointer[T]` for non-owning cache entries instead of strong pointer stores or manual pointer masking.

Engineers MUST ALWAYS use `weak.Make` and `weak.Pointer[T]` for non-owning cache entries instead of strong pointer stores or manual pointer masking.

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 invoke `runtime.SetFinalizer` on any cacheable entity

Engineers MUST NOT invoke `runtime.SetFinalizer` on any cacheable entity; all memory-adjacent resource teardown MUST use `runtime.AddCleanup`.

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

Cleanup handlers passed to `runtime.AddCleanup` MUST NEVER capture or receive the target pointer `*T`, and MUST accept only decoupled, trivially copiable identifiers (e.g., string keys, uint64 handles, file descriptors).

Cleanup handlers passed to `runtime.AddCleanup` MUST NEVER capture or receive the target pointer `*T`, and MUST accept only decoupled, trivially copiable identifiers (e.g., string keys, uint64 handles, file descriptors).

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

Cache lookups MUST dereference `wp.Value()` into a local variable exactly once per operation and verify `nil` before usage to avoid TOCTOU race conditions during concurrent collection.

Cache lookups MUST dereference `wp.Value()` into a local variable exactly once per operation and verify `nil` before usage to avoid TOCTOU race conditions during concurrent 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.
5

Eviction queues and cache lookup tables MUST maintain cleanup idempotency, ensuring that map removal via cleanup handles do not panic if manual eviction occurred prior to collection.

Eviction queues and cache lookup tables MUST maintain cleanup idempotency, ensuring that map removal via cleanup handles do not panic if manual eviction occurred prior to 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.
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 and Non-Resurrecting Cache Cleanup Standard critical for AI coding assistants?

Standardizes high-throughput in-memory cache architectures to use Go 1.24 weak.Pointer and runtime.AddCleanup instead of legacy runtime.SetFinalizer or strong-reference maps. Prevents object resurrection, eliminates multi-cycle GC retention, and avoids stop-the-world latency spikes by decoupling cleanup tokens from collected heap allocations. 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 in cache maps or invoking runtime.SetFinalizer with self-referential closures causing object resurrection.) 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