This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte-5-runes-deep-effect-resource-disposal-pattern

Svelte 5 Runes Deep Effect Resource Disposal Pattern

Enforces synchronous return-based cleanup contracts and AbortController scoping inside Svelte 5 `$effect` and `$effect.root` runes. Eliminates orphaned subscriptions, memory leaks, and cross-boundary event pollutions in long-lived isomorphic micro-frontends undergoing dynamic mounting cycles. Prevents asynchronous unhandled teardowns across complex signal trees.

Prohibited Anti-Pattern: Dangling Subscriptions and Asynchronous Void Cleanup in Svelte 5 $effect Blocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Deep Effect Resource Disposal Pattern - Enforces synchronous return-based cleanup contracts and AbortController scoping inside Svelte 5 `$effect` and `$effect.root` runes. Eliminates orphaned subscriptions, memory leaks, and cross-boundary event pollutions in long-lived isomorphic micro-frontends undergoing dynamic mounting cycles. Prevents asynchronous unhandled teardowns across complex signal trees.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-deep-effect-resource-disposal-pattern"
---

# Svelte 5 Runes Deep Effect Resource Disposal Pattern

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Dangling Subscriptions and Asynchronous Void Cleanup in Svelte 5 $effect Blocks

## System Constraints
You are a Principal Software Architect enforcing the Svelte 5 Runes Deep Effect Resource Disposal Pattern. In Svelte 5, effects (`$effect`, `$effect.pre`, `$effect.root`) establish execution boundaries whose teardowns must execute synchronously via returned cleanup functions. You must strictly forbid passing async functions directly to `$effect`, mandate `AbortController` signals for all external event streams/promises, and ensure non-Svelte external subscriptions instantiated within effect boundaries are completely dereferenced and destroyed upon component unmount or signal invalidation.

## Strict Guidelines
- Engineers MUST ALWAYS return a synchronous teardown function `() => void` directly from `$effect` and `$effect.pre` whenever asynchronous tasks, event listeners, or reactive subscriptions are established.
- Engineers MUST NOT pass an async arrow function directly to `$effect(() => { ... })` because Svelte expects a synchronous cleanup function return value, not a Promise.
- Engineers MUST instantiate an `AbortController` at the top of the effect scope to signal cancellation to all fetch calls, intervals, and observers inside asynchronous child closures.
- Engineers MUST encapsulate external or dynamic effect hierarchies created outside standard component lifecycle bounds inside `$effect.root` and manually invoke its returned cleanup function during boundary disposal.
- Code SHOULD prefer deriving state using `$derived` or `$derived.by` instead of instantiating state synchronizations inside `$effect` with manual teardowns.
- Components NEVER store external unsubscribe functions in unbound outer variables without pairing them with deterministic invocation in the effect teardown or `onDestroy` equivalent.

## Bad vs Good Implementations
### Async Task and Event Listener Teardown inside $effect

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring `$effect(async () => ...)` returns a Promise that resolves to the teardown function instead of returning the teardown function synchronously. Svelte 5 runtime drops the returned cleanup function, causing orphaned WebSocket connections and memory leaks during route changes or prop updates in micro-frontends.
```typescript
import { untrack } from 'svelte';

interface StreamProps {
  endpoint: string;
  onData: (payload: unknown) => void;
}

// ANTI-PATTERN: Passing async callback directly into $effect loses the teardown contract
export function setupTelemetryStream(props: StreamProps) {
  $effect(async () => {
    const ws = new WebSocket(props.endpoint);
    ws.onmessage = (event) => {
      props.onData(JSON.parse(event.data));
    };
    
    // Returning a cleanup inside an async function returns a Promise<() => void>,
    // which Svelte ignores completely, causing a perpetual leak.
    return () => {
      ws.close();
    };
  });
}
```

#### Production Standard (Correct)
> **Standard**: The effect callback is strictly synchronous and returns a teardown function directly to the runtime. It binds WebSocket teardown and an AbortController to cleanly cancel async actions and detach event listeners immediately when dependencies change or the component unmounts.
```typescript
import { untrack } from 'svelte';

interface StreamProps {
  endpoint: string;
  onData: (payload: unknown) => void;
}

// PRODUCTION INVARIANT: Synchronous effect body with scoped AbortController teardown
export function setupTelemetryStream(props: StreamProps) {
  $effect(() => {
    const controller = new AbortController();
    const { signal } = controller;
    const ws = new WebSocket(props.endpoint);

    const handleMessage = (event: MessageEvent) => {
      if (!signal.aborted) {
        props.onData(JSON.parse(event.data));
      }
    };

    ws.addEventListener('message', handleMessage, { signal });

    // Synchronous deterministic disposal returned directly to Svelte runtime
    return () => {
      controller.abort();
      ws.removeEventListener('message', handleMessage);
      if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
        ws.close();
      }
    };
  });
}
```

