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

Go 1.24 Weak Pointer Concurrent Cache Eviction and Memory Reclamation

Enforces Go 1.24 `weak.Pointer` semantics combined with `runtime.AddCleanup` for high-throughput in-memory routing tables, session registries, and object caches. Prevents unbounded heap growth and GC retention cycles by ensuring long-lived cache maps do not anchor active objects past their operational lifecycle.

Prohibited Anti-Pattern: Anchoring Strong References in Concurrent Maps Causing Heap Retention Cycles and OOM

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Concurrent Cache Eviction and Memory Reclamation - Enforces Go 1.24 `weak.Pointer` semantics combined with `runtime.AddCleanup` for high-throughput in-memory routing tables, session registries, and object caches. Prevents unbounded heap growth and GC retention cycles by ensuring long-lived cache maps do not anchor active objects past their operational lifecycle.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-weak-pointer-concurrent-cache-eviction"
---

# Go 1.24 Weak Pointer Concurrent Cache Eviction and Memory Reclamation

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Anchoring Strong References in Concurrent Maps Causing Heap Retention Cycles and OOM

## System Constraints
You are a Principal Go Systems Architect enforcing strict Go 1.24 memory-management and concurrent caching standards. You mandate the use of the Go 1.24 standard library `weak` package (`weak.Make` and `weak.Pointer.Value`) coupled with `runtime.AddCleanup` to decouple cache membership from GC liveness in session tables, routing maps, and canonicalizing deduplicators. Ensure dead tombstone cleanup, atomic strong-promotion validation, and absolute prevention of reference cycles.

## Strict Guidelines
- Engineers MUST ALWAYS use Go 1.24 `weak.Pointer[T]` instead of direct strong pointers `*T` when building canonicalization pools, session caches, and reverse routing tables where the cache should not prevent garbage collection.
- Engineers MUST ALWAYS defensively validate `wp.Value() != nil` when dereferencing a `weak.Pointer[T]` and handle cache misses safely when the runtime collector has reclaimed the object.
- Engineers MUST pair `weak.Pointer` entries with `runtime.AddCleanup` to automatically purge stale keys from concurrent maps when the underlying object is finalized, preventing map bucket memory leaks (tombstone buildup).
- Engineers MUST NOT use deprecated `runtime.SetFinalizer` for cache eviction or lifecycle hooks, as finalizers run asynchronously, delay reclamation across multiple GC cycles, and fail on cyclic references.
- Code MUST avoid re-promoted strong pointers leaking into long-lived closures or background goroutines that outlive the caller's transient execution frame.
- Concurrent cache stores MUST use type-safe wrapper structs over `sync.Map` or partitioned mutex buckets that encapsulate `weak.Pointer[T]` access without leaking raw weak pointers to API consumers.

## Bad vs Good Implementations
### Weak Pointer Session Registry with Automatic Key Eviction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding strong references in `sessions` prevents the Go GC from reclaiming disconnected `Session` instances. Without an explicit, error-prone manual eviction loop, memory grows indefinitely, saturating heap space and increasing GC cycle latencies.
```go
package session

import "sync"

type Session struct {
	ID    string
	Data  []byte
}

// BAD: Strong pointer cache prevents Sessions from being garbage collected
// even when all clients disconnect, causing severe heap bloat.
type Registry struct {
	mu       sync.RWMutex
	sessions map[string]*Session
}

func NewRegistry() *Registry {
	return &Registry{sessions: make(map[string]*Session)}
}

func (r *Registry) Store(s *Session) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.sessions[s.ID] = s
}

func (r *Registry) Get(id string) *Session {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.sessions[id]
}
```

