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

Go 1.24 Weak Pointer Cache Eviction and Zero-Allocation Session Standard

Mandates the use of Go 1.24 weak pointers (weak.Pointer) for ephemeral in-memory session caches to eliminate GC finalizer latency and memory retention leaks. Prohibits runtime.SetFinalizer and strong-pointer map retention, ensuring deterministic reclamation of ephemeral session states without triggering stop-the-world or allocation spikes under heavy loads.

Prohibited Anti-Pattern: Retaining Strong References in In-Memory Maps and Relying on runtime.SetFinalizer for Ephemeral Session Cleanup

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak Pointer Cache Eviction and Zero-Allocation Session Standard - Mandates the use of Go 1.24 weak pointers (weak.Pointer) for ephemeral in-memory session caches to eliminate GC finalizer latency and memory retention leaks. Prohibits runtime.SetFinalizer and strong-pointer map retention, ensuring deterministic reclamation of ephemeral session states without triggering stop-the-world or allocation spikes under heavy loads.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go124-weak-pointer-session-cache-standard"
---

# Go 1.24 Weak Pointer Cache Eviction and Zero-Allocation Session Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References in In-Memory Maps and Relying on runtime.SetFinalizer for Ephemeral Session Cleanup

## System Constraints
You are a Principal Engineer enforcing the Go 1.24 Weak Pointer Cache Eviction and Zero-Allocation Session Standard. Ephemeral session handles, caches, and short-lived state registries must use Go 1.24 weak.Pointer primitives to allow natural garbage collection without pinning memory. You strictly prohibit runtime.SetFinalizer on high-throughput session paths due to finalizer execution latency, heap resurrection risks, and GC mark-sweep stalls. Ensure all cache lookups validate pointer liveness, purge tombstoned keys safely, and reuse memory buffers via sync.Pool to maintain zero allocations on critical paths.

## Strict Guidelines
- Engineers MUST ALWAYS use Go 1.24 `weak.Pointer[T]` via `weak.Make` when registering ephemeral session objects in shared lookup tables or in-memory caches.
- Engineers MUST ALWAYS test the result of `wp.Value()` against `nil` prior to accessing session data to handle concurrent GC reclamation safely.
- Engineers MUST NOT use `runtime.SetFinalizer` or `runtime.AddCleanup` for session state reclamation on high-frequency request paths.
- Services MUST implement opportunistic or batched key tombstone pruning for keys whose `weak.Pointer[T].Value()` returns `nil` to prevent map bucket memory leakage.
- Code MUST combine `weak.Pointer[T]` caches with `sync.Pool` for session object creation to achieve zero-allocation acquisition on hot request paths.
- Engineers MUST NOT store strong references to the session payload within the cache entry struct or map key closure.
- Components NEVER assume session lifetime guarantees from a weak pointer lookup; strong references must only be maintained within the active call frame scope.

## Bad vs Good Implementations
### Go 1.24 Weak Pointer Session Cache Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Retaining strong pointers (*Session) in the cache map prevents the garbage collector from reclaiming sessions once active requests drop their handles. Using runtime.SetFinalizer forces objects to persist for an extra GC cycle, incurs substantial queue overhead on the global finalizer goroutine, and exposes the application to memory bloat under high concurrency.
```go
package session

import (
	"runtime"
	"sync"
)

type Session struct {
	ID    string
	Data  []byte
}

type Cache struct {
	mu    sync.RWMutex
	m     map[string]*Session // BAD: Strong reference pins object indefinitely until manual delete
}

func (c *Cache) Put(s *Session) {
	c.mu.Lock()
	defer c.mu.Unlock()

	// BAD: Finalizer delays reclamation by at least one extra GC cycle
	// and pushes work to a single global finalizer goroutine
	runtime.SetFinalizer(s, func(obj *Session) {
		// Risky resurrection and unbounded latency
	})
	c.m[s.ID] = s
}

func (c *Cache) Get(id string) *Session {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.m[id]
}
```

