Skip to content

Caching

Every query in gpui-query has a cache policy. The policy determines whether a fetch happens at all, and whether stale data gets served while a refetch runs in the background. Picking a policy is how you trade data freshness against request volume.

There are three variants of CachePolicy. The default is Ttl { ttl_ms: 60_000 }, a 60-second TTL. You can override it per query or set a different default when constructing the QueryClient.

CachePolicy::NoCache

Every access triggers a fresh fetch. Data from a successful fetch is stored on the resource, but never served as a cache hit on a later access. Use this for data that changes constantly and where showing a stale value is worse than showing nothing.

The practical effect: begin_request never returns CacheHit. Under IgnoreWhileLoading with a request already in flight it still returns IgnoredWhileLoading.

CachePolicy::Ttl { ttl_ms: 30_000 }

Data is fresh for ttl_ms milliseconds after it was last fetched. While fresh, accessing the query returns CacheHit and skips the network entirely. After the TTL expires, the next access starts a new fetch.

This is the default policy.

CachePolicy::StaleWhileRevalidate { ttl_ms: 30_000, stale_ms: 60_000 }

This policy splits the cache lifetime into two windows.

Fresh window (0 to ttl_ms): data is served from cache. No fetch happens. Same as Ttl.

Stale window (ttl_ms to ttl_ms + stale_ms): cached data is returned immediately, and a background refetch starts. The caller gets StaleCacheHit with a request_id for the background fetch.

Expired (past ttl_ms + stale_ms): the data is too old to serve. A normal fetch happens, same as a cache miss.

Use this when your UI benefits from showing slightly outdated data rather than flashing a loading spinner. Feed timelines, dashboards, and list views are common candidates.

CachePolicy exposes six methods that control the caching decision internally. You normally do not call these yourself (the library does).

  • is_fresh(age_ms) - returns true when age_ms is within the TTL window
  • is_stale_but_serveable(age_ms) - returns true when the age is past TTL but within the stale window (only StaleWhileRevalidate)
  • is_expired(age_ms) - returns true when the age exceeds the total valid window. NoCache always returns true
  • can_short_circuit() - whether the policy can ever skip a fetch (true for Ttl and StaleWhileRevalidate; a pure policy check with no freshness condition)
  • can_serve_stale() - whether stale data can be served (true only for StaleWhileRevalidate)
  • total_valid_ms() - returns ttl_ms + stale_ms for SWR, ttl_ms for Ttl, None for NoCache

The freshness half of those two decisions lives in the resource: should_short_circuit_cache(now_ms) and should_serve_stale_and_revalidate(now_ms) combine the policy checks with the age of the data.

Pass the policy when creating a QueryClient to set the app-wide default.

cx.set_global(QueryClient::with_policies(
CachePolicy::StaleWhileRevalidate { ttl_ms: 30_000, stale_ms: 60_000 },
RequestPolicy::LatestWins,
));

Override per query through QueryOptions:

let opts = QueryOptions::new(QueryKey::from(["notifications"]))
.cache_policy(CachePolicy::NoCache);

Or use resource_with_policies on the client directly:

let entity = client.resource_with_policies::<Vec<Notification>, MyError>(
QueryKey::from(["notifications"]),
CachePolicy::NoCache,
RequestPolicy::LatestWins,
cx,
);

When multiple parts of your app request the same key at the same time, the RequestPolicy decides what happens.

A new request cancels the in-flight one and starts fresh. This is the right choice when you always want the most recent data and do not care about wasting the earlier request.

RequestPolicy::LatestWins

If a request is already in progress, new requests for the same key are ignored. The original request runs to completion. Use this when fetches are idempotent and you want to avoid redundant work.

RequestPolicy::IgnoreWhileLoading

When you call begin_request on a resource, the return value tells you what happened.

pub enum QueryBeginResult {
Started { request_id, status, replaced_request_id },
CacheHit,
StaleCacheHit { request_id, status, replaced_request_id },
IgnoredWhileLoading { active_request_id },
}
  • Started - a new fetch was kicked off. replaced_request_id is Some if this request cancelled a previous one (under LatestWins).
  • CacheHit - the cache is fresh, no fetch needed. Use the cached data.
  • StaleCacheHit - data is stale but still serveable. Return the stale data to the UI immediately, then use the request_id to run a background fetch.
  • IgnoredWhileLoading - a request was already running and the policy is IgnoreWhileLoading.

QueryFetchMode controls whether the cache is consulted.

  • Normal (default) - respects the cache policy. Returns CacheHit if fresh.
  • Force - bypasses cache freshness. Always starts a new fetch. Still respects IgnoreWhileLoading if a request is already in flight.

Use Force when a query’s first fetch must bypass freshness checks. The hooks only fetch from Idle, so forcing a query that is already Success starts nothing. For pull-to-refresh or a manual reload button, drive the fetch yourself with prepare_fetch_query (below).

use gpui_query::{use_query, QueryKey, QueryOptions};
let (entity, _sub) = use_query(
QueryOptions::new(QueryKey::from(["users", "42"])).force(),
|_signal| async move { fetch_user(42).await },
cx,
);

For a manual forced fetch outside the hooks, client.prepare_fetch_query::<UserData, MyError>(key, cx) takes only the key and cx, runs with the client’s default policies, and returns Option<PreparedFetch<T, E>>. It returns None when IgnoreWhileLoading defers to a request already in flight.

The QueryClient has bulk methods that operate across all resources matching a filter. These use QueryKeyFilter to select which queries to touch.

invalidate_queries clears cache freshness on matching resources. The next access to those queries will trigger a refetch. It does not cancel in-flight requests.

