FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Model Weight Caching with the Cache API

Cache immutable model shards by version, verify every digest, and activate only complete generations while treating browser storage as evictable.

Freshness: current•9 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

The Cache Storage API stores named request and response pairs for reuse by web applications, including models used offline. It does not pin files permanently or make a group of shards atomic. A reliable loader stages immutable, versioned assets, verifies each digest before use, and exposes a candidate model only after every required shard is present.

Theory

CacheStorage is an origin-scoped manager for named Cache objects. A service worker can intercept fetch events and use those caches to build offline behavior, while a window or worker can also access the API in a secure context. Cache.put associates a request key with a response; Cache.match retrieves the corresponding entry. Matching normally uses the URL, method, and request matching rules, so a model version or content digest belongs in the URL or cache name. Reusing a generic path for new bytes risks serving a previous release under a current model identifier.

The Cache API is separate from the browser's HTTP cache. It gives application code explicit control over which request and response are stored, but it does not provide a transaction over many assets. Cache entries can be removed when the user clears site data or when storage pressure causes browser eviction. Storage estimate and persistence APIs can inform policy, but neither promises that a particular model file will remain available forever. Treat cache loss as a normal startup condition and keep an online recovery path where the product requires it.

A model package is usually a manifest plus several weight shards and associated tokenizer or graph files. Pin the manifest to a trusted release, and let it name each shard by an immutable path, expected SHA-256 digest, and byte length. Download a candidate into its own versioned cache. Check status and length, hash the received bytes, and call Cache.put only after the expected digest matches. Write a completion marker last. The active-version pointer changes only after that marker exists and the application can read every expected shard.

This staging boundary prevents a partially downloaded model from replacing a working one. If the browser process closes halfway through, no completion marker exists; a later install can retry or remove the incomplete candidate. If the candidate exceeds quota, discard only that candidate and keep the prior model. Retaining one previous version costs extra space but makes rollback possible without a new download. After a successful pointer switch, prune only caches that are neither active nor designated for rollback. Keep user text and inference outputs out of the weight cache; Cache Storage is intended here for immutable release assets, not a private-data database.

Storage estimate

Plan for the versions that must coexist during an update:

Splan=vnb(1+h)S_{\text{plan}} = v n b (1+h)

Here, vv is the number of retained versions, nn is the shard count per version, bb is the average shard size in mebibytes (MiB), and hh is a dimensionless headroom fraction for manifests and other origin data. The output is a planning estimate in MiB, not a reserved quota.

Suppose a model has four 96 MiB shards and the application keeps the active release while staging its replacement. With v=2v=2, n=4n=4, b=96b=96 MiB, and h=0.20h=0.20, the estimate is 2×4×96×1.20=921.62 \times 4 \times 96 \times 1.20 = 921.6 MiB. A nominal 1 GiB budget is 1,024 MiB, leaving about 102 MiB of planning margin. That margin can disappear if the origin also stores images or offline pages, so check storage usage and handle QuotaExceededError rather than assuming the estimate is guaranteed.

Version activation

The reader should consult a completion marker and a version pointer, then verify the requested shard when it is opened. If a digest check fails, reject that shard and return to the previous complete version or fetch a clean copy. Do not make a missing response look like a valid empty model. A release manifest can also include a tokenizer version and preprocessing contract so that weights are never paired with incompatible inputs.

Cache.match results and Cache.put inputs use Response bodies, which are streams. Reading a response consumes its body; either clone it for separate consumers or buffer it once and construct a fresh Response for storage, as the example does. Cross-origin assets also require the server's CORS policy to make their responses readable. For large deployments, split weights into independently hashed shards so a retry does not download a multi-gigabyte file again. The application still has to decide what to do when browser storage is full or unavailable.

Failure modes and misconceptions

A Cache match for one shard does not prove that a model release is complete. An interrupted update can leave three valid files beside a missing fourth, and an old manifest can point at paths whose content has since changed. Require a completion marker tied to the pinned version and check each shard's digest before loading it. A matching URL, matching file size, or successful HTTP response is not byte identity.

Another misconception is that Cache Storage follows HTTP cache-control freshness rules automatically. It is an application-managed request and response store; the app chooses cache names, keys, and invalidation. A cached response may outlive a server-side release or be evicted by browser storage pressure. Use immutable versioned URLs and handle a missing cache on startup. Do not store user prompts or results with model weights, and do not assume opaque cross-origin responses can be hashed by application code.

