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

TanStack Query v5 Progressive Suspense Chunk Hydration & Stream Ingestion Protocol

Enforces deterministic ingestion of streaming SSR chunks into TanStack Query v5 client caches without duplicate network fetches or Suspense boundary layout thrashing. Coordinates progressive stream deserialization, non-zero cache stale time, and stable query client identity across progressive hydration boundaries.

Prohibited Anti-Pattern: Hydration Refetch Storms and Suspense Boundary Tearing via Zero-Stale Streaming Chunk Ingestion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Query v5 Progressive Suspense Chunk Hydration & Stream Ingestion Protocol - Enforces deterministic ingestion of streaming SSR chunks into TanStack Query v5 client caches without duplicate network fetches or Suspense boundary layout thrashing. Coordinates progressive stream deserialization, non-zero cache stale time, and stable query client identity across progressive hydration boundaries.
globs: src/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tanstack-query-v5-stream-hydration-protocol"
---

# TanStack Query v5 Progressive Suspense Chunk Hydration & Stream Ingestion Protocol

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Hydration Refetch Storms and Suspense Boundary Tearing via Zero-Stale Streaming Chunk Ingestion

## System Constraints
You are a Principal Engineer enforcing TanStack Query v5 Suspense Chunk Hydration & Stream Ingestion Protocol. Mandate invariants that prevent duplicate client-side network requests and Suspense layout thrashing during progressive SSR streaming. Enforce non-zero staleTime guarantees on all dehydrated stream boundaries, stable QueryClient singletons per execution context, and deterministic ingestion of chunked dehydrated query states.

## Strict Guidelines
- Engineers MUST ALWAYS configure `defaultOptions.queries.staleTime` to a non-zero threshold (minimum 30_000ms) on queries hydrated from SSR streaming chunks to prevent instantaneous client refetching during progressive mounting.
- Engineers MUST NOT re-instantiate `QueryClient` inside React component render loops or across streaming chunk boundaries; the client instance MUST be maintained via a stable module singleton on the client or scoped via React `useState`/Ref pattern per SSR request lifecycle.
- Components using `useSuspenseQuery` MUST ALWAYS be encapsulated inside an explicit `Suspense` boundary paired with an appropriate `HydrationBoundary` that consumes dehydrated state matching the query key.
- Services streaming partial query states MUST ensure query keys are deterministic, structurally serializable, and strictly identical between the server-side prefetch stream emitter and the client-side consumer.
- Hydration stream processors MUST use transactional hydration (`hydrate(queryClient, dehydratedState)`) or official `HydrationBoundary` wrappers to prevent partial cache pollution and layout flashes.

## Bad vs Good Implementations
### Progressive Hydration Boundary and Cache Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a global QueryClient without SSR isolation leaks cross-request memory on the server. Defaulting staleTime to 0 forces useSuspenseQuery to consider stream-hydrated chunks immediately stale, initiating a redundant network fetch and thrashing the Suspense boundary.
```typescript
import React from 'react';
import { QueryClient, QueryClientProvider, useSuspenseQuery } from '@tanstack/react-query';

// ANTI-PATTERN: QueryClient created without stable SSR memoization and with staleTime: 0.
// When HTML stream delivers progressive chunks, client immediately triggers network refetch,
// causing Suspense boundary flashes, duplicate data fetching, and hydration mismatches.
const client = new QueryClient();

export function StreamingUserProfile({ userId }: { userId: string }) {
  return (
    <QueryClientProvider client={client}>
      <React.Suspense fallback={<div>Loading user...</div>}>
        <UserData userId={userId} />
      </React.Suspense>
    </QueryClientProvider>
  );
}

function UserData({ userId }: { userId: string }) {
  const { data } = useSuspenseQuery({
    queryKey: ['user', userId],
    queryFn: async () => {
      const res = await fetch(`/api/users/${userId}`);
      return res.json();
    },
    // staleTime defaults to 0, invalidating server-streamed state immediately
  });

  return <div>{data.name}</div>;
}
```