#### Production Standard (Correct)
> **Standard**: By utilizing Go 1.24's `weak.Make` and `weak.Pointer[T]`, the `Registry` holds non-owning references. When clients drop session references, the Go runtime reclaims the heap allocation. `runtime.AddCleanup` safely purges the orphaned map key, preventing tombstone accumulation.
```go
package session

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

type Session struct {
	ID   string
	Data []byte
}

// GOOD: Go 1.24 weak.Pointer allows the session to be collected
// when no active network goroutines hold a reference.
type Registry struct {
	mu       sync.RWMutex
	sessions map[string]weak.Pointer[Session]
}

func NewRegistry() *Registry {
	return &Registry{sessions: make(map[string]weak.Pointer[Session])}
}

func (r *Registry) Store(s *Session) {
	if s == nil {
		return
	}
	r.mu.Lock()
	defer r.mu.Unlock()

	r.sessions[s.ID] = weak.Make(s)

	// Register cleanup to remove the map key once the Session object is collected
	id := s.ID
	runtime.AddCleanup(s, func(targetID string) {
		r.mu.Lock()
		defer r.mu.Unlock()
		if wp, exists := r.sessions[targetID]; exists && wp.Value() == nil {
			delete(r.sessions, targetID)
		}
	}, id)
}

func (r *Registry) Get(id string) (*Session, bool) {
	r.mu.RLock()
	wp, exists := r.sessions[id]
	r.mu.RUnlock()
	if !exists {
		return nil, false
	}

	s := wp.Value()
	if s == nil {
		// Value collected; proactively purge entry
		r.mu.Lock()
		if cur, ok := r.sessions[id]; ok && cur.Value() == nil {
			delete(r.sessions, id)
		}
		r.mu.Unlock()
		return nil, false
	}

	return s, true
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 Weak Pointer Concurrent Cache Eviction and Memory Reclamation

Go 1.24 Weak Pointer Concurrent Cache Eviction and Memory Reclamation defines an industrial-grade behavioral standard for backend engineering. Enforces Go 1.24 `weak.Pointer` semantics combined with `runtime.AddCleanup` for high-throughput in-memory routing tables, session registries, and object caches. Prevents unbounded heap growth and GC retention cycles by ensuring long-lived cache maps do not anchor active objects past their operational lifecycle. 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: Anchoring Strong References in Concurrent Maps Causing Heap Retention Cycles and OOM 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 DriftAnchoring Strong References in Concurrent Maps Causing Heap Retention Cycles and OOMCritical
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]` instead of direct strong pointers `*T` when building canonicalization pools, session caches, and reverse routing tables where the cache should not prevent garbage collection.

Engineers MUST ALWAYS use Go 1.24 `weak.Pointer[T]` instead of direct strong pointers `*T` when building canonicalization pools, session caches, and reverse routing tables where the cache should not prevent garbage 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.
2

Engineers MUST ALWAYS defensively validate `wp.Value() != nil` when dereferencing a `weak.Pointer[T]` and handle cache misses safely when the runtime collector has reclaimed the object.

Engineers MUST ALWAYS defensively validate `wp.Value() != nil` when dereferencing a `weak.Pointer[T]` and handle cache misses safely when the runtime collector has reclaimed the object.

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 pair `weak.Pointer` entries with `runtime.AddCleanup` to automatically purge stale keys from concurrent maps when the underlying object is finalized, preventing map bucket memory leaks (tombstone buildup).

Engineers MUST pair `weak.Pointer` entries with `runtime.AddCleanup` to automatically purge stale keys from concurrent maps when the underlying object is finalized, preventing map bucket memory leaks (tombstone buildup).

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

Engineers MUST NOT use deprecated `runtime.SetFinalizer` for cache eviction or lifecycle hooks, as finalizers run asynchronously, delay reclamation across multiple GC cycles, and fail on cyclic references.

Engineers MUST NOT use deprecated `runtime.SetFinalizer` for cache eviction or lifecycle hooks, as finalizers run asynchronously, delay reclamation across multiple GC cycles, and fail on cyclic references.

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

Code MUST avoid re-promoted strong pointers leaking into long-lived closures or background goroutines that outlive the caller's transient execution frame.

Code MUST avoid re-promoted strong pointers leaking into long-lived closures or background goroutines that outlive the caller's transient execution frame.

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

Concurrent cache stores MUST use type-safe wrapper structs over `sync.Map` or partitioned mutex buckets that encapsulate `weak.Pointer[T]` access without leaking raw weak pointers to API consumers.

Concurrent cache stores MUST use type-safe wrapper structs over `sync.Map` or partitioned mutex buckets that encapsulate `weak.Pointer[T]` access without leaking raw weak pointers to API consumers.

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 Concurrent Cache Eviction and Memory Reclamation critical for AI coding assistants?

Enforces Go 1.24 `weak.Pointer` semantics combined with `runtime.AddCleanup` for high-throughput in-memory routing tables, session registries, and object caches. Prevents unbounded heap growth and GC retention cycles by ensuring long-lived cache maps do not anchor active objects past their operational lifecycle. 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 (Anchoring Strong References in Concurrent Maps Causing Heap Retention Cycles and OOM) 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