Skip to content

Caching

Husnain Ali edited this page Sep 27, 2026 · 3 revisions

Caching

config.cache = .memory(policy: .cacheFirst)

config.cache = CacheConfiguration(
    store: DiskCacheStore(),                 // survives launches; LRU by total size
    defaultPolicy: .staleWhileRevalidate,
    defaultTTL: 300
)
Policy Behavior
.ignoreCache Always network, do not read or write the cache
.networkOnly Network, but write the response to the cache
.cacheFirst Fresh cache hit returns immediately; otherwise network
.networkFirst Network, falling back to a cached response if it fails
.cacheOnly Cache or a .notFound-style failure; never touches the network
.staleWhileRevalidate Return the cached response now, refresh in the background
  • Only GET / HEAD are cached.
  • Entries are keyed per account (a fingerprint of the Authorization value), so a response fetched with one token is never served to another. Call await client.clearCache() when the signed-in user changes; the client also clears the cache itself when a session expires (a failed refresh, or a second 401).
  • Set-Cookie and other credential headers are never written to the cache, and disk cache file names are a SHA-256 of the key so a crafted URL cannot be made to collide with another entry.
  • ETag responses are revalidated with If-None-Match; a 304 reuses the stored body.
  • Cache-Control: no-store is never persisted; max-age and no-cache are honored.
  • Per-endpoint override via Endpoint.cachePolicy.
  • A staleWhileRevalidate background refresh runs through the normal concurrency queue at low priority, can be stopped with client.cancelAll(), and a failure is logged (at .error) instead of being discarded, so a permanently failing endpoint doesn't serve stale data forever with no sign of it.

The cache short-circuits the network entirely for fresh cacheFirst / cacheOnly hits. See Platform Notes Thread Safety and Performance for more performance notes.

Clone this wiki locally