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

Go 1.24 weak.Pointer and runtime.AddCleanup Memory Reclamation Standard

Enforces Go 1.24 weak references (weak.Pointer) and non-resurrecting cleanup hooks (runtime.AddCleanup) over legacy runtime.SetFinalizer in high-throughput proxies and caching layers. Prevents GC pause spikes, object resurrection, multi-cycle sweep delays, and finalizer-induced memory leaks.

Prohibited Anti-Pattern: Legacy runtime.SetFinalizer Object Resurrection and Strong-Reference Cache Bloat Inducing Tail Latency

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 weak.Pointer and runtime.AddCleanup Memory Reclamation Standard - Enforces Go 1.24 weak references (weak.Pointer) and non-resurrecting cleanup hooks (runtime.AddCleanup) over legacy runtime.SetFinalizer in high-throughput proxies and caching layers. Prevents GC pause spikes, object resurrection, multi-cycle sweep delays, and finalizer-induced memory leaks.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-addcleanup-reclamation"
---

# Go 1.24 weak.Pointer and runtime.AddCleanup Memory Reclamation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Legacy runtime.SetFinalizer Object Resurrection and Strong-Reference Cache Bloat Inducing Tail Latency

## System Constraints
You are a Principal Systems Engineer enforcing the Go 1.24 Weak Pointer & AddCleanup Memory Reclamation Standard. Mandate the strict deprecation of runtime.SetFinalizer in favor of runtime.AddCleanup and enforce weak.Pointer for secondary cache indexing, canonicalization maps, and ephemeron structures. Ensure that cleanup arguments never capture or re-reference the target object to guarantee zero-cycle memory reclamation.

## Strict Guidelines
- Engineers MUST NEVER use runtime.SetFinalizer; all resource deallocation must use Go 1.24 runtime.AddCleanup.
- Cleanup functions registered via runtime.AddCleanup MUST NEVER capture or take the tracked pointer as an argument, directly or via closure, to avoid pinning memory.
- Engineers MUST pass only non-pointer handles, scalar values, or detached state structs as the argument parameter to runtime.AddCleanup.
- In-memory caches, canonicalization tables, and intern pools MUST store weak.Pointer[T] instances created via weak.Make rather than strong pointers to permit single-cycle collection.
- Callers reading a weak reference MUST immediately check for nil via weak.Pointer.Value() before dereferencing, handling evicted items gracefully without panicking.
- Cleanup callbacks MUST NOT perform blocking network I/O, heavy channel operations, or acquire high-contention mutexes; offload deferred work to dedicated worker pools if necessary.

## Bad vs Good Implementations
### Migrating Legacy SetFinalizer to Go 1.24 runtime.AddCleanup with Isolated State

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: runtime.SetFinalizer resurrects the target object during the finalizer run, extending its lifetime across multiple GC cycles. Passing the object itself creates cyclic references and delays collection, creating severe GC pause spikes under heavy heap allocation.
```go
package cache

import (
	"os"
	"runtime"
)

type MappedBuffer struct {
	file *os.File
	data []byte
}

func NewMappedBuffer(f *os.File, b []byte) *MappedBuffer {
	buf := &MappedBuffer{file: f, data: b}
	// ANTI-PATTERN: SetFinalizer causes object resurrection, requires at least
	// two GC cycles to reclaim, fails silently on cyclic dependencies, and pins the struct.
	runtime.SetFinalizer(buf, func(b *MappedBuffer) {
		_ = b.file.Close() // Accidental resurrection of b during finalization
	})
	return buf
}
```

#### Production Standard (Correct)
> **Standard**: runtime.AddCleanup guarantees that the cleanup function receives only bufferCleanupState without retaining a reference to MappedBuffer. The object is collected in a single GC cycle with zero object resurrection.
```go
package cache

import (
	"os"
	"runtime"
)

type MappedBuffer struct {
	// data buffer retained in memory
	data []byte
}

type bufferCleanupState struct {
	fd uintptr
}

func cleanupBuffer(state bufferCleanupState) {
	// Runs concurrently when MappedBuffer is unreachable. Does not resurrect MappedBuffer.
	_ = os.NewFile(state.fd, "").Close()
}

func NewMappedBuffer(f *os.File, b []byte) *MappedBuffer {
	buf := &MappedBuffer{data: b}
	state := bufferCleanupState{fd: f.Fd()}

	// INVARIANT: Go 1.24 runtime.AddCleanup attaches cleanup to an isolated scalar/struct state.
	// It does NOT retain 'buf', enabling single-cycle GC reclamation.
	runtime.AddCleanup(buf, cleanupBuffer, state)
	return buf
}
```

