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

Go 1.24 Weak-Pointer Cache Eviction Invariant in HTTP Handlers

Enforces safe utilization of Go 1.24 runtime weak pointers (weak.Pointer) and runtime cleanups (runtime.AddCleanup) inside high-throughput HTTP handler caching tiers. Guarantees immediate reclamation of heavy payload memory during GC pressure while eliminating unbounded map key growth and dereference nil panics under multi-gigabit traffic.

Prohibited Anti-Pattern: Retaining strong payload pointers in global handler caches or dereferencing Go 1.24 weak pointers without nil-fallback reconstruction.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak-Pointer Cache Eviction Invariant in HTTP Handlers - Enforces safe utilization of Go 1.24 runtime weak pointers (weak.Pointer) and runtime cleanups (runtime.AddCleanup) inside high-throughput HTTP handler caching tiers. Guarantees immediate reclamation of heavy payload memory during GC pressure while eliminating unbounded map key growth and dereference nil panics under multi-gigabit traffic.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-weak-pointer-cache-eviction-invariant"
---

# Go 1.24 Weak-Pointer Cache Eviction Invariant in HTTP Handlers

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining strong payload pointers in global handler caches or dereferencing Go 1.24 weak pointers without nil-fallback reconstruction.

## System Constraints
You are a Principal Systems Engineer enforcing Go 1.24 memory invariants in high-concurrency microservices. Mandate the use of weak.Pointer for ephemeral HTTP response caching to eradicate GC heap retention and stop memory fragmentation under saturated I/O conditions.

## Strict Guidelines
- Engineers MUST ALWAYS dereference Go 1.24 weak pointers using weak.Pointer[T].Value() and immediately verify the returned pointer is non-nil before accessing payload members.
- Engineers MUST NOT store strong pointer references (*T) inside long-lived cache structures, sync.Map instances, or shared package singletons when handling dynamic or large response buffers.
- Code MUST bind cache map key eviction to the reclamation of the underlying target object using Go 1.24 runtime.AddCleanup to prevent stale weak pointer handle leakage in maps.
- Services MUST re-hydrate cached objects atomically under lock or singleflight when weak.Pointer[T].Value() returns nil due to concurrent garbage collection.
- Handlers NEVER expose raw internal cache weak references across execution boundaries or Goroutine lifecycles without materializing a locally scoped strong pointer.

## Bad vs Good Implementations
### Go 1.24 Ephemeral HTTP Payload Cache with Weak Pointers & runtime.AddCleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing strong pointers (*CacheEntry) prevents garbage collection even when active HTTP handlers complete. Under multi-gigabit traffic, memory balloons rapidly, inducing severe heap fragmentation, allocator latency spikes, and eventual OOM termination.
```go
package handler

import (
	"net/http"
	"sync"
)

type CacheEntry struct {
	Payload []byte
}

// Bad: Retains strong references to heavy payloads indefinitely.
// Multi-gigabit throughput causes heap retention spikes and severe GC pause times.
type PayloadCache struct {
	mu    sync.RWMutex
	items map[string]*CacheEntry
}

func (c *PayloadCache) GetOrCompute(key string, compute func() []byte) []byte {
	c.mu.Lock()
	defer c.mu.Unlock()

	if entry, exists := c.items[key]; exists {
		return entry.Payload
	}

	data := compute()
	c.items[key] = &CacheEntry{Payload: data}
	return data
}

func ServePayload(w http.ResponseWriter, r *http.Request, cache *PayloadCache) {
	payload := cache.GetOrCompute(r.URL.Path, func() []byte {
		return make([]byte, 10<<20) // 10MB payload
	})
	w.Write(payload)
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Go 1.24 weak.Make and weak.Pointer[CacheEntry]. The strong reference exists solely for the lifespan of the handling goroutine. When GC runs, unreferenced payloads are freed without manual TTL management, while runtime.AddCleanup safely purges dangling map keys.
```go
package handler

import (
	"net/http"
	"runtime"
	"sync"
	"weak"
)

type CacheEntry struct {
	Payload []byte
}

