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-lifecycle-standard

Go 1.24 Weak Pointer Cache Retention & Cleanup Lifecycle Standard

Enforces non-owning memory references in high-throughput Go caching layers using Go 1.24 weak.Pointer and runtime.AddCleanup. Eliminates sweep-phase GC bloat, memory resurrection leaks, and finalizer-induced goroutine stalls.

Prohibited Anti-Pattern: Retaining Strong References in Caches and Relying on Deprecated runtime.SetFinalizer

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Retention & Cleanup Lifecycle Standard - Enforces non-owning memory references in high-throughput Go caching layers using Go 1.24 weak.Pointer and runtime.AddCleanup. Eliminates sweep-phase GC bloat, memory resurrection leaks, and finalizer-induced goroutine stalls.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-cache-lifecycle-standard"
---

# Go 1.24 Weak Pointer Cache Retention & Cleanup Lifecycle Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References in Caches and Relying on Deprecated runtime.SetFinalizer

## System Constraints
You are a Principal Software Architect enforcing the Go 1.24 Weak Pointer Cache Retention Lifecycle Standard. Mandate the strict replacement of strong pointer cache maps and runtime.SetFinalizer with weak.Pointer and runtime.AddCleanup for all non-owning in-memory caches. Ensure all weak pointer resolutions check for nil, avoid capturing target pointers in cleanups, and maintain bounded memory profiles.

## Strict Guidelines
- Engineers MUST ALWAYS store non-owning references using Go 1.24 weak.Pointer[T] via weak.Make(val) in long-lived internal lookup tables or caches.
- Engineers MUST NOT use runtime.SetFinalizer; use runtime.AddCleanup with pass-by-value metadata to avoid object resurrection and cycle leaks.
- Code MUST ALWAYS check for nil when calling wp.Value() before dereferencing, handling lazy tombstone eviction when expired.
- Cleanups passed to runtime.AddCleanup MUST NEVER capture or hold a strong reference to the target object being finalized.
- Services MUST NOT rely on synchronous cleanup execution; cleanups run asynchronously in background system goroutines and must remain non-blocking.
- Components NEVER re-introduce strong references into lookup structures during sweep or cleanup phases.

## Bad vs Good Implementations
### Weak Pointer In-Memory Cache with AddCleanup Tombstone Eviction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding strong references in `items` forces cached items to remain reachable unless evicted explicitly. Applying `runtime.SetFinalizer` resurrects the object, delays reclamation by at least two GC cycles, and serializes on the single global finalizer goroutine.
```go
package cache

import (
	"runtime"
	"sync"
)

type Item struct {
	Data []byte
}

type Cache struct {
	mu    sync.RWMutex
	items map[string]*Item
}

func (c *Cache) Put(key string, val *Item) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[key] = val

	// ANTI-PATTERN: SetFinalizer causes multi-cycle GC delays, object resurrection,
	// and risks serialization stalls across runtime finalizer queues.
	runtime.SetFinalizer(val, func(i *Item) {
		c.mu.Lock()
		delete(c.items, key)
		c.mu.Unlock()
	})
}
```

#### Production Standard (Correct)
> **Standard**: Uses Go 1.24 `weak.Pointer` to avoid pinning target objects into heap memory across GC sweep phases. Replaces finalizers with `runtime.AddCleanup`, safely passing the map key by value without resurrecting the item or stalling GC sweep routines.
```go
package cache

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

type Item struct {
	Data []byte
}

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

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

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

	val := wp.Value()
	if val == nil {
		c.mu.Lock()
		delete(c.items, key)
		c.mu.Unlock()
		return nil, false
	}
	return val, true
}

func (c *Cache) Put(key string, val *Item) {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.items[key] = weak.Make(val)

	// Pass key by value; do not close over `val` to avoid capturing a strong reference
	runtime.AddCleanup(val, func(cleanupKey string) {
		c.mu.Lock()
		defer c.mu.Unlock()
		if wp, exists := c.items[cleanupKey]; exists && wp.Value() == nil {
			delete(c.items, cleanupKey)
		}
	}, key)
}
```

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 Retention & Cleanup Lifecycle Standard

Go 1.24 Weak Pointer Cache Retention & Cleanup Lifecycle Standard defines an industrial-grade behavioral standard for backend engineering. Enforces non-owning memory references in high-throughput Go caching layers using Go 1.24 weak.Pointer and runtime.AddCleanup. Eliminates sweep-phase GC bloat, memory resurrection leaks, and finalizer-induced goroutine stalls. 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 Caches and Relying on Deprecated runtime.SetFinalizer 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 Caches and Relying on Deprecated runtime.SetFinalizerCritical
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 store non-owning references using Go 1.24 weak.Pointer[T] via weak.Make(val) in long-lived internal lookup tables or caches.

Engineers MUST ALWAYS store non-owning references using Go 1.24 weak.Pointer[T] via weak.Make(val) in long-lived internal lookup tables or caches.

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

Engineers MUST NOT use runtime.SetFinalizer; use runtime.AddCleanup with pass-by-value metadata to avoid object resurrection and cycle leaks.

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 ALWAYS check for nil when calling wp.Value() before dereferencing, handling lazy tombstone eviction when expired.

Code MUST ALWAYS check for nil when calling wp.Value() before dereferencing, handling lazy tombstone eviction when expired.

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

Cleanups passed to runtime.AddCleanup MUST NEVER capture or hold a strong reference to the target object being finalized.

Cleanups passed to runtime.AddCleanup MUST NEVER capture or hold a strong reference to the target object being finalized.

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

Services MUST NOT rely on synchronous cleanup execution

Services MUST NOT rely on synchronous cleanup execution; cleanups run asynchronously in background system goroutines and must remain non-blocking.

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.
6

Components NEVER re-introduce strong references into lookup structures during sweep or cleanup phases.

Components NEVER re-introduce strong references into lookup structures during sweep or cleanup phases.

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 Retention & Cleanup Lifecycle Standard critical for AI coding assistants?

Enforces non-owning memory references in high-throughput Go caching layers using Go 1.24 weak.Pointer and runtime.AddCleanup. Eliminates sweep-phase GC bloat, memory resurrection leaks, and finalizer-induced goroutine stalls. 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 Caches and Relying on Deprecated runtime.SetFinalizer) 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