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

Go 1.24 Weak-Pointer Dynamic Route Cache & Canonicalization Contract

Enforces Go 1.24 weak pointer semantics (`weak.Pointer`) for dynamic HTTP path-trie canonicalization caches to eliminate cache-induced memory leaks without generational sweep overhead. Mandates non-escaped value validation, atomic nil-checks on dereferencing, and bounded key retention to prevent cardinality-induced heap exhaustion.

Prohibited Anti-Pattern: Retaining Strong References in Path Canonicalization Caches Causing Unbounded Trie Heap Growth

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak-Pointer Dynamic Route Cache & Canonicalization Contract - Enforces Go 1.24 weak pointer semantics (`weak.Pointer`) for dynamic HTTP path-trie canonicalization caches to eliminate cache-induced memory leaks without generational sweep overhead. Mandates non-escaped value validation, atomic nil-checks on dereferencing, and bounded key retention to prevent cardinality-induced heap exhaustion.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-route-cache-contract"
---

# Go 1.24 Weak-Pointer Dynamic Route Cache & Canonicalization Contract

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References in Path Canonicalization Caches Causing Unbounded Trie Heap Growth

## System Constraints
You are a Principal Engineer enforcing Go 1.24 runtime weak pointer invariants (`weak.Pointer`, `weak.Make`) in HTTP path-trie routing and canonicalization layers. You must prevent memory leaks caused by unbounded dynamic path parameter caching, eliminate manual generational sweep goroutines, and guarantee thread-safe weak-pointer dereferencing with strict nil fallback mechanisms.

## Strict Guidelines
- Engineers MUST ALWAYS use `weak.Make` when inserting parsed dynamic route metadata or canonical path entries into global lookup structures.
- Engineers MUST ALWAYS immediately nil-check the return value of `weak.Pointer.Value()` before accessing cached route nodes, treating `nil` as a cache miss.
- Engineers MUST NOT store strong pointers (`*T`) to dynamic route nodes in long-lived canonicalization lookup tables, sync.Maps, or shard registries.
- Engineers MUST combine `weak.Pointer` with `runtime.AddCleanup` when cache keys require eviction alongside garbage-collected route node targets to prevent key-string accumulation.
- Code MUST NEVER cast interior struct fields to weak pointers; weak pointers MUST point directly to heap-allocated struct instances.
- Services MUST NOT run background ticker-based generational sweep goroutines for route caches where Go 1.24 runtime weak-pointer reclamation can naturally govern node lifecycle.
- Components NEVER assume weak-pointer resolution is stable across sequential reads in the same request scope without pinning the resolved strong reference locally.

## Bad vs Good Implementations
### Dynamic Route Canonicalization Cache using Go 1.24 weak.Pointer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing strong `*RouteNode` pointers in a long-lived map prevents the Go garbage collector from ever reclaiming dynamic path instances. When exposed to high-cardinality dynamic paths (e.g., UUID-based URIs), the path-trie table expands infinitely, eventually causing OOM crashes unless manually scavenged via complex generational sweep background jobs.
```go
package router

import "sync"

type RouteNode struct {
	Pattern   string
	Canonical string
	Params    map[string]string
}

type RouteCache struct {
	mu    sync.RWMutex
	nodes map[string]*RouteNode // BAD: Strong references cause unbounded heap retention
}

func (c *RouteCache) GetOrCreate(path string) *RouteNode {
	c.mu.RLock()
	node, exists := c.nodes[path]
	c.mu.RUnlock()
	if exists {
		return node
	}

	c.mu.Lock()
	defer c.mu.Unlock()
	if node, exists = c.nodes[path]; exists {
		return node
	}

	newNode := &RouteNode{
		Pattern:   path,
		Canonical: parseCanonical(path),
		Params:    extractParams(path),
	}
	c.nodes[path] = newNode // Memory leak on high-cardinality endpoints
	return newNode
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Go 1.24 `weak.Pointer[RouteNode]` and `weak.Make(newNode)`. The router holds only weak references in its global registry, allowing the runtime GC to reclaim route nodes when requests finish and active handlers no longer reference them. `runtime.AddCleanup` asynchronously evicts stale string keys upon GC collection, eliminating key-space leaks and avoiding manual generational sweep background goroutines.
```go
package router

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

type RouteNode struct {
	Pattern   string
	Canonical string
	Params    map[string]string
}

