This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: tanstack-query-v5-stream-cancellation-gc-eviction

TanStack Query v5 Stream Cancellation and Bounded Memory Eviction

High-frequency streaming interfaces (SSE, WebSockets, or chunked transfer feeds) managed by TanStack Query v5 must explicitly link query cancellation tokens to the underlying transport abort protocol. Infinite streaming queries must configure strict sliding memory bounds using maxPages and deterministic garbage collection eviction timeouts (gcTime) to prevent runaway heap expansion and catastrophic browser tab crashes on unmount.

Prohibited Anti-Pattern: Ignoring QueryFunctionContext.signal in streaming queries while accumulating unbounded infinite pages with unevicted cache lifetimes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Query v5 Stream Cancellation and Bounded Memory Eviction - High-frequency streaming interfaces (SSE, WebSockets, or chunked transfer feeds) managed by TanStack Query v5 must explicitly link query cancellation tokens to the underlying transport abort protocol. Infinite streaming queries must configure strict sliding memory bounds using maxPages and deterministic garbage collection eviction timeouts (gcTime) to prevent runaway heap expansion and catastrophic browser tab crashes on unmount.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tanstack-query-v5-stream-cancellation-gc-eviction"
---

# TanStack Query v5 Stream Cancellation and Bounded Memory Eviction

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Ignoring QueryFunctionContext.signal in streaming queries while accumulating unbounded infinite pages with unevicted cache lifetimes.

## System Constraints
You are a Principal Frontend Architect enforcing zero-leak streaming lifecycles in TanStack Query v5. Every streaming queryFn must wire the provided AbortSignal to the underlying transport, infinite queries must enforce a bounded window via maxPages, and unmounted streaming caches must be immediately scheduled for garbage collection eviction.

## Strict Guidelines
- Engineers MUST ALWAYS extract and wire `signal` from `QueryFunctionContext` to the underlying network transport (Fetch, EventSource, or WebSocket reader).
- Engineers MUST ALWAYS enforce `maxPages` in `useInfiniteQuery` options when processing unbounded real-time chunks or event bursts to maintain a strictly bounded heap footprint.
- Engineers MUST NOT use `gcTime: Infinity` on real-time streaming queries; `gcTime` MUST be constrained to a strictly finite duration (or `0` when cache persistence across unmounts is hazardous).
- Code MUST explicitly cancel the `ReadableStreamDefaultReader` or invoke `EventSource.close()` inside the `signal.addEventListener('abort', ...)` callback if manual consumption is required.
- Components NEVER unmount without propagating query cancellation; when components unmount, engineers SHOULD verify `queryClient.cancelQueries` or active signal teardown triggers immediately.

## Bad vs Good Implementations
### Unbounded Infinite Stream without Abort Signal vs Bounded Deterministic GC Stream

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The queryFn ignores `context.signal`, preventing TanStack Query from cancelling the underlying HTTP connection upon component unmount or query invalidation. Furthermore, omitting `maxPages` and setting `gcTime: Infinity` causes the browser heap to accumulate every appended page indefinitely, inevitably triggering Out-Of-Memory (OOM) tab crashes.
```typescript
import { useInfiniteQuery } from '@tanstack/react-query';

interface StreamChunk {
  id: string;
  data: string[];
}

export function useLiveTelemetryBad() {
  return useInfiniteQuery({
    queryKey: ['telemetry', 'live'],
    // CRITICAL: Ignores QueryFunctionContext.signal; streaming continues on unmount
    queryFn: async ({ pageParam = 0 }) => {
      const response = await fetch(`/api/telemetry/stream?cursor=${pageParam}`);
      const chunk: StreamChunk = await response.json();
      return chunk;
    },
    initialPageParam: 0,
    getNextPageParam: (lastPage) => Number(lastPage.id) + 1,
    // CRITICAL: Infinite gcTime and no maxPages causes unbounded heap growth
    gcTime: Infinity,
    staleTime: 0,
  });
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation forwards `signal` to `fetch`, ensuring immediate connection termination and network socket deallocation when unmounted. Setting `maxPages: 20` bounds the in-memory pagination structure to a sliding window, while `gcTime: 1000 * 60 * 2` guarantees dormant stream nodes are purged from the QueryCache heap deterministically.
```typescript
import { useInfiniteQuery } from '@tanstack/react-query';

