This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte-5-runes-hydration-graph-teardown

Svelte 5 Runes Reactive Graph Isolation and SSR Teardown Standard

Enforces strict boundary encapsulation of Svelte 5 reactive signal graphs within component trees and explicit root scopes. Prohibits global module-scoped rune allocations and untracked dynamic subscriptions that lead to memory leaks in SSR worker threads and retained signal graphs post-hydration. Mandates explicit graph disposal via $effect.root cleanup functions and per-request context factories.

Prohibited Anti-Pattern: Global Module-Level Runes and Unscoped Reactive Signal Graphs in Universal Code

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Reactive Graph Isolation and SSR Teardown Standard - Enforces strict boundary encapsulation of Svelte 5 reactive signal graphs within component trees and explicit root scopes. Prohibits global module-scoped rune allocations and untracked dynamic subscriptions that lead to memory leaks in SSR worker threads and retained signal graphs post-hydration. Mandates explicit graph disposal via $effect.root cleanup functions and per-request context factories.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-hydration-graph-teardown"
---

# Svelte 5 Runes Reactive Graph Isolation and SSR Teardown Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Global Module-Level Runes and Unscoped Reactive Signal Graphs in Universal Code

## System Constraints
You are a Principal Software Architect enforcing the Svelte 5 Runes Fine-Grained Reactive Graph Memory Boundary Standard. Svelte 5 uses a runtime push-pull signal graph. Any reactive rune ($state, $derived, $effect) defined in module-level scope or instantiated outside a component tree without an $effect.root wrapper creates a permanent, non-garbage-collected reference that persists across SSR requests and retains the entire DOM/reactive context. You must mandate component-scoped or Context-scoped state instantiation and deterministic $effect.root cleanup.

## Strict Guidelines
- Engineers MUST NOT declare mutable runes ($state, $derived) at top-level module scope in universal code (.svelte.ts or .ts modules shared between server and client).
- Engineers MUST instantiate shared cross-component state via factory functions bound to Svelte component contexts using setContext and getContext.
- Code creating dynamic reactive scopes outside component lifecycles MUST wrap execution in $effect.root() and invoke the returned cleanup function on destruction.
- Services managing long-lived signal graphs MUST implement an explicit destroy() or dispose() method that cleans up all signal subscriptions and active listeners.
- Components NEVER attach $effect hooks to external global event emitters or subjects without returning an explicit cleanup callback inside the effect.

## Bad vs Good Implementations
### Module-Scoped Signal Leak vs. Context-Scoped State Factory

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting a singleton instance containing runes at the module level attaches the reactive signals to the global process runtime. In SSR environments, this singleton leaks user data across requests, prevents V8 garbage collection of subscriber graphs, and causes hydration mismatches and unbounded memory growth on client route changes.
```typescript
// src/lib/stores/session.svelte.ts
// FATAL: Top-level module-scoped rune retains memory across all incoming SSR requests
// and causes state pollution between different authenticated users in Node.js/SSR runtimes.
class GlobalSessionStore {
  user = $state<{ id: string; name: string } | null>(null);
  isAuthenticated = $derived(this.user !== null);
}

export const sessionStore = new GlobalSessionStore();
```

#### Production Standard (Correct)
> **Standard**: Encapsulating rune state within an instantiable class accessed through Svelte's Context API ensures that every SSR render pass and client component tree has a discrete, isolated signal graph. When the component unmounts, the entire context branch is automatically reclaimed by the garbage collector.
```typescript
// src/lib/stores/session.svelte.ts
import { getContext, setContext } from 'svelte';

export class SessionStore {
  user = $state<{ id: string; name: string } | null>(null);
  isAuthenticated = $derived(this.user !== null);

  constructor(initialUser: { id: string; name: string } | null = null) {
    this.user = initialUser;
  }
}

const SESSION_KEY = Symbol('SESSION_KEY');

export function setSessionStore(initialUser: { id: string; name: string } | null = null): SessionStore {
  const store = new SessionStore(initialUser);
  return setContext(SESSION_KEY, store);
}

export function getSessionStore(): SessionStore {
  const store = getContext<SessionStore>(SESSION_KEY);
  if (!store) {
    throw new Error('SessionStore accessed outside component context hierarchy');
  }
  return store;
}
```