type RouteCache struct {
	mu    sync.RWMutex
	nodes map[string]weak.Pointer[RouteNode]
}

func NewRouteCache() *RouteCache {
	return &RouteCache{
		nodes: make(map[string]weak.Pointer[RouteNode]),
	}
}

func (c *RouteCache) GetOrCreate(path string) *RouteNode {
	c.mu.RLock()
	if wp, exists := c.nodes[path]; exists {
		if node := wp.Value(); node != nil {
			c.mu.RUnlock()
			return node
		}
	}
	c.mu.RUnlock()

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

	// Double-check under write lock
	if wp, exists := c.nodes[path]; exists {
		if node := wp.Value(); node != nil {
			return node
		}
	}

	newNode := &RouteNode{
		Pattern:   path,
		Canonical: parseCanonical(path),
		Params:    extractParams(path),
	}

	c.nodes[path] = weak.Make(newNode)

	// Attach runtime cleanup to purge tombstoned map key when node is collected
	runtime.AddCleanup(newNode, func(key string) {
		c.mu.Lock()
		if wp, ok := c.nodes[key]; ok && wp.Value() == nil {
			delete(c.nodes, key)
		}
		c.mu.Unlock()
	}, path)

	return newNode
}
```

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-Pointer Dynamic Route Cache & Canonicalization Contract

Go 1.24 Weak-Pointer Dynamic Route Cache & Canonicalization Contract defines an industrial-grade behavioral standard for backend engineering. Enforces Go 1.24 weak pointer semantics (`weak.Pointer`) for dynamic HTTP path-trie canonicalization caches to eliminate cache-induced memory leaks without generational sweep overhead. Mandates non-escaped value validation, atomic nil-checks on dereferencing, and bounded key retention to prevent cardinality-induced heap exhaustion. 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 Path Canonicalization Caches Causing Unbounded Trie Heap Growth 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 Path Canonicalization Caches Causing Unbounded Trie Heap GrowthCritical
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 `weak.Make` when inserting parsed dynamic route metadata or canonical path entries into global lookup structures.

Engineers MUST ALWAYS use `weak.Make` when inserting parsed dynamic route metadata or canonical path entries into global lookup structures.

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 immediately nil-check the return value of `weak.Pointer.Value()` before accessing cached route nodes, treating `nil` as a cache miss.

Engineers MUST ALWAYS immediately nil-check the return value of `weak.Pointer.Value()` before accessing cached route nodes, treating `nil` as a cache miss.

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 pointers (`*T`) to dynamic route nodes in long-lived canonicalization lookup tables, sync.Maps, or shard registries.

Engineers MUST NOT store strong pointers (`*T`) to dynamic route nodes in long-lived canonicalization lookup tables, sync.Maps, or shard registries.

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 combine `weak.Pointer` with `runtime.AddCleanup` when cache keys require eviction alongside garbage-collected route node targets to prevent key-string accumulation.

Engineers MUST combine `weak.Pointer` with `runtime.AddCleanup` when cache keys require eviction alongside garbage-collected route node targets to prevent key-string accumulation.

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 NEVER cast interior struct fields to weak pointers

Code MUST NEVER cast interior struct fields to weak pointers; weak pointers MUST point directly to heap-allocated struct instances.

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

Services MUST NOT run background ticker-based generational sweep goroutines for route caches where Go 1.24 runtime weak-pointer reclamation can naturally govern node lifecycle.

Services MUST NOT run background ticker-based generational sweep goroutines for route caches where Go 1.24 runtime weak-pointer reclamation can naturally govern node lifecycle.

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 weak-pointer resolution is stable across sequential reads in the same request scope without pinning the resolved strong reference locally.

Components NEVER assume weak-pointer resolution is stable across sequential reads in the same request scope without pinning the resolved strong reference locally.

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 Dynamic Route Cache & Canonicalization Contract critical for AI coding assistants?

Enforces Go 1.24 weak pointer semantics (`weak.Pointer`) for dynamic HTTP path-trie canonicalization caches to eliminate cache-induced memory leaks without generational sweep overhead. Mandates non-escaped value validation, atomic nil-checks on dereferencing, and bounded key retention to prevent cardinality-induced heap exhaustion. 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 Path Canonicalization Caches Causing Unbounded Trie Heap Growth) 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