Skip to main content

Cache entry lifecycle

Every query result is stored as a cache entry keyed by METHOD:path:params. An entry moves through these states:

staleTime and cacheTime

These two values control the freshness lifecycle:
  • staleTime“when do I refetch?” How long data stays fresh. While fresh, kweri.query() returns the cached data without hitting the network. Once stale, the next access refetches in the background. Default: 0 (immediately stale).
  • cacheTime“when do I forget?” How long an entry with no active observers is kept in memory before it can be garbage-collected. Default: 5 minutes.
They are independent: staleTime governs freshness (refetching), cacheTime governs retention (memory). An entry can be stale but still cached — it’s kept around and refetched on next access. Normally cacheTime ≥ staleTime.

Per-query overrides

Freshness is really a property of the data, not the instance — a profile and a stock price want very different staleTimes. Override per call, taking precedence over the instance defaults:
Overrides are stamped onto the cache entry when it’s (re)fetched, so they take effect from that write forward.

Stale-while-revalidate

When a query is called for data that exists in cache but is stale:
  1. The cached data is returned immediately (no loading state)
  2. A background network request is fired to refresh it
  3. Subscribers are notified when the fresh data arrives
This means your UI never blocks on network latency for data you’ve already seen.

Cache structure

Each entry stores:

isFresh

Data is considered fresh when:
If staleTime is 0 (the default), data is always stale and a background refetch will always fire when the query is called.

Invalidation

Invalidation marks an entry as stale without removing it. The cached data is still returned immediately; a refetch fires in the background.
invalidateByPath is the most common pattern after a mutation — it catches all variants (e.g., /users, /users/1, /users?page=2) without you needing to enumerate every param combination.

Cache removal

Removal deletes the entry from memory entirely. The next query call starts from scratch.

Direct cache manipulation

You can read and write the cache directly without going through the network — useful for optimistic updates:
Data written with setCachedData bypasses schema validation. It is marked as a success entry with updatedAt set to now, so it will remain fresh for staleTime milliseconds.

Error caching

Errors are also cached, but with a much shorter lifetime (default: 5 seconds). This prevents retry storms while still allowing the UI to recover quickly. When an error entry expires, the next call to kweri.query() will attempt a fresh fetch.