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

Svelte 5 Runes Async Lifecycle & $effect.root Teardown Standard

Enforces deterministic teardown of reactive dependencies and effects across asynchronous execution contexts and non-component modules in Svelte 5. Prevents catastrophic client-side memory leaks and zombie listeners caused by orphaned effects spawned across microtask boundaries or outside owner hierarchies.

Prohibited Anti-Pattern: Orphaned Reactive Effects via Async Microtasks and Unscoped Non-Component Root Subscriptions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Async Lifecycle & $effect.root Teardown Standard - Enforces deterministic teardown of reactive dependencies and effects across asynchronous execution contexts and non-component modules in Svelte 5. Prevents catastrophic client-side memory leaks and zombie listeners caused by orphaned effects spawned across microtask boundaries or outside owner hierarchies.
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-async-lifecycle-effect-root-teardown"
---

# Svelte 5 Runes Async Lifecycle & $effect.root Teardown Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Orphaned Reactive Effects via Async Microtasks and Unscoped Non-Component Root Subscriptions

## System Constraints
You are a Principal Software Architect enforcing Svelte 5 Runes lifecycle safety. You must mandate deterministic teardown for all reactive dependencies, forbidding async functions as direct $effect callbacks and requiring $effect.root encapsulation for effects instantiated outside synchronous component initialization.

## Strict Guidelines
- Engineers MUST NEVER pass an async function directly to `$effect()` or `$effect.pre()`, because returning a Promise prevents Svelte from registering the synchronous teardown function.
- Engineers MUST instantiate an `AbortController` or explicit cancellation token synchronously within `$effect()` and invoke `controller.abort()` in the returned teardown closure to cancel pending asynchronous tasks.
- Engineers MUST ALWAYS wrap reactive effects instantiated in non-component contexts (such as external state machines, classes in `.svelte.ts`, or global services) inside `$effect.root()`.
- Engineers MUST explicitly capture and expose the cleanup function returned by `$effect.root()`, ensuring consumers invoke it during view transitions, route changes, or component unmounts.
- Engineers MUST NOT spawn `$effect` or `$derived` declarations across asynchronous microtask boundaries (e.g., following an `await` statement or inside `setTimeout`), as the reactive owner context will be lost.
- Components and services MUST use `untrack()` when reading transient signals inside an effect that should not re-trigger the asynchronous workflow.

## Bad vs Good Implementations
### Asynchronous Effect with Deterministic Abort Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing an async function to $effect causes it to return a Promise instead of a teardown function. Svelte 5 ignores Promise returns for teardown, causing in-flight network responses to mutate state after component unmount, leaking memory and producing stale UI updates.
```typescript
import { $effect, $state } from 'svelte';

export function useLiveUserQuery(userId: () => string) {
  let user = $state<any>(null);

  // CRITICAL BUG: Async callback returns Promise<() => void>, bypassing cleanup registration
  $effect(async () => {
    const id = userId();
    const res = await fetch(`/api/users/${id}`);
    user = await res.json();

    return () => {
      // This cleanup is unreachable and never called by Svelte runtime
      console.log('Cleanup never executed');
    };
  });

  return { get user() { return user; } };
}
```

#### Production Standard (Correct)
> **Standard**: The effect callback is synchronous and immediately returns a cleanup function that triggers AbortController.abort(). The async task is safely encapsulated, preventing orphaned state mutations on rapid transitions.
```typescript
import { $effect, $state, untrack } from 'svelte';

export function useLiveUserQuery(userId: () => string) {
  let user = $state<any>(null);

  $effect(() => {
    const id = userId();
    const controller = new AbortController();

    async function fetchUser() {
      try {
        const res = await fetch(`/api/users/${id}`, { signal: controller.signal });
        if (!res.ok) throw new Error('Fetch failed');
        const data = await res.json();
        // Guard against writing if cancelled
        if (!controller.signal.aborted) {
          user = data;
        }
      } catch (err: unknown) {
        if ((err as Error).name !== 'AbortError') {
          throw err;
        }
      }
    }

    fetchUser();

    // Synchronous teardown returned to Svelte's reactive engine
    return () => {
      controller.abort();
    };
  });

  return { get user() { return user; } };
}
```