let client = cx.global_mut::<QueryClient>();
client.invalidate_queries(
&QueryKeyFilter::Prefix(&QueryKey::from(["users"])),
cx,
);

This is the standard pattern after a mutation: invalidate the affected query prefix so the next read fetches fresh data.

remove_queries drops matching resources from the registry entirely. Unlike invalidation, which keeps the entity and expires its cache, removal deletes the registry entry only; the entity itself stays alive until the last strong handle elsewhere (such as a view holding the Entity returned by use_query) is dropped.

client.remove_queries(&QueryKeyFilter::All);
  • Exact(&key) - matches only the exact key
  • Prefix(&key) - matches all keys that start with the given prefix segments
  • All - matches every key

Prefix matching is hierarchical. Prefix(&QueryKey::from(["users"])) matches ["users"], ["users", "42"], and ["users", "42", "posts"].

Sometimes you want to update the UI before the server confirms the change. set_query_data writes a value directly into the cache, storing the previous value for rollback.

let client = cx.global_mut::<QueryClient>();
client.set_query_data::<Vec<User>, MyError>(
key.clone(),
updated_user_list,
cx,
);

QueryClient has no dedicated rollback method. Capture the previous value with get_query_data before the optimistic write, then restore it if the mutation fails:

let client = cx.global_mut::<QueryClient>();
let previous = client.get_query_data::<Vec<User>, MyError>(&key, cx);
client.set_query_data::<Vec<User>, MyError>(key.clone(), optimistic_data, cx);
// ... later, if the mutation fails ...
if let Some(previous) = previous {
client.set_query_data::<Vec<User>, MyError>(key.clone(), previous, cx);
}

Restoring through set_query_data notifies observers and marks the persist snapshot, so mounted views re-render and the rollback is persisted. Calling rollback_to_previous() on the resource entity restores the same value but does not notify observers.

Buckets hold only weak entity handles, so a query no component is observing has its resource freed by GPUI refcounting as soon as the last handle drops; garbage collection then prunes the leftover registry entries. The gc method on QueryClient collects Idle, Failure, and Cancelled resources that have been idle longer than gc_time_ms (clamped to a 1 second floor), keeps Success resources for twice that or as long as a stale-while-revalidate policy can still serve them, and never collects a resource with a fetch in flight.

let client = cx.global_mut::<QueryClient>();
client.gc(cx);

If you already hold a timestamp, client.gc_with_time(now_ms, cx) skips the clock read.

The default GC time is 5 minutes (300,000 ms), and it is a client-wide setting: change it with QueryClient::with_gc_time. The gc_time_ms field on QueryOptions, written through the .gc_time() builder, is reserved and has no effect today.

cx.set_global(
QueryClient::with_policies(cache_policy, request_policy)
.with_gc_time(10 * 60 * 1_000),
);

A fetcher normally returns Result<T, E>, and the resource uses whatever CachePolicy the caller supplied through QueryOptions. That policy is decided entirely on the client.

Sometimes the server knows better. A Cache-Control: max-age=30 response header is more authoritative than a TTL you guessed at compile time. The *_with_policy hooks let a fetcher return Result<Fetched<T>, E> instead, carrying a server-derived CachePolicy that overrides the caller’s per-query policy once the fetch resolves successfully.

  • use_query_with_policy(options, fetcher, cx) - same shape as use_query (options-first, signal-accepting fetcher, returns (Entity<QueryResource<T, E>>, Subscription)), but the fetcher returns Result<Fetched<T>, E>.
  • fetch_query_with_policy(&entity, fetcher, cx) - same shape as fetch_query, but the fetcher returns Result<Fetched<T>, E>.

Fetched<T> has three constructors:

// No override: the resource keeps the caller's policy.
Fetched::new(data)
// Override: the resource's policy is replaced with the server's.
Fetched::with_policy(data, policy: CachePolicy)
// (`persist` feature) Attach opaque metadata that flows into PersistedEntry::meta.
Fetched::with_meta(self, meta)

A fetcher that parses only the response headers can push that TTL back into the resource:

use gpui_query::{
use_query_with_policy, CachePolicy, Fetched, QueryKey, QueryOptions,
};
use gpui_query_http::cache_policy_from_headers;
let (entity, _sub) = use_query_with_policy(
QueryOptions::new(QueryKey::from(["notifications"])),
|_signal| async move {
let resp = client.get(url).send().await?;
let policy = cache_policy_from_headers(resp.headers())
.unwrap_or(CachePolicy::NoCache);
Ok(Fetched::with_policy(resp.json().await?, policy))
},
cx,
);

The server policy replaces the resource’s stored policy immediately after complete_success, so subsequent freshness and SWR checks use the server’s TTL. Returning Fetched::new(data) (or using the plain Result<T, E> hooks) leaves the caller’s policy untouched. Server-wins is strictly opt-in.

Fetched::with_meta requires the persist feature. The opaque meta flows into PersistedEntry::meta when the resource is persisted, so it survives a cold start. See Persistence. For the full HTTP Cache-Control and ETag flow, see HTTP caching.

A typical setup looks like this:

// App-wide defaults: 30s TTL with 60s stale window, latest-wins dedup, 10-minute GC
cx.set_global(
QueryClient::with_policies(
CachePolicy::StaleWhileRevalidate { ttl_ms: 30_000, stale_ms: 60_000 },
RequestPolicy::LatestWins,
)
.with_gc_time(10 * 60 * 1_000),
);

Then override per query as needed. A real-time notifications feed might use NoCache. A rarely-changing config endpoint might use Ttl { ttl_ms: 300_000 }.

See Queries for how to define queries that use these policies, QueryClient for the full client API, and Error Handling for what happens when a fetch fails.