This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte-5-universal-context-boundary-isolation-standard

Svelte 5 Universal Context Boundary Isolation and SSR Reactive Graph Concurrency Guardrail

Enforces rigid request-boundary isolation for Svelte 5 reactive primitives ($state, $derived) in multi-tenant SSR environments. Prevents catastrophic cross-request data leaks and signal graph memory accumulation by eliminating module-level reactive singletons in favor of scoped component tree contexts.

Prohibited Anti-Pattern: Module-Scoped Reactive Singletons Leaking Multi-Tenant State and Retaining Signal Graphs in High-Concurrency SSR

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Universal Context Boundary Isolation and SSR Reactive Graph Concurrency Guardrail - Enforces rigid request-boundary isolation for Svelte 5 reactive primitives ($state, $derived) in multi-tenant SSR environments. Prevents catastrophic cross-request data leaks and signal graph memory accumulation by eliminating module-level reactive singletons in favor of scoped component tree contexts.
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-universal-context-boundary-isolation-standard"
---

# Svelte 5 Universal Context Boundary Isolation and SSR Reactive Graph Concurrency Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Module-Scoped Reactive Singletons Leaking Multi-Tenant State and Retaining Signal Graphs in High-Concurrency SSR

## System Constraints
You are a Principal Software Architect enforcing the Svelte 5 Universal Context Boundary Isolation Standard. In server-side rendering (SSR), module-level state persists across requests across the Node.js/runtime process lifetime. You must reject any module-level reactive runes ($state, $derived) and force strictly encapsulated context-bound state instantiated within component lifecycles or request handlers.

## Strict Guidelines
- Engineers MUST NEVER declare reactive primitives ($state, $derived, $state.raw) in the global or module scope of *.svelte.ts or *.ts files consumed during SSR.
- Engineers MUST ALWAYS encapsulate request- or tenant-specific state inside classes or closure factories instantiated per-component lifecycle using Svelte 5 setContext/getContext with unique Symbol keys.
- Components NEVER import a shared reactive singleton directly; all shared reactive domain models MUST be retrieved via an explicit typed context accessor hook (e.g., useTenantSession()).
- Code MUST explicitly throw a descriptive invariant error if a context accessor function is invoked outside an active Svelte component initialization lifecycle.
- Services MUST keep reactive state instances strictly isolated to the component tree or explicit request event boundaries (event.locals in SvelteKit) to allow garbage collection of the reactive graph immediately following render completion.

## Bad vs Good Implementations
### Preventing Module-Level Reactive Singletons in Multi-Tenant SSR

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Svelte 5 SSR, module-scoped $state is evaluated once per Node.js process. When multiple tenants execute SSR requests concurrently, Tenant A's state overrides and leaks into Tenant B's render pipeline. Additionally, the reactive dependency nodes are never reclaimed by the garbage collector, driving exponential memory leaks.
```typescript
// tenantSession.svelte.ts
// VULNERABILITY: Module-scoped rune acts as a server-wide singleton across all concurrent requests.
export interface Session {
  tenantId: string;
  userId: string;
  cart: string[];
}

// Module-level reactive state retains subscriber graphs and bleeds across tenant requests
export const session = $state<Session>({
  tenantId: '',
  userId: '',
  cart: []
});

export function setTenantSession(next: Session) {
  session.tenantId = next.tenantId;
  session.userId = next.userId;
  session.cart = [...next.cart];
}
```

#### Production Standard (Correct)
> **Standard**: The TenantSessionStore binds to the Svelte component tree via setContext. Every SSR request initializes its own unique store instance inside its root layout or page boundary. When SSR completes, the component tree and its reactive graph are completely de-referenced and collected by the garbage collector, guaranteeing zero multi-tenant data bleed.
```typescript
// tenantSession.svelte.ts
import { getContext, setContext } from 'svelte';

export interface Session {
  readonly tenantId: string;
  readonly userId: string;
  readonly cart: readonly string[];
}

const SESSION_KEY = Symbol.for('svelte5.tenant.session.boundary');

export class TenantSessionStore {
  #state = $state<Session>({
    tenantId: '',
    userId: '',
    cart: []
  });

  constructor(initial: Session) {
    this.#state = initial;
  }

  get current(): Session {
    return this.#state;
  }

  updateCart(items: string[]): void {
    this.#state = {
      ...this.#state,
      cart: items
    };
  }
}

export function createTenantSessionContext(initial: Session): TenantSessionStore {
  const store = new TenantSessionStore(initial);
  setContext(SESSION_KEY, store);
  return store;
}

export function useTenantSession(): TenantSessionStore {
  const store = getContext<TenantSessionStore>(SESSION_KEY);
  if (!store) {
    throw new Error('TenantSessionContext invariant violation: Accessed outside component hierarchy boundary.');
  }
  return store;
}
```

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 Universal Context Boundary Isolation and SSR Reactive Graph Concurrency Guardrail

Svelte 5 Universal Context Boundary Isolation and SSR Reactive Graph Concurrency Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces rigid request-boundary isolation for Svelte 5 reactive primitives ($state, $derived) in multi-tenant SSR environments. Prevents catastrophic cross-request data leaks and signal graph memory accumulation by eliminating module-level reactive singletons in favor of scoped component tree contexts. 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: Module-Scoped Reactive Singletons Leaking Multi-Tenant State and Retaining Signal Graphs in High-Concurrency SSR 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 DriftModule-Scoped Reactive Singletons Leaking Multi-Tenant State and Retaining Signal Graphs in High-Concurrency SSRCritical
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 declare reactive primitives ($state, $derived, $state.raw) in the global or module scope of *.svelte.ts or *.ts files consumed during SSR.

Engineers MUST NEVER declare reactive primitives ($state, $derived, $state.raw) in the global or module scope of *.svelte.ts or *.ts files consumed during SSR.

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 ALWAYS encapsulate request- or tenant-specific state inside classes or closure factories instantiated per-component lifecycle using Svelte 5 setContext/getContext with unique Symbol keys.

Engineers MUST ALWAYS encapsulate request- or tenant-specific state inside classes or closure factories instantiated per-component lifecycle using Svelte 5 setContext/getContext with unique Symbol keys.

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

Components NEVER import a shared reactive singleton directly

Components NEVER import a shared reactive singleton directly; all shared reactive domain models MUST be retrieved via an explicit typed context accessor hook (e.g., useTenantSession()).

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

Code MUST explicitly throw a descriptive invariant error if a context accessor function is invoked outside an active Svelte component initialization lifecycle.

Code MUST explicitly throw a descriptive invariant error if a context accessor function is invoked outside an active Svelte component initialization 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.
5

Services MUST keep reactive state instances strictly isolated to the component tree or explicit request event boundaries (event.locals in SvelteKit) to allow garbage collection of the reactive graph immediately following render completion.

Services MUST keep reactive state instances strictly isolated to the component tree or explicit request event boundaries (event.locals in SvelteKit) to allow garbage collection of the reactive graph immediately following render completion.

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 Universal Context Boundary Isolation and SSR Reactive Graph Concurrency Guardrail critical for AI coding assistants?

Enforces rigid request-boundary isolation for Svelte 5 reactive primitives ($state, $derived) in multi-tenant SSR environments. Prevents catastrophic cross-request data leaks and signal graph memory accumulation by eliminating module-level reactive singletons in favor of scoped component tree contexts. 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 (Module-Scoped Reactive Singletons Leaking Multi-Tenant State and Retaining Signal Graphs in High-Concurrency SSR) 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