// Good: Stores Go 1.24 weak.Pointer[T]. Payloads are reclaimed during GC cycles
// if no active HTTP request goroutine holds a strong reference.
type PayloadCache struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[CacheEntry]
}

func NewPayloadCache() *PayloadCache {
	return &PayloadCache{
		items: make(map[string]weak.Pointer[CacheEntry]),
	}
}

func (c *PayloadCache) GetOrCompute(key string, compute func() []byte) *CacheEntry {
	c.mu.RLock()
	wp, exists := c.items[key]
	c.mu.RUnlock()

	if exists {
		if entry := wp.Value(); entry != nil {
			return entry
		}
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	// Double-check after lock acquisition
	if wp, exists := c.items[key]; exists {
		if entry := wp.Value(); entry != nil {
			return entry
		}
	}

	entry := &CacheEntry{Payload: compute()}
	c.items[key] = weak.Make(entry)

	// Clean up map key when entry is swept by GC (Go 1.24)
	runtime.AddCleanup(entry, func(k string) {
		c.mu.Lock()
		delete(c.items, k)
		c.mu.Unlock()
	}, key)

	return entry
}

func ServePayload(w http.ResponseWriter, r *http.Request, cache *PayloadCache) {
	entry := cache.GetOrCompute(r.URL.Path, func() []byte {
		return make([]byte, 10<<20) // 10MB payload safely collected after transmission
	})
	w.Write(entry.Payload)
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Go 1.24 Weak-Pointer Cache Eviction Invariant in HTTP Handlers

Go 1.24 Weak-Pointer Cache Eviction Invariant in HTTP Handlers defines an industrial-grade behavioral standard for backend engineering. Enforces safe utilization of Go 1.24 runtime weak pointers (weak.Pointer) and runtime cleanups (runtime.AddCleanup) inside high-throughput HTTP handler caching tiers. Guarantees immediate reclamation of heavy payload memory during GC pressure while eliminating unbounded map key growth and dereference nil panics under multi-gigabit traffic. 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 payload pointers in global handler caches or dereferencing Go 1.24 weak pointers without nil-fallback reconstruction. 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 payload pointers in global handler caches or dereferencing Go 1.24 weak pointers without nil-fallback reconstruction.Critical
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 dereference Go 1.24 weak pointers using weak.Pointer[T].Value() and immediately verify the returned pointer is non-nil before accessing payload members.

Engineers MUST ALWAYS dereference Go 1.24 weak pointers using weak.Pointer[T].Value() and immediately verify the returned pointer is non-nil before accessing payload members.

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 store strong pointer references (*T) inside long-lived cache structures, sync.Map instances, or shared package singletons when handling dynamic or large response buffers.

Engineers MUST NOT store strong pointer references (*T) inside long-lived cache structures, sync.Map instances, or shared package singletons when handling dynamic or large response buffers.

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 MUST bind cache map key eviction to the reclamation of the underlying target object using Go 1.24 runtime.AddCleanup to prevent stale weak pointer handle leakage in maps.

Code MUST bind cache map key eviction to the reclamation of the underlying target object using Go 1.24 runtime.AddCleanup to prevent stale weak pointer handle leakage in 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.
4

Services MUST re-hydrate cached objects atomically under lock or singleflight when weak.Pointer[T].Value() returns nil due to concurrent garbage collection.

Services MUST re-hydrate cached objects atomically under lock or singleflight when weak.Pointer[T].Value() returns nil due to concurrent 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.
5

Handlers NEVER expose raw internal cache weak references across execution boundaries or Goroutine lifecycles without materializing a locally scoped strong pointer.

Handlers NEVER expose raw internal cache weak references across execution boundaries or Goroutine lifecycles without materializing a locally scoped strong pointer.

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 Invariant in HTTP Handlers critical for AI coding assistants?

Enforces safe utilization of Go 1.24 runtime weak pointers (weak.Pointer) and runtime cleanups (runtime.AddCleanup) inside high-throughput HTTP handler caching tiers. Guarantees immediate reclamation of heavy payload memory during GC pressure while eliminating unbounded map key growth and dereference nil panics under multi-gigabit traffic. 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 payload pointers in global handler caches or dereferencing Go 1.24 weak pointers without nil-fallback reconstruction.) 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