Trade-offs

Keeping both active and candidate versions consumes about twice the model's shard size during an update, but it preserves a known-good rollback path. Replacing the current generation in place saves space and makes interrupted downloads harder to recover from. A complete precache reduces cold-start network dependence; lazy loading consumes less storage up front but can stall when a later shard is first needed. Choose the policy from the offline requirement and available storage, then surface a deliberate smaller-model or online fallback when the planned bytes do not fit.

Decision scenario

A four-shard update has validated three shards when Cache.put for the last one raises QuotaExceededError. Keep the active pointer on the existing complete release, delete or leave the candidate unselectable, and measure whether safe old caches or unrelated offline assets can be removed. If the candidate still does not fit, use a smaller release or ask the user to reconnect for a non-cached model. Do not expose the partial generation as usable.

Pin trusted release manifest
Fetch immutable shard
Verify digest and length
Write completion marker
Switch version pointer or roll back
Conceptual teaching model synthesized from:mdn-cache-storage-api,w3c-service-workers-spec,mdn-storage-quota-eviction

Implementation example

This TypeScript installer receives a manifest that was already authenticated by the application release process. Each candidate uses a new cache name, so a failed install cannot delete the cache referenced by the current version pointer.

typescript
type Shard = { path: string; sha256: string; bytes: number };
type Manifest = { version: string; digest: string; shards: Shard[] };
async function sha256Hex(bytes: ArrayBuffer): Promise<string> {
return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)),
(value) => value.toString(16).padStart(2, "0")).join("");
}
​
async function stageWeights(manifest: Manifest): Promise<string> {
const cacheName = "weights:" + manifest.version + ":" + manifest.digest;
const cache = await caches.open(cacheName);
const marker = new Request(new URL("/__model_cache__/" + encodeURIComponent(manifest.version) + "/complete.json", location.origin));
try {
for (const shard of manifest.shards) {
const request = new Request(new URL(shard.path, location.origin));
const old = await cache.match(request);
if (old) {
const bytes = await old.arrayBuffer();
if (bytes.byteLength === shard.bytes && await sha256Hex(bytes) === shard.sha256) continue;
await cache.delete(request);
}
const response = await fetch(request, { cache: "no-store" });
if (!response.ok) throw new Error("weight fetch failed");
const bytes = await response.arrayBuffer();
if (bytes.byteLength !== shard.bytes || await sha256Hex(bytes) !== shard.sha256) throw new Error("bad weight");
await cache.put(request, new Response(bytes, {
headers: { "content-type": "application/octet-stream" },
}));
}
await cache.put(marker, new Response(JSON.stringify(manifest),
{ headers: { "content-type": "application/json" } }));
return cacheName;
} catch (error) {
await caches.delete(cacheName);
throw error;
}
}
​
async function activate(version: string, cacheName: string): Promise<void> {
const marker = new Request(new URL("/__model_cache__/" + encodeURIComponent(version) + "/complete.json", location.origin));
if (!await caches.match(marker, { cacheName })) throw new Error("incomplete model");
const active = localStorage.getItem("active-weight-cache");
if (active) localStorage.setItem("previous-weight-cache", active);
localStorage.setItem("active-weight-cache", cacheName);
}
​
async function readShard(cacheName: string, version: string, shard: Shard): Promise<ArrayBuffer> {
const marker = new Request(new URL("/__model_cache__/" + encodeURIComponent(version) + "/complete.json", location.origin));
if (!await caches.match(marker, { cacheName })) throw new Error("incomplete model");
const request = new Request(new URL(shard.path, location.origin));
const response = await caches.match(request, { cacheName });
if (!response) throw new Error("missing model shard");
const bytes = await response.arrayBuffer();
if (bytes.byteLength !== shard.bytes || await sha256Hex(bytes) !== shard.sha256) throw new Error("bad cached weight");
return bytes;
}

Learning outcomes

  • Explain how request keys, response bodies, cache versions, and completion markers work together.
  • Estimate the storage needed to keep active and candidate model releases with headroom.
  • Design integrity, quota-failure, activation, and rollback checks for browser model assets.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next