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

Svelte 5 Runes Async Effect Boundary & Memory Leak Prevention

Enforces strict lifecycle boundaries and deterministic cancellation for asynchronous operations initiated inside Svelte 5 `$effect` blocks. Prevents detached DOM nodes, stale closures, and listener accumulation in long-lived single-page applications by mandating AbortController propagation, synchronous teardown returns, and isolation of untracked async execution paths.

Prohibited Anti-Pattern: Unbounded Async Operations in $effect Without AbortController Teardown Leading to Retained Scope References

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Async Effect Boundary & Memory Leak Prevention - Enforces strict lifecycle boundaries and deterministic cancellation for asynchronous operations initiated inside Svelte 5 `$effect` blocks. Prevents detached DOM nodes, stale closures, and listener accumulation in long-lived single-page applications by mandating AbortController propagation, synchronous teardown returns, and isolation of untracked async execution paths.
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-async-effect-boundary-memory-leak-prevention"
---

# Svelte 5 Runes Async Effect Boundary & Memory Leak Prevention

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded Async Operations in $effect Without AbortController Teardown Leading to Retained Scope References

## System Constraints
You are a Principal Software Architect enforcing Svelte 5 Runes Async Effect Boundary & Memory Leak Prevention. Mandate deterministic cleanup, synchronous teardown returns, explicit AbortSignal wiring, and untracked read isolation in all reactive boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS return a synchronous cleanup function directly from `$effect` that cancels in-flight async operations via `AbortController.abort()` or equivalent disposal hooks.
- Engineers MUST NOT pass an async function directly to `$effect(() => async () => ...)`; `$effect` MUST be synchronous to ensure the teardown handler is registered immediately upon execution.
- Code MUST isolate reads of reactive state occurring after asynchronous microtasks using `untrack()` if those signals should not trigger re-execution of the effect.
- Engineers MUST check `abortSignal.aborted` prior to updating any reactive state (`$state`) following an `await` boundary to avoid mutating unmounted or superseded component scopes.
- Components NEVER store persistent external subscriptions or DOM listeners within `$derived` or `$derived.by` functions, as derived runes are strictly pure computation boundaries with no teardown lifecycle.

## Bad vs Good Implementations
### Async Data Fetching with AbortController Teardown vs. Orphaned Promise Leak

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Async functions passed to $effect resolve to a Promise, meaning the returned value is a Promise rather than a synchronous teardown function. If userId changes before the fetch completes, the prior promise continues running and will overwrite state out of order, retaining references to destroyed scopes.
```typescript
import { untrack } from 'svelte';

// ANTI-PATTERN: Passing an async function to $effect precludes returning a synchronous cleanup.
// Stale updates and retained closures run unchecked if userId changes rapidly or component unmounts.
let userId = $state('user-1');
let profileData = $state<Record<string, unknown> | null>(null);

$effect(async () => {
  const response = await fetch(`/api/users/${userId}`);
  const json = await response.json();
  // Stale closure mutation: overwrites newer responses if requests resolve out-of-order
  profileData = json;
});
```

#### Production Standard (Correct)
> **Standard**: The effect body is synchronous, ensuring the teardown callback is bound immediately. An AbortController invalidates the pending network request on dependency change or component unmount, preventing race-condition mutations and memory retention.
```typescript
import { untrack } from 'svelte';

// PRODUCTION INVARIANT: Synchronous $effect returning an explicit teardown function.
// Propagates AbortSignal to cancel inflight requests and guards state writes against aborted contexts.
let userId = $state('user-1');
let profileData = $state<Record<string, unknown> | null>(null);

$effect(() => {
  const id = userId; // Explicitly tracked dependency
  const controller = new AbortController();

  async function executeFetch(signal: AbortSignal) {
    try {
      const response = await fetch(`/api/users/${id}`, { signal });
      if (signal.aborted) return;
      const json = await response.json();
      if (!signal.aborted) {
        profileData = json;
      }
    } catch (err: unknown) {
      if (err instanceof DOMException && err.name === 'AbortError') return;
      throw err;
    }
  }

  void executeFetch(controller.signal);

  return () => {
    controller.abort();
  };
});
```

