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

Go 1.24 Weak Pointer Cache Reclamation and Finalizer Isolation Guardrail

Standardizes in-memory cache architectures on Go 1.24 weak pointer semantics (`weak.Pointer`) and decoupled cleanup handlers (`runtime.AddCleanup`). Eliminates mark-and-sweep GC latency spikes caused by large retained heaps and completely prevents object resurrection and cyclic dependency leaks historically induced by `runtime.SetFinalizer`.

Prohibited Anti-Pattern: Retaining Large In-Memory Caches with Strong References or Legacy Finalizers Causing Memory Leaks and GC Pauses

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Reclamation and Finalizer Isolation Guardrail - Standardizes in-memory cache architectures on Go 1.24 weak pointer semantics (`weak.Pointer`) and decoupled cleanup handlers (`runtime.AddCleanup`). Eliminates mark-and-sweep GC latency spikes caused by large retained heaps and completely prevents object resurrection and cyclic dependency leaks historically induced by `runtime.SetFinalizer`.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go124-weak-pointer-cache-finalizer-isolation"
---

# Go 1.24 Weak Pointer Cache Reclamation and Finalizer Isolation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Large In-Memory Caches with Strong References or Legacy Finalizers Causing Memory Leaks and GC Pauses

## System Constraints
You are a Principal Systems Engineer enforcing strict Go 1.24 memory safety and GC-optimization standards. Mandate the usage of the standard library `weak` package (`weak.Make` and `weak.Pointer.Value`) for non-authoritative in-memory caches, canonical maps, and associate cleanup tasks using `runtime.AddCleanup` instead of `runtime.SetFinalizer`. Reject code that re-resurrects objects, retains cyclic references across GC boundaries, or fails to handle nil dereferences on collected weak pointer values.

## Strict Guidelines
- Engineers MUST ALWAYS use Go 1.24 `weak.Pointer[T]` via `weak.Make(&v)` for non-authoritative caching or identity-map registries to permit immediate GC collection without explicit eviction.
- Engineers MUST ALWAYS check for `nil` immediately upon resolving `wp.Value()` before utilizing or promoting the underlying pointer.
- Engineers MUST NOT use `runtime.SetFinalizer` under any circumstances; all deferred resource reclamation MUST use `runtime.AddCleanup` with decoupled state arguments.
- Cleanup functions registered with `runtime.AddCleanup` MUST NOT capture, close over, or reference the target object pointer, as doing so resurrects the object or prevents GC collection.
- Components NEVER store strong pointer references alongside weak references in the same internal table or lookup structure without an asynchronous or generational sweeping mechanism to purge stale weak keys.

## Bad vs Good Implementations
### In-Memory Cache with Weak Pointer Resolution and Isolated Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing strong pointers in an unbounded map creates permanent heap retention, leading to severe GC pause times and OOM crashes. Using `runtime.SetFinalizer` prolongs object lifespan by at least one full GC cycle, risks memory leaks in cyclic references, and implicitly introduces resurrection hazards through closure captures.
```go
package cache

import (
	"runtime"
	"sync"
)

type LargePayload struct {
	ID   string
	Data []byte
}

type Cache struct {
	mu    sync.RWMutex
	items map[string]*LargePayload // Anti-pattern: Strong pointers prevent GC reclamation
}

func (c *Cache) Put(id string, payload *LargePayload) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[id] = payload

	// Anti-pattern: runtime.SetFinalizer delays GC by an extra cycle,
	// fails on circular references, and can resurrect payload by closing over it
	runtime.SetFinalizer(payload, func(p *LargePayload) {
		c.mu.Lock()
		delete(c.items, p.ID) // Closed over pointer resurrects/delays cleanup
		c.mu.Unlock()
	})
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Go 1.24 `weak.Pointer[LargePayload]`, allowing the runtime garbage collector to instantly reclaim payload bytes under memory pressure. `runtime.AddCleanup` receives only the cache key string (`id`), strictly isolating cleanup execution from the target object to guarantee zero object resurrection, optimal GC sweeping latency, and leak-free table pruning.
```go
package cache

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