interface StreamChunk {
  id: string;
  data: string[];
}

const MAX_PAGE_LIMIT = 20;
const STREAM_GC_TIME = 1000 * 60 * 2; // 2 minutes

export function useLiveTelemetryGood() {
  return useInfiniteQuery({
    queryKey: ['telemetry', 'live'],
    // Mandatory: Forward QueryFunctionContext.signal to fetch
    queryFn: async ({ pageParam, signal }): Promise<StreamChunk> => {
      const response = await fetch(`/api/telemetry/stream?cursor=${pageParam}`, {
        signal,
        headers: { Accept: 'application/json' },
      });

      if (!response.ok) {
        throw new Error(`Telemetry stream failed: ${response.statusText}`);
      }

      return response.json();
    },
    initialPageParam: 0,
    getNextPageParam: (lastPage) => Number(lastPage.id) + 1,
    // Mandatory: Constrain in-memory page buffer to prevent memory bloat
    maxPages: MAX_PAGE_LIMIT,
    // Mandatory: Bounded cache eviction to release GC handles
    gcTime: STREAM_GC_TIME,
    staleTime: 1000 * 5,
  });
}
```

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: TanStack Query v5 Stream Cancellation and Bounded Memory Eviction

TanStack Query v5 Stream Cancellation and Bounded Memory Eviction defines an industrial-grade behavioral standard for frontend engineering. High-frequency streaming interfaces (SSE, WebSockets, or chunked transfer feeds) managed by TanStack Query v5 must explicitly link query cancellation tokens to the underlying transport abort protocol. Infinite streaming queries must configure strict sliding memory bounds using maxPages and deterministic garbage collection eviction timeouts (gcTime) to prevent runaway heap expansion and catastrophic browser tab crashes on unmount. 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: Ignoring QueryFunctionContext.signal in streaming queries while accumulating unbounded infinite pages with unevicted cache lifetimes. 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 DriftIgnoring QueryFunctionContext.signal in streaming queries while accumulating unbounded infinite pages with unevicted cache lifetimes.Critical
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 extract and wire `signal` from `QueryFunctionContext` to the underlying network transport (Fetch, EventSource, or WebSocket reader).

Engineers MUST ALWAYS extract and wire `signal` from `QueryFunctionContext` to the underlying network transport (Fetch, EventSource, or WebSocket reader).

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 enforce `maxPages` in `useInfiniteQuery` options when processing unbounded real-time chunks or event bursts to maintain a strictly bounded heap footprint.

Engineers MUST ALWAYS enforce `maxPages` in `useInfiniteQuery` options when processing unbounded real-time chunks or event bursts to maintain a strictly bounded heap footprint.

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 NOT use `gcTime

Engineers MUST NOT use `gcTime: Infinity` on real-time streaming queries; `gcTime` MUST be constrained to a strictly finite duration (or `0` when cache persistence across unmounts is hazardous).

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 cancel the `ReadableStreamDefaultReader` or invoke `EventSource.close()` inside the `signal.addEventListener('abort', ...)` callback if manual consumption is required.

Code MUST explicitly cancel the `ReadableStreamDefaultReader` or invoke `EventSource.close()` inside the `signal.addEventListener('abort', ...)` callback if manual consumption is required.

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 unmount without propagating query cancellation

Components NEVER unmount without propagating query cancellation; when components unmount, engineers SHOULD verify `queryClient.cancelQueries` or active signal teardown triggers immediately.

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 TanStack Query v5 Stream Cancellation and Bounded Memory Eviction critical for AI coding assistants?

High-frequency streaming interfaces (SSE, WebSockets, or chunked transfer feeds) managed by TanStack Query v5 must explicitly link query cancellation tokens to the underlying transport abort protocol. Infinite streaming queries must configure strict sliding memory bounds using maxPages and deterministic garbage collection eviction timeouts (gcTime) to prevent runaway heap expansion and catastrophic browser tab crashes on unmount. 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 (Ignoring QueryFunctionContext.signal in streaming queries while accumulating unbounded infinite pages with unevicted cache lifetimes.) 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

TanStack