### External Event Streaming Lifecycle Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Without returning a synchronous destructor, every reactivity pulse re-instantiates WebSocket connections without closing the former, accumulating background sockets and duplicate memory retention.
```typescript
// ANTI-PATTERN: Creating event streams without teardown inside $effect.pre or reactive blocks
let channelId = $state('general');
let messages = $state<string[]>([]);

$effect(() => {
  const ws = new WebSocket(`wss://chat.domain.com/rooms/${channelId}`);
  ws.onmessage = (event) => {
    messages = [...messages, event.data];
  };
  // Missing teardown: Sockets remain open and leak memory on each channelId update
});
```

#### Production Standard (Correct)
> **Standard**: Explicit removal of event listeners alongside deterministic WebSocket termination inside the teardown callback guarantees no retained network handles or lingering closures across rune transitions.
```typescript
// PRODUCTION INVARIANT: Comprehensive socket lifecycle disposal within effect boundary
let channelId = $state('general');
let messages = $state<string[]>([]);

$effect(() => {
  const activeChannel = channelId;
  const ws = new WebSocket(`wss://chat.domain.com/rooms/${activeChannel}`);

  const handleMessage = (event: MessageEvent<string>) => {
    messages.push(event.data);
  };

  ws.addEventListener('message', handleMessage);

  return () => {
    ws.removeEventListener('message', handleMessage);
    ws.close(1000, 'Boundary disposed');
  };
});
```

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 Async Effect Boundary & Memory Leak Prevention

Svelte 5 Runes Async Effect Boundary & Memory Leak Prevention defines an industrial-grade behavioral standard for frontend engineering. Enforces strict lifecycle boundaries and deterministic cancellation for asynchronous operations initiated inside Svelte 5 `$effect` blocks. Prevents detached DOM nodes, stale closures, and listener accumulation in long-lived single-page applications by mandating AbortController propagation, synchronous teardown returns, and isolation of untracked async execution paths. 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 Operations in $effect Without AbortController Teardown Leading to Retained Scope References 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 Operations in $effect Without AbortController Teardown Leading to Retained Scope ReferencesCritical
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 cleanup function directly from `$effect` that cancels in-flight async operations via `AbortController.abort()` or equivalent disposal hooks.

Engineers MUST ALWAYS return a synchronous cleanup function directly from `$effect` that cancels in-flight async operations via `AbortController.abort()` or equivalent disposal hooks.

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 function directly to `$effect(() => async () => ...)`

Engineers MUST NOT pass an async function directly to `$effect(() => async () => ...)`; `$effect` MUST be synchronous to ensure the teardown handler is registered immediately upon execution.

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 MUST isolate reads of reactive state occurring after asynchronous microtasks using `untrack()` if those signals should not trigger re-execution of the effect.

Code MUST isolate reads of reactive state occurring after asynchronous microtasks using `untrack()` if those signals should not trigger re-execution 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

Engineers MUST check `abortSignal.aborted` prior to updating any reactive state (`$state`) following an `await` boundary to avoid mutating unmounted or superseded component scopes.

Engineers MUST check `abortSignal.aborted` prior to updating any reactive state (`$state`) following an `await` boundary to avoid mutating unmounted or superseded component scopes.

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 store persistent external subscriptions or DOM listeners within `$derived` or `$derived.by` functions, as derived runes are strictly pure computation boundaries with no teardown lifecycle.

Components NEVER store persistent external subscriptions or DOM listeners within `$derived` or `$derived.by` functions, as derived runes are strictly pure computation boundaries with no teardown lifecycle.

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 Effect Boundary & Memory Leak Prevention critical for AI coding assistants?

Enforces strict lifecycle boundaries and deterministic cancellation for asynchronous operations initiated inside Svelte 5 `$effect` blocks. Prevents detached DOM nodes, stale closures, and listener accumulation in long-lived single-page applications by mandating AbortController propagation, synchronous teardown returns, and isolation of untracked async execution paths. 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 Operations in $effect Without AbortController Teardown Leading to Retained Scope References) 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