| | |

Svelte Query 05 ⚡ Caching Lifecycle — Mastering freshness, garbage collection, and background refetching

⏱️ Estimated read: 6 min | |

Caching is the most significant performance optimization in Svelte Query, yet it is often the most misunderstood aspect of the library. Developers frequently confuse the time data is considered “fresh” with the time data is allowed to persist in memory. These two concepts—controlled by staleTime and gcTime (formerly cacheTime)—dictate how your application balances network efficiency with memory usage.

This chapter explores the lifecycle of a query from the moment it is fetched until it is eventually purged from the system. We will examine how staleTime dictates when a background re-fetch should be triggered and how gcTime ensures your application doesn’t bloat its memory footprint by keeping unused data indefinitely. By mastering these settings, you gain control over the user experience, ensuring that data is always as current as possible without overwhelming your server with redundant requests.

Key point: staleTime defines the duration after which data is considered “stale” and subject to automatic re-fetching, while gcTime determines how long an unused query result remains in the cache before it is garbage collected from memory.


Why exists

  • The Redundant Request problem. Without a staleTime strategy, the application might fetch the same data repeatedly when navigating between routes, wasting bandwidth.
  • The Stale UI problem. Users expect an application to stay current, but refreshing the entire UI is jarring. Background re-fetching keeps data fresh without interrupting the user.
  • The Memory Leak problem. An unbounded cache will eventually consume all available client memory; gcTime ensures that unused data is evicted.
  • The Focus-driven Data problem. Users often switch tabs or background the browser. refetchOnWindowFocus ensures the data is fresh the moment they return.
  • The Network-Latency trade-off. Sometimes, showing slightly stale data instantly is better than showing a loading spinner; caching allows for this “stale-while-revalidate” pattern.

a. staleTime: Preventing redundant network requests

staleTime is the threshold that determines if a query needs to be updated. When a query is “fresh,” Svelte Query will return the cached data immediately without hitting the network. If the data is “stale,” Svelte Query will serve the cached data but simultaneously initiate a background re-fetch to ensure the UI eventually synchronizes with the server.

const query = createQuery(() => ({
  queryKey: ['user'],
  queryFn: fetchUser,
  // Data stays 'fresh' for 1 minute
  staleTime: 60 * 1000, 
}));

Setting staleTime: 0 (the default) means data is considered stale immediately upon receipt. This forces every mount or query instantiation to trigger a background fetch. Increasing this value is the single most effective way to reduce API load and eliminate “flickering” loading states in your application.

b. gcTime: Managing memory and garbage collection

gcTime (Garbage Collection Time) controls how long unused data remains in the cache. A query is considered “unused” when no active components are subscribed to it. Once a query becomes inactive, the timer starts; if the timer hits zero, the query is garbage collected and removed from the cache entirely.

const query = createQuery(() => ({
  queryKey: ['posts'],
  queryFn: fetchPosts,
  // Cache stays in memory for 10 minutes after use
  gcTime: 10 * 60 * 1000,
}));

It is crucial to understand that gcTime must always be longer than staleTime. If you set gcTime to be shorter than staleTime, data might be garbage collected while it is still technically considered “fresh,” forcing an unnecessary network request when the component remounts.

c. Background refetching and window focus behaviors

Svelte Query provides built-in mechanisms to ensure data stays relevant without manual intervention. By default, refetchOnWindowFocus, refetchOnReconnect, and refetchOnMount are set to true. When the user navigates away from your tab and returns, the refetchOnWindowFocus trigger checks if the data is stale and, if so, kicks off a background update.

const query = createQuery(() => ({
  queryKey: ['notifications'],
  queryFn: fetchNotifications,
  // Disable automatic refetching on focus
  refetchOnWindowFocus: false,
}));

This behavior is “intelligent”—it only refetches if the data is currently stale. If your staleTime is set to 5 minutes and the user focuses the window after 30 seconds, Svelte Query knows the data is still fresh and does not trigger a request. This minimizes overhead while providing a “live” feel to the application.


Complete Example Session

// ============================================
// PART 1: THE AGGRESSIVE CACHE
// ============================================
const fastConfig = createQuery(() => ({
  queryKey: ['config'],
  queryFn: fetchConfig,
  staleTime: Infinity, // Never refetch
  gcTime: 0,          // Collect immediately
}));

// ============================================
// PART 2: THE REAL-TIME POLL
// ============================================
const liveData = createQuery(() => ({
  queryKey: ['ticks'],
  queryFn: fetchTicks,
  staleTime: 0,           // Always stale
  refetchInterval: 1000,  // Poll every 1s
}));

// ============================================
// PART 3: THE STANDARD WEB APP CONFIG
// ============================================
const standard = createQuery(() => ({
  queryKey: ['profile'],
  queryFn: fetchProfile,
  staleTime: 1000 * 60 * 5, // 5 min freshness
  gcTime: 1000 * 60 * 30,   // 30 min memory
}));