### Stateful Service Isolation via $effect.root Outside Component Tree

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Invoking $effect directly in a class or external utility without an active component owner fails or produces an orphan effect that cannot be automatically collected, leaking the DOM event listener permanently across view lifecycles.
```typescript
import { $state, $effect } from 'svelte';

export class ViewportTracker {
  width = $state(typeof window !== 'undefined' ? window.innerWidth : 0);

  constructor() {
    // CRITICAL BUG: Creating $effect outside component boundary without owner scope
    // triggers Svelte runtime error 'effect_orphan' or creates an uncollected memory leak
    $effect(() => {
      const onResize = () => { this.width = window.innerWidth; };
      window.addEventListener('resize', onResize);
      return () => window.removeEventListener('resize', onResize);
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: $effect.root isolates and manages the reactive tree manually, returning a deterministic disposal function. Consumers can destroy the tracker during onMount teardown or page unloads, cleanly deregistering all reactive listeners.
```typescript
import { $state, $effect } from 'svelte';

export class ViewportTracker {
  width = $state(typeof window !== 'undefined' ? window.innerWidth : 0);
  private cleanup: (() => void) | null = null;

  constructor() {
    // Explicitly establish an un-parented reactive root scope
    this.cleanup = $effect.root(() => {
      $effect(() => {
        const onResize = () => { this.width = window.innerWidth; };
        window.addEventListener('resize', onResize);
        return () => window.removeEventListener('resize', onResize);
      });
    });
  }

  destroy(): void {
    if (this.cleanup) {
      this.cleanup();
      this.cleanup = null;
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Svelte 5 Runes Async Lifecycle & $effect.root Teardown Standard

Svelte 5 Runes Async Lifecycle & $effect.root Teardown Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic teardown of reactive dependencies and effects across asynchronous execution contexts and non-component modules in Svelte 5. Prevents catastrophic client-side memory leaks and zombie listeners caused by orphaned effects spawned across microtask boundaries or outside owner hierarchies. 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: Orphaned Reactive Effects via Async Microtasks and Unscoped Non-Component Root Subscriptions 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 DriftOrphaned Reactive Effects via Async Microtasks and Unscoped Non-Component Root SubscriptionsCritical
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 NEVER pass an async function directly to `$effect()` or `$effect.pre()`, because returning a Promise prevents Svelte from registering the synchronous teardown function.

Engineers MUST NEVER pass an async function directly to `$effect()` or `$effect.pre()`, because returning a Promise prevents Svelte from registering the synchronous teardown function.

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 an `AbortController` or explicit cancellation token synchronously within `$effect()` and invoke `controller.abort()` in the returned teardown closure to cancel pending asynchronous tasks.

Engineers MUST instantiate an `AbortController` or explicit cancellation token synchronously within `$effect()` and invoke `controller.abort()` in the returned teardown closure to cancel pending asynchronous tasks.

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 ALWAYS wrap reactive effects instantiated in non-component contexts (such as external state machines, classes in `.svelte.ts`, or global services) inside `$effect.root()`.

Engineers MUST ALWAYS wrap reactive effects instantiated in non-component contexts (such as external state machines, classes in `.svelte.ts`, or global services) inside `$effect.root()`.

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 explicitly capture and expose the cleanup function returned by `$effect.root()`, ensuring consumers invoke it during view transitions, route changes, or component unmounts.

Engineers MUST explicitly capture and expose the cleanup function returned by `$effect.root()`, ensuring consumers invoke it during view transitions, route changes, or component unmounts.

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

Engineers MUST NOT spawn `$effect` or `$derived` declarations across asynchronous microtask boundaries (e.g., following an `await` statement or inside `setTimeout`), as the reactive owner context will be lost.

Engineers MUST NOT spawn `$effect` or `$derived` declarations across asynchronous microtask boundaries (e.g., following an `await` statement or inside `setTimeout`), as the reactive owner context will be lost.

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

Components and services MUST use `untrack()` when reading transient signals inside an effect that should not re-trigger the asynchronous workflow.

Components and services MUST use `untrack()` when reading transient signals inside an effect that should not re-trigger the asynchronous workflow.

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 Async Lifecycle & $effect.root Teardown Standard critical for AI coding assistants?

Enforces deterministic teardown of reactive dependencies and effects across asynchronous execution contexts and non-component modules in Svelte 5. Prevents catastrophic client-side memory leaks and zombie listeners caused by orphaned effects spawned across microtask boundaries or outside owner hierarchies. 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 (Orphaned Reactive Effects via Async Microtasks and Unscoped Non-Component Root Subscriptions) 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