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

Go 1.24 Weak Reference Cache Eviction Standard

Mandates the use of Go 1.24's native weak package to eliminate memory leaks and unbounded heap growth in high-throughput in-memory entity caches. Caches storing canonical entities must store weak.Pointer instances to permit timely runtime garbage collection, pairing retrievals with mandatory nil checks and deferred key pruning.

Prohibited Anti-Pattern: Retaining Strong Pointers in In-Memory Caches Leading to Unbounded Heap Retention and GC Pressure

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Reference Cache Eviction Standard - Mandates the use of Go 1.24's native weak package to eliminate memory leaks and unbounded heap growth in high-throughput in-memory entity caches. Caches storing canonical entities must store weak.Pointer instances to permit timely runtime garbage collection, pairing retrievals with mandatory nil checks and deferred key pruning.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-1-24-weak-reference-cache-standard"
---

# Go 1.24 Weak Reference Cache Eviction Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong Pointers in In-Memory Caches Leading to Unbounded Heap Retention and GC Pressure

## System Constraints
You are a Principal Go Architect enforcing the Go 1.24 Weak Reference Cache Eviction Standard. Prevent memory leaks by mandating Go 1.24 native weak pointers (weak.Pointer) for secondary in-memory indexes and deduplication caches. Strictly reject strong-pointer retaining caches that bypass runtime GC reclamation.

## Strict Guidelines
- Engineers MUST ALWAYS utilize Go 1.24's 'weak.Make[T](ptr)' when storing non-authoritative entity references in memory lookup maps.
- Engineers MUST ALWAYS test the result of 'wp.Value()' against nil before accessing the underlying object to handle concurrent or prior GC eviction.
- Engineers MUST NOT store strong references to heap objects alongside weak references within the same eviction domain.
- Services MUST implement asynchronous or opportunistically triggered tombstone cleaning for cache keys whose weak pointers resolve to nil.
- Components NEVER assume an object remains pinned between consecutive invocations of 'wp.Value()'; the dereferenced strong pointer must be stored in a local variable for the duration of its use.

## Bad vs Good Implementations
### In-Memory Entity Cache: Strong Pointers vs Go 1.24 weak.Pointer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining strong pointers (*Entity) in the map roots all cached instances to the garbage collector heap graph. Even if the rest of the application finishes processing the entity, the cache keeps the entire byte slice allocated until manual eviction, driving the heap to exhaustion in high-throughput workloads.
```go
package cache

import (
	"sync"
)

type Entity struct {
	ID   string
	Data []byte
}

// BAD: Storing strong pointers prevents the Go GC from reclaiming
// inactive entities, causing unbounded memory growth under load.
type StrongCache struct {
	mu    sync.RWMutex
	items map[string]*Entity
}

func NewStrongCache() *StrongCache {
	return &StrongCache{items: make(map[string]*Entity)}
}

func (c *StrongCache) Put(id string, e *Entity) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[id] = e
}

func (c *StrongCache) Get(id string) *Entity {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.items[id]
}
```

#### Production Standard (Correct)
> **Standard**: Go 1.24's weak.Pointer holds non-owning references. When all external caller references fall out of scope, the GC collects the entity automatically. On cache hit, wp.Value() securely creates a temporary strong pointer pinned to the local stack frame, pruning nil keys opportunistically.
```go
package cache

import (
	"sync"
	"weak"
)

type Entity struct {
	ID   string
	Data []byte
}

// GOOD: Leveraging Go 1.24 weak.Pointer allows the GC to reclaim
// entities whenever external consumers release their strong references.
type WeakCache struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[Entity]
}

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

func (c *WeakCache) Put(id string, e *Entity) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.items[id] = weak.Make(e)
}

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

	// Materialize strong pointer and pin locally
	val := wp.Value()
	if val == nil {
		// Opportunistic tombstone cleanup
		c.mu.Lock()
		delete(c.items, id)
		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.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 Weak Reference Cache Eviction Standard

Go 1.24 Weak Reference Cache Eviction Standard defines an industrial-grade behavioral standard for backend engineering. Mandates the use of Go 1.24's native weak package to eliminate memory leaks and unbounded heap growth in high-throughput in-memory entity caches. Caches storing canonical entities must store weak.Pointer instances to permit timely runtime garbage collection, pairing retrievals with mandatory nil checks and deferred key pruning. 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 Pointers in In-Memory Caches Leading to Unbounded Heap Retention and GC Pressure 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 Pointers in In-Memory Caches Leading to Unbounded Heap Retention and GC PressureCritical
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 utilize Go 1.24's 'weak.Make[T](ptr)' when storing non-authoritative entity references in memory lookup maps.

Engineers MUST ALWAYS utilize Go 1.24's 'weak.Make[T](ptr)' when storing non-authoritative entity references in memory lookup maps.

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 test the result of 'wp.Value()' against nil before accessing the underlying object to handle concurrent or prior GC eviction.

Engineers MUST ALWAYS test the result of 'wp.Value()' against nil before accessing the underlying object to handle concurrent or prior GC 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.
3

Engineers MUST NOT store strong references to heap objects alongside weak references within the same eviction domain.

Engineers MUST NOT store strong references to heap objects alongside weak references within the same eviction domain.

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 implement asynchronous or opportunistically triggered tombstone cleaning for cache keys whose weak pointers resolve to nil.

Services MUST implement asynchronous or opportunistically triggered tombstone cleaning for cache keys whose weak pointers resolve to nil.

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 assume an object remains pinned between consecutive invocations of 'wp.Value()'

Components NEVER assume an object remains pinned between consecutive invocations of 'wp.Value()'; the dereferenced strong pointer must be stored in a local variable for the duration of its use.

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 Reference Cache Eviction Standard critical for AI coding assistants?

Mandates the use of Go 1.24's native weak package to eliminate memory leaks and unbounded heap growth in high-throughput in-memory entity caches. Caches storing canonical entities must store weak.Pointer instances to permit timely runtime garbage collection, pairing retrievals with mandatory nil checks and deferred key pruning. 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 Pointers in In-Memory Caches Leading to Unbounded Heap Retention and GC Pressure) 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