// ============================================
// PART 4: DISABLING FOCUS REFETCH
// ============================================
const silent = createQuery(() => ({
  queryKey: ['logs'],
  queryFn: fetchLogs,
  refetchOnWindowFocus: false,
}));

This sequence demonstrates the contrast between aggressive caching for static data, active polling for real-time data, and standard application settings.


Quick Reference

Cache Lifecycle Settings

PropertyDefaultPurpose
staleTime0Prevents background fetches
gcTime5 minPurges unused data from RAM
refetchOnWindowFocustrueSyncs data on tab activation
refetchOnReconnecttrueSyncs data on network return

Lifecycle Stages

StageTrigger
FetchQuery mounted/stale
InactiveComponent unmounted
GCgcTime threshold reached

Best Practices

✅ Do This:

// Match staleTime to your data's volatility
staleTime: 60 * 1000                                           // ✅

// Ensure gcTime > staleTime
gcTime: 10 * 60 * 1000                                         // ✅

// Disable focus refetch for heavy dashboards
refetchOnWindowFocus: false                                    // ✅

// Use Infinity for static app configuration
staleTime: Infinity                                            // ✅

❌ Don’t Do This:

// Don't set gcTime < staleTime
gcTime: 1000, staleTime: 5000                                  // ❌

// Don't use 0 staleTime for expensive requests
staleTime: 0                                                   // ❌

// Don't disable focus refetch for mission-critical data
refetchOnWindowFocus: false // (user sees stale data)          // ❌

// Don't leave gcTime at default if memory is tight
// (explicitly set it lower)                                   // ❌

Common Pitfalls

PitfallWhy It HappensFix
Unnecessary FetchesstaleTime too shortIncrease staleTime
UI FlickeringstaleTime 0 with slow APISet staleTime > 0
Memory BloatgcTime set to InfinityUse finite gcTime
Stale DataFocus refetch is disabledEnable refetchOnWindowFocus

Real-World Examples

1. Static site settings

staleTime: Infinity

2. E-commerce product prices (volatile)

staleTime: 1000 * 30 // 30 seconds

3. User notification counts

refetchInterval: 5000

4. Disabling re-fetch on background

refetchOnWindowFocus: false

5. Long-term cache

gcTime: 1000 * 60 * 60 // 1 hour

6. Always force fetch

staleTime: 0

7. Refetch on mount

refetchOnMount: 'always'

8. Retry logic adjustment

retry: 3

9. Background fetch status checking

if (query.isFetching) { ... }

10. Manual invalidation trigger

client.invalidateQueries({ queryKey: ['data'] })

Visual

staleTime vs gcTime

┌──────────────────────────────────────────────┐
│  DATA LIFECYCLE                              │
│  [ FETCH ] ──► [ FRESH ] ──► [ STALE ] ──► [ GC ]
│                 │ (no fetch)  │ (refetch)    │
│                 │             │              │
│          (staleTime ends)     (gcTime ends)  │
└──────────────────────────────────────────────┘

refetchOnWindowFocus Flow

┌──────────────────────────────────────────────┐
│  USER SWITCHES TAB                           │
│        │                                     │
│  USER RETURNS (FOCUS)                        │
│        │                                     │
│  CHECK: Is data stale?                       │
│  YES ──► Background Refetch                  │
│  NO  ──► Keep Cached Data                    │
└──────────────────────────────────────────────┘

Memory Retention

┌──────────────────────────────────────────────┐
│  COMPONENT UNMOUNTED                         │
│  │                                           │
│  [ TIMER STARTS: gcTime ]                    │
│  │                                           │
│  IF TIMER REACHES 0 ──► PURGE FROM MEMORY    │
└──────────────────────────────────────────────┘

Summary

ItemValue
staleTimeFreshness threshold
gcTimeMemory retention duration
Focus refetchSynchronization trigger
Default staleTime0 (Always stale)
Default gcTime5 minutes

Key takeaways:

  • Understand freshness. staleTime is about network efficiency; it dictates when Svelte Query is allowed to skip a fetch.
  • Understand garbage collection. gcTime is about memory management; it dictates when a cache entry is discarded.
  • The golden rule. Always keep gcTime higher than staleTime to avoid purging fresh data.
  • Be smart about focus. refetchOnWindowFocus is a great user experience booster, but consider disabling it for heavy or non-essential network calls.
  • Static vs. Volatile. Use Infinity for static resources and short staleTime intervals for highly volatile data like price tickers or status feeds.

Remember: The caching lifecycle is the balancing act between server load and user experience. By correctly configuring your staleTime and gcTime, you ensure your application feels snappy and responsive because it avoids unnecessary network requests, yet remains robust and performant by pruning unused data from memory.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!