### Standalone Reactive Graph with Explicit $effect.root Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling $effect outside an active component initialization context fails silently or throws depending on environment, and if called inside an unscoped utility, it creates an unmanaged reactive node that can never be garbage collected, leaking listeners whenever createExternalTracker is called.
```typescript
// src/lib/services/tracker.svelte.ts
// FATAL: Instantiating reactive roots outside component tree without capture or teardown
export function createExternalTracker(sourceSignal: () => number) {
  let lastVal = $state(0);
  
  // Memory leak: This effect persists indefinitely without component lifecycle coupling
  $effect(() => {
    lastVal = sourceSignal();
    console.log('Value changed:', lastVal);
  });

  return { get value() { return lastVal; } };
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping external or dynamic signal operations in $effect.root provides a reference to the graph cleanup routine. Calling cleanup() explicitly cuts all bidirectional edges in the reactive graph, detaching dependencies and permitting immediate V8 garbage collection.
```typescript
// src/lib/services/tracker.svelte.ts
export interface ExternalTracker {
  readonly value: number;
  dispose: () => void;
}

export function createExternalTracker(sourceSignal: () => number): ExternalTracker {
  let lastVal = $state(0);
  
  // Deterministic isolation: $effect.root creates an explicit ownership boundary
  const cleanup = $effect.root(() => {
    $effect(() => {
      lastVal = sourceSignal();
    });
  });

  return {
    get value() {
      return lastVal;
    },
    dispose() {
      cleanup();
    }
  };
}
```

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: Svelte 5 Runes Reactive Graph Isolation and SSR Teardown Standard

Svelte 5 Runes Reactive Graph Isolation and SSR Teardown Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary encapsulation of Svelte 5 reactive signal graphs within component trees and explicit root scopes. Prohibits global module-scoped rune allocations and untracked dynamic subscriptions that lead to memory leaks in SSR worker threads and retained signal graphs post-hydration. Mandates explicit graph disposal via $effect.root cleanup functions and per-request context factories. 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: Global Module-Level Runes and Unscoped Reactive Signal Graphs in Universal Code 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 DriftGlobal Module-Level Runes and Unscoped Reactive Signal Graphs in Universal CodeCritical
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 NOT declare mutable runes ($state, $derived) at top-level module scope in universal code (.svelte.ts or .ts modules shared between server and client).

Engineers MUST NOT declare mutable runes ($state, $derived) at top-level module scope in universal code (.svelte.ts or .ts modules shared between server and client).

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 instantiate shared cross-component state via factory functions bound to Svelte component contexts using setContext and getContext.

Engineers MUST instantiate shared cross-component state via factory functions bound to Svelte component contexts using setContext and getContext.

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 creating dynamic reactive scopes outside component lifecycles MUST wrap execution in $effect.root() and invoke the returned cleanup function on destruction.

Code creating dynamic reactive scopes outside component lifecycles MUST wrap execution in $effect.root() and invoke the returned cleanup function on destruction.

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 managing long-lived signal graphs MUST implement an explicit destroy() or dispose() method that cleans up all signal subscriptions and active listeners.

Services managing long-lived signal graphs MUST implement an explicit destroy() or dispose() method that cleans up all signal subscriptions and active listeners.

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

Components NEVER attach $effect hooks to external global event emitters or subjects without returning an explicit cleanup callback inside the effect.

Components NEVER attach $effect hooks to external global event emitters or subjects without returning an explicit cleanup callback inside the effect.

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 Svelte 5 Runes Reactive Graph Isolation and SSR Teardown Standard critical for AI coding assistants?

Enforces strict boundary encapsulation of Svelte 5 reactive signal graphs within component trees and explicit root scopes. Prohibits global module-scoped rune allocations and untracked dynamic subscriptions that lead to memory leaks in SSR worker threads and retained signal graphs post-hydration. Mandates explicit graph disposal via $effect.root cleanup functions and per-request context factories. 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 (Global Module-Level Runes and Unscoped Reactive Signal Graphs in Universal Code) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Svelte