### High-Throughput Canonical Cache using Go 1.24 weak.Pointer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing strong pointers in an indexing or canonicalization cache retains entries indefinitely until explicitly evicted, causing cache ballooning and forcing GC to traverse massive live heaps.
```go
package proxy

import "sync"

type Entry struct {
	Payload []byte
}

type Cache struct {
	mu    sync.RWMutex
	items map[string]*Entry // ANTI-PATTERN: Strong references prevent GC collection
}

func (c *Cache) Get(key string) *Entry {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.items[key]
}
```

#### Production Standard (Correct)
> **Standard**: Using weak.Make stores a weak reference (weak.Pointer[T]). When consumer references fall away, the GC reclaims the underlying Entry memory without requiring explicit eviction sweeps, drastically reducing memory pressure.
```go
package proxy

import (
	"sync"
	"weak"
)

type Entry struct {
	Payload []byte
}

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

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

func (c *WeakCache) GetOrStore(key string, factory func() *Entry) *Entry {
	c.mu.Lock()
	defer c.mu.Unlock()

	if wp, ok := c.items[key]; ok {
		if val := wp.Value(); val != nil {
			return val // Cache hit: item is still live
		}
	}

	// Cache miss or collected by GC: allocate and record weak reference
	entry := factory()
	c.items[key] = weak.Make(entry)
	return entry
}
```

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 and runtime.AddCleanup Memory Reclamation Standard

Go 1.24 weak.Pointer and runtime.AddCleanup Memory Reclamation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces Go 1.24 weak references (weak.Pointer) and non-resurrecting cleanup hooks (runtime.AddCleanup) over legacy runtime.SetFinalizer in high-throughput proxies and caching layers. Prevents GC pause spikes, object resurrection, multi-cycle sweep delays, and finalizer-induced memory leaks. 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: Legacy runtime.SetFinalizer Object Resurrection and Strong-Reference Cache Bloat Inducing Tail Latency 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 DriftLegacy runtime.SetFinalizer Object Resurrection and Strong-Reference Cache Bloat Inducing Tail LatencyCritical
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 NEVER use runtime.SetFinalizer

Engineers MUST NEVER use runtime.SetFinalizer; all resource deallocation must use Go 1.24 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.
2

Cleanup functions registered via runtime.AddCleanup MUST NEVER capture or take the tracked pointer as an argument, directly or via closure, to avoid pinning memory.

Cleanup functions registered via runtime.AddCleanup MUST NEVER capture or take the tracked pointer as an argument, directly or via closure, to avoid pinning 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.
3

Engineers MUST pass only non-pointer handles, scalar values, or detached state structs as the argument parameter to runtime.AddCleanup.

Engineers MUST pass only non-pointer handles, scalar values, or detached state structs as the argument parameter to 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.
4

In-memory caches, canonicalization tables, and intern pools MUST store weak.Pointer[T] instances created via weak.Make rather than strong pointers to permit single-cycle collection.

In-memory caches, canonicalization tables, and intern pools MUST store weak.Pointer[T] instances created via weak.Make rather than strong pointers to permit single-cycle 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

Callers reading a weak reference MUST immediately check for nil via weak.Pointer.Value() before dereferencing, handling evicted items gracefully without panicking.

Callers reading a weak reference MUST immediately check for nil via weak.Pointer.Value() before dereferencing, handling evicted items gracefully without panicking.

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

Cleanup callbacks MUST NOT perform blocking network I/O, heavy channel operations, or acquire high-contention mutexes

Cleanup callbacks MUST NOT perform blocking network I/O, heavy channel operations, or acquire high-contention mutexes; offload deferred work to dedicated worker pools if necessary.

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 runtime.AddCleanup Memory Reclamation Standard critical for AI coding assistants?

Enforces Go 1.24 weak references (weak.Pointer) and non-resurrecting cleanup hooks (runtime.AddCleanup) over legacy runtime.SetFinalizer in high-throughput proxies and caching layers. Prevents GC pause spikes, object resurrection, multi-cycle sweep delays, and finalizer-induced memory leaks. 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 (Legacy runtime.SetFinalizer Object Resurrection and Strong-Reference Cache Bloat Inducing Tail Latency) 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