Cache System Overview

July 25, 2026 · View on GitHub

Three-tier cache for regenerable data. In-process memory, cross-window shared state, and localStorage-backed persistence.

Scope

Use Cache for data that:

  • Can be regenerated or lost without user impact
  • Needs no backup or cross-device sync
  • Has lifecycle tied to a component, window, or app session

For user settings use Preference; for business data use DataApi.

Tiers

TierScopeSurvives restartAuthorityUse for
MemoryPer-processNoLocal to each processComputed results, API responses
SharedAll renderer windows + MainNoMain (relays + conflict sink)Cross-window UI state
Persist (Renderer)All renderer windowsYes (localStorage)Each rendererRecent items, non-critical UI state
Persist (Main)Main process onlyYes (JSON file)MainLoseable main-process state

Persist has two independent stores. Each renderer persists to its own localStorage; Main persists to its own JSON file ({userData}/cache.json) exposed as getPersist / setPersist / hasPersist / deletePersist (plus subscribePersistChange) on the Main CacheService. The two never share data — Main cannot read renderer persist and vice versa. Separately, Main still relays renderer-origin CacheSyncMessage { type: 'persist' } between windows (it forwards them; it does not store the renderer's persist).

Reach for the Main persist tier last. It was the last tier added, for a deliberately narrow need: small, loseable, main-process-authoritative state that genuinely belongs nowhere else. Before choosing it, rule out the better-fitting systems first — a user setting belongs in Preference; cross-window or renderer-owned UI state belongs in Shared / renderer Persist; business data belongs in DataApi. In the vast majority of cases one of those is the right answer, so use Main persist only when the state is owned by the main process, regenerable, and has no home in any other system. See System Selection for the full decision guide.

Key Types

TypeExample schemaCall siteTiers
Fixed'app.user.avatar': stringget('app.user.avatar')Memory / Shared / Persist
Template'scroll.position.${topicId}': numberget('scroll.position.t42')Memory / Shared
Casual(none — type argument only)getCasual<T>('my.dynamic.key')Memory only

Template keys share one default value across all instances — all web_search.provider.last_used_key.* fall back to ''. Casual keys are blocked at compile time from matching any schema pattern (UseCacheCasualKey in src/shared/data/cache/cacheSchemas.ts:393).

Design Invariants

Non-obvious rules the code enforces; assume them when designing consumers.

  1. Same-value write never fires subscribers or re-renders. Equality via isEqual (es-toolkit/compat). It is a full no-op (no broadcast either) only when expireAt is also unchanged — a same-value write that moves the TTL still broadcasts to mirrors, see invariant 2. (src/main/data/CacheService.ts isEqual guards before broadcastSync / notifier) — Corollary for the hooks' functional updater setX(prev => …): it must return a new value. Mutating prev in place and returning the same reference compares the stored value against itself, so this no-op short-circuit silently swallows the update (the hooks type prev shallow-readonly to block the common top-level case).
  2. TTL-only refresh does not fire subscribers — but does sync mirrors. Updating expireAt on the same value fires no main value-subscriber and no hook re-render. Main still broadcasts the full entry so every renderer mirror renews its expireAt in step; the receiving renderer renews in place, keeping the old value reference (an equal-value heartbeat never causes re-renders).
  3. Subscribers fire only on explicit writes; eviction still reaches mirrors. Lazy TTL cleanup, the 10-min GC sweep, and onStop never fire main value-subscribers. Every Main-origin runtime eviction (lazy TTL cleanup, GC sweep, deleteShared hitting an expired entry) still broadcasts one deletion tombstone so renderer mirrors — which have no GC — physically converge; renderer hooks DO re-render on that tombstone (the value visibly disappears). onStop clears without broadcasting.
  4. Shared expiry is eventually consistent — never expiry-instant. External-store snapshots (getSharedSnapshot, the reader behind all shared cache hooks) are pure physical reads: no TTL evaluation, no store mutation. An expired entry may briefly keep serving its old value until Main's tombstone lands (next Main read of the key, or the GC sweep — upper bound TTL + 10 min) or this window's own imperative getShared evicts it locally. Do not design UI that needs a value to vanish at the TTL instant; useCache / useSharedCache still warn when a hooked key carries TTL.
  5. Writable hooks pin cache entries. registerHook / unregisterHook refcount keys; delete / deleteShared return false while any hook is active. The read-only useSharedCacheValue does NOT pin (and never writes a default) — an owner's deletion always passes through observers.
  6. Persist presence means "overridden", not "stored". Both persist tiers (Main JSON + renderer localStorage) have no absent state — getPersist always returns the stored override or the schema default (never undefined). hasPersist reports whether the effective value differs from the default (i.e. has been overridden), and deletePersist resets a key to its default rather than removing it. Keys are fixed by schema. Change subscription differs by process in API shape only: Main exposes a dedicated subscribePersistChange (main-local, same model as subscribeChange; never relayed to renderers), while the renderer routes persist changes through its unified subscribe(key, cb).
  7. TTL uses absolute expireAt (Unix ms). Every process expires the same entry at the same instant, regardless of clock skew in IPC delivery.
  8. Main-wins convergence. All cross-window shared writes are serialized through Main; on window init, Main-priority override applies to conflicts with the renderer's pre-sync copy.
  9. Re-entrant callbacks are safe. Subscribers may write back into the same key; the isEqual short-circuit terminates loops once the value stabilizes. Callback errors are caught and logged without skipping other subscribers.
  10. Template placeholders are runtime-anonymous. ${providerId} and ${foo} match identical concrete keys. Dynamic segments match [\w\-]+ only — dots, colons, and non-ASCII are rejected (src/shared/data/cache/templateKey.ts:35-46).

Architecture

┌─────────────────────── Renderer Process ──────────────────────┐
│   useCache / useSharedCache / usePersistCache                 │
│                          │                                    │
│                          ▼                                    │
│                   CacheService (Renderer)                     │
│   - Memory cache (local)                                      │
│   - Shared cache (local copy; init-synced from Main)          │
│   - Persist cache (localStorage, authoritative)               │
└──────────────────────────┬────────────────────────────────────┘
                           │ IPC: Cache_Sync / Cache_GetAllShared
┌──────────────────────────▼────────────────────────────────────┐
│                    CacheService (Main)                        │
│   - Internal cache (Main-only)                                │
│   - Shared cache (authoritative; relays to all windows)       │
│   - Persist: own JSON store + relays renderer persist         │
│   - subscribeChange / subscribeSharedChange for Main services │
└───────────────────────────────────────────────────────────────┘

Both channels are sender-gated by validateSender (untrusted Cache_Sync messages are dropped, Cache_GetAllShared rejects) — see IpcApi Overview §Security.

Process Responsibilities

ConcernMainRenderer
Internal memory cacheYes (services' own scratch space)Yes (window-local)
Shared cache authorityYesLocal copy; writes broadcast via IPC to Main
Persist cache storageYes (own JSON file, debounced 350ms, flush on stop); also relays renderer persist syncYes (localStorage, debounced 350ms, flush on unload)
Init sync for new windowsServes getAllShared()Calls getAllShared() on startup
subscribeChange / subscribeSharedChangeMain-only API; template-aware
Hook refcountingregisterHook / unregisterHook
GC (10-min sweep of expired)Yes

API Reference

Renderer

MethodTierKey type
useCache / get / set / has / delete / hasTTLMemoryFixed + Template
getCasual / setCasual / hasCasual / deleteCasual / hasTTLCasualMemoryDynamic only (schema keys blocked)
useSharedCache / getShared / setShared / hasShared / deleteShared / hasSharedTTLSharedFixed + Template
useSharedCacheValue — read-only observer for main-owned keys: no default write-back, no pin, no setter; undefined on physical missSharedFixed + Template
useSharedCacheSelector — multi-key read-only aggregate observer: values tuple → selector → selection-level bail-outSharedFixed + Template
usePersistCache / getPersist / setPersist (value or (prev) => next) / hasPersist / deletePersistPersistFixed only
isSharedCacheReady / onSharedCacheReadyShared
getStats(includeDetails?: boolean)All

Main

MethodTierKey type
get / set / has / deleteInternalFree-form string
getShared / setShared / hasShared / deleteSharedSharedFixed + Template
getPersist / setPersist / hasPersist / deletePersistPersist (Main)Fixed only
subscribeChange<T>(key, cb)InternalExact key
subscribeSharedChange<K>(key, cb)SharedFixed + Template (fires for every matching concrete instance)
subscribePersistChange<K>(key, cb)Persist (Main)Exact key (main-local)

See Also

  • Cache Usage — React hooks, direct API, patterns
  • Cache Schema Guide — Adding fixed and template keys
  • Source: src/main/data/CacheService.ts, src/renderer/data/CacheService.ts, src/renderer/data/hooks/useCache.ts, src/shared/data/cache/