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

Go 1.24 Weak-Pointer Contextual Middleware Eviction Invariant

Enforces deterministic eviction of scoped request metadata and auxiliary telemetry stored in process-wide middleware registries using Go 1.24 weak pointers (weak.Make). Eliminates cross-goroutine memory retention and context-bound memory leaks in long-running services without resorting to runtime.SetFinalizer, finalizer queues, or premature garbage collector retention.

Prohibited Anti-Pattern: Retaining Strong References to Short-Lived HTTP Contexts in Global Middleware Registries or Finalizer Queues

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Go 1.24 Weak-Pointer Contextual Middleware Eviction Invariant - Enforces deterministic eviction of scoped request metadata and auxiliary telemetry stored in process-wide middleware registries using Go 1.24 weak pointers (weak.Make). Eliminates cross-goroutine memory retention and context-bound memory leaks in long-running services without resorting to runtime.SetFinalizer, finalizer queues, or premature garbage collector retention.
globs: **/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/go-124-weak-pointer-contextual-middleware-eviction-invariant"
---

# Go 1.24 Weak-Pointer Contextual Middleware Eviction Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining Strong References to Short-Lived HTTP Contexts in Global Middleware Registries or Finalizer Queues

## System Constraints
You are a Principal Backend Architect enforcing memory safety, GC efficiency, and Go 1.24 weak pointer semantics. You must mandate that global middleware telemetry caches, trace mappings, and cross-goroutine context attachments never hold strong references to short-lived request contexts or their state structs. Enforce Go 1.24 weak.Pointer primitives over sync.Map with strong keys, runtime.SetFinalizer chains, and explicit manual eviction callbacks.

## Strict Guidelines
- Engineers MUST ALWAYS use the Go 1.24 'weak' package (weak.Make) when associating long-lived registry states, metrics caches, or debug sessions with short-lived request contexts or transaction objects.
- Engineers MUST NOT use 'runtime.SetFinalizer' or 'runtime.AddCleanup' to perform memory cleanup on context-scoped structs when non-blocking reclamation via weak pointers is sufficient.
- Engineers MUST verify that weak.Pointer.Value() returns a non-nil pointer before dereferencing, ensuring safe degradation if the referenced request struct has already been reclaimed by the runtime.
- Services MUST NOT use strong pointers as keys in persistent sync.Map or map[K]V registries to track inflight HTTP/gRPC request metadata.
- Registry lookup operations MUST be designed to gracefully purge tombstoned weak references during periodic sweeps or subsequent read misses, preventing registry entry bloating.

## Bad vs Good Implementations
### Inflight Request Registry with Weak Pointer Eviction vs Strong Pointer Memory Leak

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing raw, strong pointers to request-scoped structures in a shared process-wide map creates a direct memory leak. Even after the HTTP request terminates and the context goes out of scope, the global map prevents the garbage collector from freeing the 64KB payload and request metadata.
```go
package middleware

import (
	"context"
	"net/http"
	"sync"
)

type RequestMeta struct {
	RequestID string
	Payload   []byte
}

// ANTI-PATTERN: Strong references to RequestMeta prevent GC,
// accumulating unbounded memory in long-lived services under high load.
var globalRegistry = struct {
	sync.RWMutex
	m map[*RequestMeta]string
}{
	m: make(map[*RequestMeta]string),
}

func TrackingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		meta := &RequestMeta{
			RequestID: r.Header.Get("X-Request-ID"),
			Payload:   make([]byte, 1024*64), // 64KB per request
		}
		globalRegistry.Lock()
		globalRegistry.m[meta] = r.RemoteAddr
		globalRegistry.Unlock()

		ctx := context.WithValue(r.Context(), "meta", meta)
		next.ServeHTTP(w, r.WithContext(ctx))
		// Note: If downstream fails, panics, or forgets to explicitly delete,
		// meta remains referenced in globalRegistry indefinitely.
	})
}
```