#### Production Standard (Correct)
> **Standard**: Using Go 1.24 weak.Pointer allows the garbage collector to reclaim sessions the moment client handlers drop their active strong references. Cache lookups safely dereference through wp.Value(), cleaning up dangling map keys opportunistically without blocking runtime GC cycles or suffering finalizer queue latency.
```go
package session

import (
	"sync"
	"weak"
)

type Session struct {
	ID   string
	Data []byte
}

var sessionPool = sync.Pool{
	New: func() any {
		return &Session{
			Data: make([]byte, 0, 1024),
		}
	},
}

type Cache struct {
	mu sync.RWMutex
	m  map[string]weak.Pointer[Session] // GOOD: Weak pointer permits normal GC reclamation
}

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

func (c *Cache) Put(s *Session) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.m[s.ID] = weak.Make(s)
}

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

	s := wp.Value()
	if s == nil {
		// Opportunistic tombstone cleanup
		c.mu.Lock()
		if current, exists := c.m[id]; exists && current.Value() == nil {
			delete(c.m, id)
		}
		c.mu.Unlock()
		return nil, false
	}
	return s, 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 Cache Eviction and Zero-Allocation Session Standard

Go 1.24 Weak Pointer Cache Eviction and Zero-Allocation Session Standard defines an industrial-grade behavioral standard for backend engineering. Mandates the use of Go 1.24 weak pointers (weak.Pointer) for ephemeral in-memory session caches to eliminate GC finalizer latency and memory retention leaks. Prohibits runtime.SetFinalizer and strong-pointer map retention, ensuring deterministic reclamation of ephemeral session states without triggering stop-the-world or allocation spikes under heavy loads. 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 In-Memory Maps and Relying on runtime.SetFinalizer for Ephemeral Session Cleanup 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 In-Memory Maps and Relying on runtime.SetFinalizer for Ephemeral Session CleanupCritical
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]` via `weak.Make` when registering ephemeral session objects in shared lookup tables or in-memory caches.

Engineers MUST ALWAYS use Go 1.24 `weak.Pointer[T]` via `weak.Make` when registering ephemeral session objects in shared lookup tables or in-memory 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 ALWAYS test the result of `wp.Value()` against `nil` prior to accessing session data to handle concurrent GC reclamation safely.

Engineers MUST ALWAYS test the result of `wp.Value()` against `nil` prior to accessing session data to handle concurrent GC reclamation safely.

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 use `runtime.SetFinalizer` or `runtime.AddCleanup` for session state reclamation on high-frequency request paths.

Engineers MUST NOT use `runtime.SetFinalizer` or `runtime.AddCleanup` for session state reclamation on high-frequency request paths.

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 opportunistic or batched key tombstone pruning for keys whose `weak.Pointer[T].Value()` returns `nil` to prevent map bucket memory leakage.

Services MUST implement opportunistic or batched key tombstone pruning for keys whose `weak.Pointer[T].Value()` returns `nil` to prevent map bucket memory leakage.

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 combine `weak.Pointer[T]` caches with `sync.Pool` for session object creation to achieve zero-allocation acquisition on hot request paths.

Code MUST combine `weak.Pointer[T]` caches with `sync.Pool` for session object creation to achieve zero-allocation acquisition on hot request paths.

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

Engineers MUST NOT store strong references to the session payload within the cache entry struct or map key closure.

Engineers MUST NOT store strong references to the session payload within the cache entry struct or map key closure.

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

Components NEVER assume session lifetime guarantees from a weak pointer lookup

Components NEVER assume session lifetime guarantees from a weak pointer lookup; strong references must only be maintained within the active call frame scope.

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 Eviction and Zero-Allocation Session Standard critical for AI coding assistants?

Mandates the use of Go 1.24 weak pointers (weak.Pointer) for ephemeral in-memory session caches to eliminate GC finalizer latency and memory retention leaks. Prohibits runtime.SetFinalizer and strong-pointer map retention, ensuring deterministic reclamation of ephemeral session states without triggering stop-the-world or allocation spikes under heavy loads. 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 In-Memory Maps and Relying on runtime.SetFinalizer for Ephemeral Session Cleanup) 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