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

Go 1.24 Weak Pointer Finalizer-Free In-Memory Cache Invariant

Mandates the use of Go 1.24 standard library weak.Pointer for L1 runtime caches in latency-sensitive RPC services. Prohibits runtime.SetFinalizer and strong-pointer storage in eviction tables to prevent multi-generation GC promotion, stop-the-world finalizer queues, and heap fragmentation.

Prohibited Anti-Pattern: Retaining Strong References or Attaching runtime.SetFinalizer in In-Memory Caches Induces Head-of-Line GC Blocking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Finalizer-Free In-Memory Cache Invariant - Mandates the use of Go 1.24 standard library weak.Pointer for L1 runtime caches in latency-sensitive RPC services. Prohibits runtime.SetFinalizer and strong-pointer storage in eviction tables to prevent multi-generation GC promotion, stop-the-world finalizer queues, and heap fragmentation.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-weak-pointer-finalizer-free-cache-standard"
---

# Go 1.24 Weak Pointer Finalizer-Free In-Memory Cache Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References or Attaching runtime.SetFinalizer in In-Memory Caches Induces Head-of-Line GC Blocking

## System Constraints
You are a Principal Systems Architect enforcing the Go 1.24 Weak Pointer Finalizer-Free In-Memory Cache Invariant. Go 1.24 introduces the official `weak` package, providing zero-overhead, garbage-collector-integrated weak references without finalizer queue delays. You must ensure all ephemeral L1 caches leverage `weak.Pointer` rather than `runtime.SetFinalizer` or unbounded strong pointer maps. Flag any pattern that introduces object resurrection, prolongs GC sweep cycles through finalizers, or fails to validate `wp.Value()` against `nil`.

## Strict Guidelines
- Engineers MUST ALWAYS construct weak references using Go 1.24 `weak.Make(ptr)` on heap-allocated pointer types (*T).
- Engineers MUST NOT attach `runtime.SetFinalizer` to cached entities or cache nodes; finalizers force objects across an extra GC cycle and introduce queue contention.
- Code SHOULD atomically resolve `wp.Value()` on read operations and immediately handle `nil` values as transient cache misses.
- Services MUST NOT retain secondary strong pointers to the cached value within cache metadata, internal sync rings, or custom index keys.
- Components NEVER expose naked weak pointers across service boundaries; cache resolvers must convert validated weak references to strong references before returning to callers.

## Bad vs Good Implementations
### Go 1.24 Weak Pointer Cache Implementation vs. Finalizer Anti-Pattern

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing strong pointers in the cache map combined with runtime.SetFinalizer causes severe GC latency spikes. Finalizers force objects to survive the initial GC sweep, serialize object cleanup onto a single global runtime finalizer queue, and create severe lock-contention and deadlock risks during concurrent sweeps.
```go
package cache

import (
	"runtime"
	"sync"
)

type Item struct {
	Data []byte
}

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

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

	// ANTI-PATTERN: runtime.SetFinalizer delays GC collection by at least
	// one full cycle, risks resurrection, and serializes on the finalizer queue.
	runtime.SetFinalizer(val, func(i *Item) {
		c.mu.Lock()
		delete(c.items, key) // Deadlock hazard and GC latency spike
		c.mu.Unlock()
	})
}

func (c *BadCache) Get(key string) *Item {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.items[key] // Strongly held; cannot be reclaimed under memory pressure
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Go 1.24 `weak.Pointer[Item]` via `weak.Make(val)`. The GC is allowed to reclaim unreferenced cache items in a single collection cycle without finalizer overhead. Dereferencing via `wp.Value()` is thread-safe and allows zero-latency reclamation and opportunistic lazy cleanup.
```go
package cache

import (
	"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) Set(key string, val *Item) {
	if val == nil {
		return
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	// Store weak reference directly; value can be collected cleanly in a single GC pass
	c.items[key] = weak.Make(val)
}

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

	if !ok {
		return nil, false
	}

	// Atomically promote weak pointer to strong pointer
	val := wp.Value()
	if val == nil {
		// GC has already reclaimed the memory; lazily evict dead index entry
		c.mu.Lock()
		delete(c.items, key)
		c.mu.Unlock()
		return nil, false
	}

	return val, true
}
```

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 Finalizer-Free In-Memory Cache Invariant

Go 1.24 Weak Pointer Finalizer-Free In-Memory Cache Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates the use of Go 1.24 standard library weak.Pointer for L1 runtime caches in latency-sensitive RPC services. Prohibits runtime.SetFinalizer and strong-pointer storage in eviction tables to prevent multi-generation GC promotion, stop-the-world finalizer queues, and heap fragmentation. 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 or Attaching runtime.SetFinalizer in In-Memory Caches Induces Head-of-Line GC Blocking 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 or Attaching runtime.SetFinalizer in In-Memory Caches Induces Head-of-Line GC BlockingCritical
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 construct weak references using Go 1.24 `weak.Make(ptr)` on heap-allocated pointer types (*T).

Engineers MUST ALWAYS construct weak references using Go 1.24 `weak.Make(ptr)` on heap-allocated pointer types (*T).

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 attach `runtime.SetFinalizer` to cached entities or cache nodes

Engineers MUST NOT attach `runtime.SetFinalizer` to cached entities or cache nodes; finalizers force objects across an extra GC cycle and introduce queue contention.

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 SHOULD atomically resolve `wp.Value()` on read operations and immediately handle `nil` values as transient cache misses.

Code SHOULD atomically resolve `wp.Value()` on read operations and immediately handle `nil` values as transient cache misses.

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 NOT retain secondary strong pointers to the cached value within cache metadata, internal sync rings, or custom index keys.

Services MUST NOT retain secondary strong pointers to the cached value within cache metadata, internal sync rings, or custom index 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.
5

Components NEVER expose naked weak pointers across service boundaries

Components NEVER expose naked weak pointers across service boundaries; cache resolvers must convert validated weak references to strong references before returning to callers.

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 Finalizer-Free In-Memory Cache Invariant critical for AI coding assistants?

Mandates the use of Go 1.24 standard library weak.Pointer for L1 runtime caches in latency-sensitive RPC services. Prohibits runtime.SetFinalizer and strong-pointer storage in eviction tables to prevent multi-generation GC promotion, stop-the-world finalizer queues, and heap fragmentation. 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 or Attaching runtime.SetFinalizer in In-Memory Caches Induces Head-of-Line GC Blocking) 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