### Manual Boundary Isolation using $effect.root

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `$effect` inside arbitrary classes or outside the component initialization lifecycle without `$effect.root` will attach to the parent component context (if active) or fail, resulting in uncontrolled lifecycles and orphaned subscriptions when the class instance is destroyed.
```typescript
// ANTI-PATTERN: Instantiating nested untracked effect in shared service without root disposal boundary
import { customStore } from './external-store';

export class DynamicPluginManager {
  private state = $state({ active: false });

  public mountPlugin() {
    // $effect called outside component tree without root wrapper leaks when plugin unloads
    $effect(() => {
      const unsubscribe = customStore.subscribe((val) => {
        this.state.active = val.isActive;
      });
      return () => unsubscribe();
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping external lifecycle effect declarations in `$effect.root` provides a manual dispose function (`teardownRoot`). Calling this function guarantees all inner runes effects and their teardown functions are executed, preventing memory leaks in non-component class lifecycles.
```typescript
// PRODUCTION INVARIANT: Explicit $effect.root isolation and manual cleanup hook
import { customStore } from './external-store';

export class DynamicPluginManager {
  public state = $state({ active: false });
  private teardownRoot: (() => void) | null = null;

  public mountPlugin(): void {
    this.unmountPlugin(); // Ensure idempotency

    this.teardownRoot = $effect.root(() => {
      $effect(() => {
        const unsubscribe = customStore.subscribe((val) => {
          this.state.active = val.isActive;
        });
        return () => {
          unsubscribe();
        };
      });
    });
  }

  public unmountPlugin(): void {
    if (this.teardownRoot) {
      this.teardownRoot();
      this.teardownRoot = null;
    }
  }
}
```

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 Deep Effect Resource Disposal Pattern

Svelte 5 Runes Deep Effect Resource Disposal Pattern defines an industrial-grade behavioral standard for frontend engineering. Enforces synchronous return-based cleanup contracts and AbortController scoping inside Svelte 5 `$effect` and `$effect.root` runes. Eliminates orphaned subscriptions, memory leaks, and cross-boundary event pollutions in long-lived isomorphic micro-frontends undergoing dynamic mounting cycles. Prevents asynchronous unhandled teardowns across complex signal trees. 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: Dangling Subscriptions and Asynchronous Void Cleanup in Svelte 5 $effect Blocks 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 DriftDangling Subscriptions and Asynchronous Void Cleanup in Svelte 5 $effect BlocksCritical
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 return a synchronous teardown function `() => void` directly from `$effect` and `$effect.pre` whenever asynchronous tasks, event listeners, or reactive subscriptions are established.

Engineers MUST ALWAYS return a synchronous teardown function `() => void` directly from `$effect` and `$effect.pre` whenever asynchronous tasks, event listeners, or reactive subscriptions are established.

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 pass an async arrow function directly to `$effect(() => { ... })` because Svelte expects a synchronous cleanup function return value, not a Promise.

Engineers MUST NOT pass an async arrow function directly to `$effect(() => { ... })` because Svelte expects a synchronous cleanup function return value, not a Promise.

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 instantiate an `AbortController` at the top of the effect scope to signal cancellation to all fetch calls, intervals, and observers inside asynchronous child closures.

Engineers MUST instantiate an `AbortController` at the top of the effect scope to signal cancellation to all fetch calls, intervals, and observers inside asynchronous child closures.

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 encapsulate external or dynamic effect hierarchies created outside standard component lifecycle bounds inside `$effect.root` and manually invoke its returned cleanup function during boundary disposal.

Engineers MUST encapsulate external or dynamic effect hierarchies created outside standard component lifecycle bounds inside `$effect.root` and manually invoke its returned cleanup function during boundary disposal.

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 SHOULD prefer deriving state using `$derived` or `$derived.by` instead of instantiating state synchronizations inside `$effect` with manual teardowns.

Code SHOULD prefer deriving state using `$derived` or `$derived.by` instead of instantiating state synchronizations inside `$effect` with manual teardowns.

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 NEVER store external unsubscribe functions in unbound outer variables without pairing them with deterministic invocation in the effect teardown or `onDestroy` equivalent.

Components NEVER store external unsubscribe functions in unbound outer variables without pairing them with deterministic invocation in the effect teardown or `onDestroy` equivalent.

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 Deep Effect Resource Disposal Pattern critical for AI coding assistants?

Enforces synchronous return-based cleanup contracts and AbortController scoping inside Svelte 5 `$effect` and `$effect.root` runes. Eliminates orphaned subscriptions, memory leaks, and cross-boundary event pollutions in long-lived isomorphic micro-frontends undergoing dynamic mounting cycles. Prevents asynchronous unhandled teardowns across complex signal trees. 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 (Dangling Subscriptions and Asynchronous Void Cleanup in Svelte 5 $effect Blocks) 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