type LargePayload struct {
	ID   string
	Data []byte
}

type Cache struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[LargePayload]
}

func NewCache() *Cache {
	return &Cache{items: make(map[string]weak.Pointer[LargePayload])}
}

func (c *Cache) Put(payload *LargePayload) {
	c.mu.Lock()
	defer c.mu.Unlock()

	id := payload.ID
	c.items[id] = weak.Make(payload)

	// Go 1.24: Pass primitive or non-pointer state into runtime.AddCleanup to isolate cleanup
	runtime.AddCleanup(payload, func(key string) {
		c.mu.Lock()
		defer c.mu.Unlock()
		if wp, exists := c.items[key]; exists && wp.Value() == nil {
			delete(c.items, key)
		}
	}, id)
}

func (c *Cache) Get(id string) *LargePayload {
	c.mu.RLock()
	wp, exists := c.items[id]
	c.mu.RUnlock()

	if !exists {
		return nil
	}

	// Go 1.24: Explicitly retrieve and nil-check resolved strong pointer
	val := wp.Value()
	if val == nil {
		c.mu.Lock()
		delete(c.items, id)
		c.mu.Unlock()
		return nil
	}
	return val
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 Weak Pointer Cache Reclamation and Finalizer Isolation Guardrail

Go 1.24 Weak Pointer Cache Reclamation and Finalizer Isolation Guardrail defines an industrial-grade behavioral standard for backend engineering. Standardizes in-memory cache architectures on Go 1.24 weak pointer semantics (`weak.Pointer`) and decoupled cleanup handlers (`runtime.AddCleanup`). Eliminates mark-and-sweep GC latency spikes caused by large retained heaps and completely prevents object resurrection and cyclic dependency leaks historically induced by `runtime.SetFinalizer`. 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 Large In-Memory Caches with Strong References or Legacy Finalizers Causing Memory Leaks and GC Pauses 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 Large In-Memory Caches with Strong References or Legacy Finalizers Causing Memory Leaks and GC PausesCritical
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 Go 1.24 `weak.Pointer[T]` via `weak.Make(&v)` for non-authoritative caching or identity-map registries to permit immediate GC collection without explicit eviction.

Engineers MUST ALWAYS use Go 1.24 `weak.Pointer[T]` via `weak.Make(&v)` for non-authoritative caching or identity-map registries to permit immediate GC collection without explicit eviction.

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 ALWAYS check for `nil` immediately upon resolving `wp.Value()` before utilizing or promoting the underlying pointer.

Engineers MUST ALWAYS check for `nil` immediately upon resolving `wp.Value()` before utilizing or promoting the underlying pointer.

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

Engineers MUST NOT use `runtime.SetFinalizer` under any circumstances

Engineers MUST NOT use `runtime.SetFinalizer` under any circumstances; all deferred resource reclamation MUST use `runtime.AddCleanup` with decoupled state arguments.

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

Cleanup functions registered with `runtime.AddCleanup` MUST NOT capture, close over, or reference the target object pointer, as doing so resurrects the object or prevents GC collection.

Cleanup functions registered with `runtime.AddCleanup` MUST NOT capture, close over, or reference the target object pointer, as doing so resurrects the object or prevents GC 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

Components NEVER store strong pointer references alongside weak references in the same internal table or lookup structure without an asynchronous or generational sweeping mechanism to purge stale weak keys.

Components NEVER store strong pointer references alongside weak references in the same internal table or lookup structure without an asynchronous or generational sweeping mechanism to purge stale weak keys.

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 Reclamation and Finalizer Isolation Guardrail critical for AI coding assistants?

Standardizes in-memory cache architectures on Go 1.24 weak pointer semantics (`weak.Pointer`) and decoupled cleanup handlers (`runtime.AddCleanup`). Eliminates mark-and-sweep GC latency spikes caused by large retained heaps and completely prevents object resurrection and cyclic dependency leaks historically induced by `runtime.SetFinalizer`. 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 Large In-Memory Caches with Strong References or Legacy Finalizers Causing Memory Leaks and GC Pauses) 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