#### Production Standard (Correct)
> **Standard**: Uses Go 1.24 weak.Make to store a non-retaining reference to RequestMeta. Once the request lifecycle concludes and the strong reference inside the context is dropped, the Go runtime garbage-collects RequestMeta immediately without finalizer execution costs or stop-the-world stalls. The registry implements safe dereferencing with wk.Value() and lazy tombstone removal.
```go
package middleware

import (
	"context"
	"net/http"
	"sync"
	"weak" // Go 1.24+ weak pointer package
)

type contextKey struct{}

type RequestMeta struct {
	RequestID string
	Payload   []byte
}

// PRODUCTION FIX: Store weak pointers. The GC can reclaim RequestMeta
// as soon as the HTTP handler stack releases its strong reference.
type Registry struct {
	mu    sync.RWMutex
	items map[string]weak.Pointer[RequestMeta]
}

var globalRegistry = &Registry{
	items: make(map[string]weak.Pointer[RequestMeta]),
}

func (reg *Registry) Register(id string, meta *RequestMeta) {
	reg.mu.Lock()
	defer reg.mu.Unlock()
	reg.items[id] = weak.Make(meta)
}

func (reg *Registry) Get(id string) *RequestMeta {
	reg.mu.RLock()
	wk, exists := reg.items[id]
	reg.mu.RUnlock()
	if !exists {
		return nil
	}
	val := wk.Value()
	if val == nil {
		reg.mu.Lock()
		delete(reg.items, id) // Lazy eviction of dead weak pointer
		reg.mu.Unlock()
		return nil
	}
	return val
}

func TrackingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		meta := &RequestMeta{
			RequestID: r.Header.Get("X-Request-ID"),
			Payload:   make([]byte, 1024*64),
		}
		globalRegistry.Register(meta.RequestID, meta)

		ctx := context.WithValue(r.Context(), contextKey{}, meta)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
```

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 Contextual Middleware Eviction Invariant

Go 1.24 Weak-Pointer Contextual Middleware Eviction Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic eviction of scoped request metadata and auxiliary telemetry stored in process-wide middleware registries using Go 1.24 weak pointers (weak.Make). Eliminates cross-goroutine memory retention and context-bound memory leaks in long-running services without resorting to runtime.SetFinalizer, finalizer queues, or premature garbage collector retention. 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 to Short-Lived HTTP Contexts in Global Middleware Registries or Finalizer Queues 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 to Short-Lived HTTP Contexts in Global Middleware Registries or Finalizer QueuesCritical
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 the Go 1.24 'weak' package (weak.Make) when associating long-lived registry states, metrics caches, or debug sessions with short-lived request contexts or transaction objects.

Engineers MUST ALWAYS use the Go 1.24 'weak' package (weak.Make) when associating long-lived registry states, metrics caches, or debug sessions with short-lived request contexts or transaction objects.

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 use 'runtime.SetFinalizer' or 'runtime.AddCleanup' to perform memory cleanup on context-scoped structs when non-blocking reclamation via weak pointers is sufficient.

Engineers MUST NOT use 'runtime.SetFinalizer' or 'runtime.AddCleanup' to perform memory cleanup on context-scoped structs when non-blocking reclamation via weak pointers is sufficient.

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 verify that weak.Pointer.Value() returns a non-nil pointer before dereferencing, ensuring safe degradation if the referenced request struct has already been reclaimed by the runtime.

Engineers MUST verify that weak.Pointer.Value() returns a non-nil pointer before dereferencing, ensuring safe degradation if the referenced request struct has already been reclaimed by the runtime.

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 NOT use strong pointers as keys in persistent sync.Map or map[K]V registries to track inflight HTTP/gRPC request metadata.

Services MUST NOT use strong pointers as keys in persistent sync.Map or map[K]V registries to track inflight HTTP/gRPC request metadata.

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

Registry lookup operations MUST be designed to gracefully purge tombstoned weak references during periodic sweeps or subsequent read misses, preventing registry entry bloating.

Registry lookup operations MUST be designed to gracefully purge tombstoned weak references during periodic sweeps or subsequent read misses, preventing registry entry bloating.

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 Contextual Middleware Eviction Invariant critical for AI coding assistants?

Enforces deterministic eviction of scoped request metadata and auxiliary telemetry stored in process-wide middleware registries using Go 1.24 weak pointers (weak.Make). Eliminates cross-goroutine memory retention and context-bound memory leaks in long-running services without resorting to runtime.SetFinalizer, finalizer queues, or premature garbage collector retention. 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 to Short-Lived HTTP Contexts in Global Middleware Registries or Finalizer Queues) 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