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

Svelte 5 Runes Fine-Grained Effect Disposer Bounds & Teardown Lifecycle

Enforces strict cleanup contracts and scope boundaries for Svelte 5 $effect and $effect.pre runes within high-frequency streaming dashboards. Guarantees that dynamically mounted DOM branch transitions and reactive subscription switches explicitly return teardown disposers to prevent catastrophic detached DOM and WebSocket listener leaks.

Prohibited Anti-Pattern: Unbounded Async Side-Effects and Missing Teardown Disposers in Svelte 5 $effect Runes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Fine-Grained Effect Disposer Bounds & Teardown Lifecycle - Enforces strict cleanup contracts and scope boundaries for Svelte 5 $effect and $effect.pre runes within high-frequency streaming dashboards. Guarantees that dynamically mounted DOM branch transitions and reactive subscription switches explicitly return teardown disposers to prevent catastrophic detached DOM and WebSocket listener leaks.
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-effect-disposer-bounds"
---

# Svelte 5 Runes Fine-Grained Effect Disposer Bounds & Teardown Lifecycle

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded Async Side-Effects and Missing Teardown Disposers in Svelte 5 $effect Runes

## System Constraints
You are a Principal Frontend Architect enforcing deterministic memory management and reactivity lifecycles in Svelte 5. You must validate that all $effect, $effect.pre, and $effect.root invocations handling high-frequency subscriptions or asynchronous operations maintain strict disposer contracts across component and conditional DOM boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS return a synchronous teardown cleanup function from $effect blocks that establish external event listeners, timers, WebSockets, or Worker channels.
- Engineers MUST NOT pass async functions directly to $effect or $effect.pre because Svelte 5 ignores returned Promises, bypassing cleanup registration.
- Code SHOULD encapsulate asynchronous setup logic inside an internal async IIFE or helper while synchronously returning the abort/teardown function from the root of the $effect.
- Components NEVER execute global event subscriptions or imperative canvas/WebGL loops inside $derived expressions or naked component initialization script blocks; all dynamic side-effects MUST be bounded to $effect.
- Services MUST leverage AbortController signals linked to the returned disposer to guarantee cancellation of inflight microtasks when dependencies change or branch contexts unmount.
- Engineers MUST use $effect.root when creating manual reactive root scopes outside the Svelte component tree, and MUST explicitly invoke the returned disposer during teardown.

## Bad vs Good Implementations
### Asynchronous Real-Time Stream Subscription Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Async functions return a Promise<Function>. Svelte 5 $effect expects either undefined or a synchronous () => void disposer. Passing an async function leaves WebSocket connections active indefinitely upon symbol change or DOM branch unmount, leading to detached DOM references and network socket leaks.
```typescript
// In a high-frequency Svelte 5 dashboard component (e.g., SymbolDetail.svelte)
let { symbol = $bindable() }: { symbol: string } = $props();

// ANTI-PATTERN: Passing an async function directly to $effect.
// Svelte 5 does not await the promise or extract the returned cleanup function from a resolved promise.
$effect(async () => {
  const socket = new WebSocket(`wss://stream.market.com/quotes/${symbol}`);
  socket.onmessage = (event) => {
    console.log(JSON.parse(event.data));
  };
  // This cleanup return is lost inside the unresolved Promise!
  return () => {
    socket.close();
  };
});
```

#### Production Standard (Correct)
> **Standard**: The $effect function synchronously executes and returns a clean disposer callback. Using AbortController in tandem with socket.close ensures both in-flight microtasks and transport layers are immediately torn down whenever the reactive dependency (`symbol`) invalidates or the component is unmounted.
```typescript
// In a high-frequency Svelte 5 dashboard component (e.g., SymbolDetail.svelte)
let { symbol }: { symbol: string } = $props();

// CORRECT: Synchronous effect body with explicit AbortController and synchronous disposer contract
$effect(() => {
  const controller = new AbortController();
  const { signal } = controller;
  const socket = new WebSocket(`wss://stream.market.com/quotes/${symbol}`);

  socket.addEventListener('message', (event) => {
    if (signal.aborted) return;
    const data = JSON.parse(event.data);
    // update bounded reactive state safely
  }, { signal });

  // Synchronously returned cleanup ensures deterministic disposer execution
  return () => {
    controller.abort();
    if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
      socket.close();
    }
  };
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Svelte 5 Runes Fine-Grained Effect Disposer Bounds & Teardown Lifecycle

Svelte 5 Runes Fine-Grained Effect Disposer Bounds & Teardown Lifecycle defines an industrial-grade behavioral standard for frontend engineering. Enforces strict cleanup contracts and scope boundaries for Svelte 5 $effect and $effect.pre runes within high-frequency streaming dashboards. Guarantees that dynamically mounted DOM branch transitions and reactive subscription switches explicitly return teardown disposers to prevent catastrophic detached DOM and WebSocket listener leaks. 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: Unbounded Async Side-Effects and Missing Teardown Disposers in Svelte 5 $effect Runes 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 DriftUnbounded Async Side-Effects and Missing Teardown Disposers in Svelte 5 $effect RunesCritical
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 cleanup function from $effect blocks that establish external event listeners, timers, WebSockets, or Worker channels.

Engineers MUST ALWAYS return a synchronous teardown cleanup function from $effect blocks that establish external event listeners, timers, WebSockets, or Worker channels.

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 async functions directly to $effect or $effect.pre because Svelte 5 ignores returned Promises, bypassing cleanup registration.

Engineers MUST NOT pass async functions directly to $effect or $effect.pre because Svelte 5 ignores returned Promises, bypassing cleanup registration.

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 SHOULD encapsulate asynchronous setup logic inside an internal async IIFE or helper while synchronously returning the abort/teardown function from the root of the $effect.

Code SHOULD encapsulate asynchronous setup logic inside an internal async IIFE or helper while synchronously returning the abort/teardown function from the root of 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.
4

Components NEVER execute global event subscriptions or imperative canvas/WebGL loops inside $derived expressions or naked component initialization script blocks

Components NEVER execute global event subscriptions or imperative canvas/WebGL loops inside $derived expressions or naked component initialization script blocks; all dynamic side-effects MUST be bounded to $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.
5

Services MUST leverage AbortController signals linked to the returned disposer to guarantee cancellation of inflight microtasks when dependencies change or branch contexts unmount.

Services MUST leverage AbortController signals linked to the returned disposer to guarantee cancellation of inflight microtasks when dependencies change or branch contexts unmount.

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

Engineers MUST use $effect.root when creating manual reactive root scopes outside the Svelte component tree, and MUST explicitly invoke the returned disposer during teardown.

Engineers MUST use $effect.root when creating manual reactive root scopes outside the Svelte component tree, and MUST explicitly invoke the returned disposer during teardown.

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 Fine-Grained Effect Disposer Bounds & Teardown Lifecycle critical for AI coding assistants?

Enforces strict cleanup contracts and scope boundaries for Svelte 5 $effect and $effect.pre runes within high-frequency streaming dashboards. Guarantees that dynamically mounted DOM branch transitions and reactive subscription switches explicitly return teardown disposers to prevent catastrophic detached DOM and WebSocket listener leaks. 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 (Unbounded Async Side-Effects and Missing Teardown Disposers in Svelte 5 $effect Runes) 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