Persistence
A cache created with persist: true keeps its covered history in IndexedDB, so a reload or a new tab starts from what earlier sessions fetched: history that never changes is fetched once per device instead of once per session. It is off by default, set per cache, and structural: every tab must pass the same value. The design is §4.10 of the architecture.
export async function openCandles(client: TscacheClient) {
const cache = await client.cache({
id: "candles/ACME/1m",
interval: MINUTE,
fields: { close: "f64", volume: "f64" },
version: "2026-10", // stored records of another version are never loaded
persist: true, // kept in IndexedDB when the client is hosted 'shared'
});
// Elsewhere (dedicated, in-process, Node) the flag does nothing.
const persisted =
client.mode === "shared" && typeof indexedDB !== "undefined";
return { cache, persisted };
}Where it acts
Only the SharedWorker hosting persists: every tab of the origin reaches one worker, whose engine is then the only writer of the database. In the dedicated-worker and in-process hostings (a browser without SharedWorker, a fallback, or a pinned mode), in Node and for an Engine used directly, persist: true is accepted and does nothing, without an event. client.mode === 'shared' in a browser with IndexedDB tells you that the cache persists.
A page that fell back persists nothing
A page whose SharedWorker failed (a browser without it, a script that did not load, a worker that did not answer in time) runs a dedicated worker or in-process, and its caches stay in memory: a reload fetches everything again. Nothing reports it except client.mode, which is then 'dedicated' or 'in-process', and the modeFallback events, which are emitted once, just after createClient resolves, to the listeners attached by then. Check client.mode if persistence matters to you.
What is stored, and when
- The covered ranges below the finalized watermark, and the points inside them. The provisional tail (Versions and watermarks) is never stored, so a reload fetches it again.
- Additions are written behind: about a second after the last change, and at most five seconds after the first. A live tail that only rewrites provisional points writes nothing.
- A removal (
invalidate,clear, a watermark moved back, a version change) is written at once, and the call that made it answers once the removal is durable or, after the cache's persistence has stopped, once the persister releases it (architecture §4.10.1, What can outlive a removal, says what the disk can then hold).clearAll()tries to empty the disk and resolves once that clear has settled: use it to remove data from the disk. Either call takes at most about ten seconds on a failing disk, or about fifteen when it also waited for the persistence module to load. - When the last tab closes, the worker writes what was still waiting. Where the browser supports it (Chromium), tscache creates the worker with
extendedLifetime, which keeps it running about 30 seconds after its last tab so that write can land. Elsewhere the option is ignored, and a worker that ends first loses the additions still waiting, at most five seconds of them; the disk keeps the earlier state. A removal is different: its call waits for the disk as above (Failures).
Loading
cache() of a persisted cache resolves once its records are loaded and applied, so the first get through the handle sees them; on a stalled disk it waits at most five seconds. After a clearAll, every SharedWorker that ran it, the caller's and each one it reached, loads nothing more for the rest of its life (Sensitive data and logout). A second tab opening the same cache waits for the same load. A range the records do not cover, an evicted one included, reads as uncached and is fetched; it never reads as a confirmed gap.
With a memory budget (Memory), a page the worker evicts leaves the disk too: the next write-behind flush deletes its record, so the stored records never hold more than memory did, and the next session's load stays within what the budget let the worker hold. An evicted range is therefore fetched again from the backend, in this session and the next. A load larger than the budget keeps only its newest pages. Ranges that are covered but hold no bar (confirmed gaps) cost no memory, are never evicted and keep their small records. Records written under another structure or another version are not loaded, and the cache writes its own over them.
A cache with a calendar interval in a zone checks its stored pages as it checks a server's snapshot (Server rendering): after a browser update that changed the zone's rules, a page whose range or coverage ends now fall in other slots is skipped and fetched again. The five seconds bound the disk read; applying the records comes after it, and for a very fragmented calendar cache (more than about 14,500 separate coverage ranges) only the newest pages are applied.
Failures
A persistence failure never rejects a call. The cache stops persisting and goes on in memory, and every tab hears persistStopped with reason 'quota-exceeded' (the origin's storage quota is full: the cache stops at the first refused write, without retrying, with the QuotaExceededError), 'unavailable' (the database cannot be opened, or a write or the load did not finish in time) or 'error' (a write or the load failed, with the error). A write that fails for a reason other than quota is retried while a retry fits inside about five seconds of the write being due, and the cache goes on persisting when a retry succeeds. A write that is refused for quota, or that still fails after those five seconds, stops the cache. A load whose read fails or does not finish in time stops the cache too, and a database that cannot be opened, or a persistence module that does not load, stops every persisted cache of the worker. After the browser closes the database connection, a later load or write stops its cache with 'error'. A call that removes coverage from one cache (invalidate, clear, a watermark moved back, a version change) answers once the removal is durable or, after the cache's persistence has stopped, once the persister releases it, at most about ten seconds, or fifteen when it also waits for the persistence module to load; clearAll() answers once its own clear has settled (Sensitive data and logout). What the disk holds when such a call resolves after a stop, and what a later session can load, is set out in architecture §4.10.1, What can outlive a removal. A stop while cache() loads is emitted before the handle exists, so listen on the client:
export function watchPersistence(client: TscacheClient): () => void {
// A stop while cache() loads comes before the handle exists: listen on
// the client. The cache goes on in memory.
return client.on("persistStopped", ({ cacheId, reason, error }) => {
console.warn(`${cacheId} is no longer persisted (${reason})`, error);
});
}A fourth reason, 'superseded', is not a failure: a newer deploy's worker is running in the origin and owns the records now (Stale scripts after a deploy). The older worker stops writing, for every persisted cache at once, and deletes nothing of its own accord; a cache it opens later loads nothing. Its invalidate, clear and other removals still try to delete the stored pages they withdraw, and their calls answer as above, in at most about five seconds; the newer worker may fetch a little more again, since a removal deletes whole stored pages. The withdrawn range can remain, or come back: while the newer worker's own memory holds that range, its next write of those pages puts them back, and a later load can serve them until the newer worker removes them too. Make a removal that must leave the disk in a current tab, or use clearAll(). If the older worker could not load its persistence code at all, its removals delete nothing. clearAll() still tries to empty the disk and resolves once that clear has settled. A deletion still waiting when the worker is superseded, for a cache that stopped earlier for one of the reasons above, does not run, and those records can remain too. The older worker's tabs keep working from memory until they are reloaded.
Versions across sessions
A stored range is served in every later session without asking the backend, so a restatement the backend does not announce lasts across reloads too. Set version when the dataset has one: records of another version are never loaded. Without one, invalidate or clear on your own clock removes stored ranges as well (Expiry and other patterns).
Keeping the storage
Browsers evict best-effort storage under pressure, an origin at a time; an evicted range is fetched again. To keep the cache, ask for persistent storage from the page. tscache never asks, since some browsers prompt the user:
export async function keepStorage(): Promise<boolean> {
// Best-effort storage can be evicted under pressure; ask to keep it.
// Some browsers prompt the user, so tscache never asks on its own.
return (await navigator.storage?.persist?.()) ?? false;
}Sensitive data and logout
Stored records are readable by every script of the origin and outlive the session. Keep per-user or sensitive caches in memory; that is why persist is per cache. At logout, one clearAll() empties every cache and the database:
export async function logout(client: TscacheClient): Promise<void> {
// Empties every cache and, from a client of any hosting, the database
// too: resolves once the records are gone, or the clear gave up.
await client.clearAll();
}From 0.3.0 it reaches every SharedWorker of 0.3.0 or later in the origin that takes part in the workers' channel (see the workers guide), an older deploy's that other tabs still use included: each clears its memory and the disk too, so none of them writes the data back. The promise resolves when the calling worker's own clear is done and does not wait for the others. A worker of tscache 0.1.0 or 0.2.0 is not reached and writes back what it still holds; a worker the browser has suspended (for example, one whose only tabs sit in the back-forward cache) is also excluded from BroadcastChannel delivery while suspended and keeps its memory if kept alive until its next clearAll. If a clearAll cannot empty the disk within five seconds, every persisted cache stops, and that worker persists nothing more until it ends. When the logout comes while the worker's persistence module is still loading, as on the worker's first use of persistence or soon after a first cache(), the call waits for that loading first, so it can take up to ten seconds. When the module failed to load, clearAll still tries once to empty the database, and its call waits at most five seconds for it. When a clearAll answers without having emptied the database, records may still be on disk, and a later worker can load them (architecture §4.10.1, What can outlive a removal).
After a clearAll, every SharedWorker that ran it, the caller's and each one it reached, loads nothing more from the database for the rest of its life: a persisted cache it first opens afterwards starts empty (the open rule is in §4.10.6 of the architecture, under Open; see Coverage and reads for when a read fetches). So no worker that has cleared can serve back pre-logout records that a slower worker wrote late. A worker started later loads as usual.
A client hosted in a dedicated worker or in-process persists nothing, but its clearAll empties the database too, so a logout from any page removes what a SharedWorker session stored, within the limits above. It loads the clearing code only then, and creates no database where there is none, except in a browser without indexedDB.databases() (Firefox before 126), where it cannot tell and leaves an empty database behind. From 0.3.0 its clearAll reaches the SharedWorkers of 0.3.0 or later that other tabs still use as well, which clear their memory and so write nothing back. When the clear fails (IndexedDB unavailable, or refusing the clear for five seconds), the call still resolves, nothing else changes, and the next clearAll tries again.