#### Production Standard (Correct)
> **Standard**: Isolates QueryClient lifecycle per request on the server while preserving a single browser instance. Sets an explicit staleTime (60s) preventing duplicate network requests during stream chunk ingestion, and uses HydrationBoundary to transactionally load progressive server chunks into the client cache.
```typescript
import React, { useState } from 'react';
import {
  QueryClient,
  QueryClientProvider,
  HydrationBoundary,
  DehydratedState,
  useSuspenseQuery,
} from '@tanstack/react-query';

const STREAMING_CACHE_STALE_TIME_MS = 60 * 1000;

function makeQueryClient(): QueryClient {
  return new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: STREAMING_CACHE_STALE_TIME_MS,
        gcTime: 5 * 60 * 1000,
        refetchOnWindowFocus: false,
        refetchOnMount: false,
      },
    },
  });
}

let browserQueryClient: QueryClient | undefined;

export function getQueryClient(): QueryClient {
  if (typeof window === 'undefined') {
    return makeQueryClient();
  }
  if (!browserQueryClient) {
    browserQueryClient = makeQueryClient();
  }
  return browserQueryClient;
}

interface StreamingBoundaryProps {
  children: React.ReactNode;
  dehydratedState?: DehydratedState;
}

export function ProgressiveHydrationRoot({ children, dehydratedState }: StreamingBoundaryProps) {
  const [queryClient] = useState(() => getQueryClient());

  return (
    <QueryClientProvider client={queryClient}>
      <HydrationBoundary state={dehydratedState}>
        <React.Suspense fallback={<div>Ingesting stream chunk...</div>}>
          {children}
        </React.Suspense>
      </HydrationBoundary>
    </QueryClientProvider>
  );
}

export function StreamedUserData({ userId }: { userId: string }) {
  const { data } = useSuspenseQuery({
    queryKey: ['user', userId] as const,
    queryFn: async () => {
      const res = await fetch(`/api/users/${userId}`);
      if (!res.ok) {
        throw new Error(`Failed to fetch user: ${res.statusText}`);
      }
      return res.json() as Promise<{ id: string; name: string }>;
    },
  });

  return <div>{data.name}</div>;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: TanStack Query v5 Progressive Suspense Chunk Hydration & Stream Ingestion Protocol

TanStack Query v5 Progressive Suspense Chunk Hydration & Stream Ingestion Protocol defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic ingestion of streaming SSR chunks into TanStack Query v5 client caches without duplicate network fetches or Suspense boundary layout thrashing. Coordinates progressive stream deserialization, non-zero cache stale time, and stable query client identity across progressive hydration boundaries. 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: Hydration Refetch Storms and Suspense Boundary Tearing via Zero-Stale Streaming Chunk Ingestion 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 DriftHydration Refetch Storms and Suspense Boundary Tearing via Zero-Stale Streaming Chunk IngestionCritical
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 configure `defaultOptions.queries.staleTime` to a non-zero threshold (minimum 30_000ms) on queries hydrated from SSR streaming chunks to prevent instantaneous client refetching during progressive mounting.

Engineers MUST ALWAYS configure `defaultOptions.queries.staleTime` to a non-zero threshold (minimum 30_000ms) on queries hydrated from SSR streaming chunks to prevent instantaneous client refetching during progressive mounting.

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 re-instantiate `QueryClient` inside React component render loops or across streaming chunk boundaries

Engineers MUST NOT re-instantiate `QueryClient` inside React component render loops or across streaming chunk boundaries; the client instance MUST be maintained via a stable module singleton on the client or scoped via React `useState`/Ref pattern per SSR request 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.
3

Components using `useSuspenseQuery` MUST ALWAYS be encapsulated inside an explicit `Suspense` boundary paired with an appropriate `HydrationBoundary` that consumes dehydrated state matching the query key.

Components using `useSuspenseQuery` MUST ALWAYS be encapsulated inside an explicit `Suspense` boundary paired with an appropriate `HydrationBoundary` that consumes dehydrated state matching the query key.

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

Services streaming partial query states MUST ensure query keys are deterministic, structurally serializable, and strictly identical between the server-side prefetch stream emitter and the client-side consumer.

Services streaming partial query states MUST ensure query keys are deterministic, structurally serializable, and strictly identical between the server-side prefetch stream emitter and the client-side consumer.

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

Hydration stream processors MUST use transactional hydration (`hydrate(queryClient, dehydratedState)`) or official `HydrationBoundary` wrappers to prevent partial cache pollution and layout flashes.

Hydration stream processors MUST use transactional hydration (`hydrate(queryClient, dehydratedState)`) or official `HydrationBoundary` wrappers to prevent partial cache pollution and layout flashes.

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 Progressive Suspense Chunk Hydration & Stream Ingestion Protocol critical for AI coding assistants?

Enforces deterministic ingestion of streaming SSR chunks into TanStack Query v5 client caches without duplicate network fetches or Suspense boundary layout thrashing. Coordinates progressive stream deserialization, non-zero cache stale time, and stable query client identity across progressive hydration boundaries. 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 (Hydration Refetch Storms and Suspense Boundary Tearing via Zero-Stale Streaming Chunk Ingestion) 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