Mental model
A model download indicator should report bytes the browser has received from the artifact response, not guessed completion from elapsed time or file count. Show a percentage only when the total describes the same bytes the browser is counting; otherwise show an indeterminate transfer state. Keep download completion, integrity verification, and model readiness as separate milestones.
For a fresh fetch, Response.body is a readable byte stream: each read yields a Uint8Array chunk, so adding byteLength measures observed body bytes. The Content-Length field describes a representation length under HTTP semantics, but a browser may decode content codings before exposing Response.body. A compressed response can therefore make a raw header total disagree with the decoded bytes in JavaScript. For model artifacts, prefer an identity-encoded response or a server-provided artifact-size field whose contract names the exact representation. If the browser cannot access a trustworthy total, a spinner with “Downloading; size unavailable” is more accurate than a percentage.
This distinction matters because a transfer has several independent checkpoints. The network can deliver every byte while the stored object is still incomplete, the checksum can fail after the writer closes, and a valid file can still fail to parse or allocate on a device. Make those states visible: transferring, verifying, loading, then ready, with an actionable error or retry state at each boundary. A cached model can skip transfer entirely; do not replay a fake download animation for bytes that came from local storage.
Learning outcomes
- Derive a transfer percentage only from a measured byte count and a compatible total.
- Explain how
Content-Range, validators, content coding, and browser storage affect large model downloads. - Implement streamed writes with cancellation and an explicit boundary between downloaded and ready.
Theory
Let be bytes read from the response body and be a known total for that same body representation. Then the progress fraction is
B_r and B_t are both bytes; the ratio is dimensionless. Clamp neither a mismatch nor an overrun into a plausible-looking 100 percent. If B_r > B_t, the server may have compressed the object, changed its representation, or sent a bad size field; mark the total untrusted and report an artifact protocol error. If B_t is absent, zero, inaccessible across CORS, or unknown until the end, the UI cannot calculate a meaningful percentage.
HTTP range responses add a second kind of progress. A 206 Partial Content response describes the current segment, while Content-Range describes its offset and the representation's complete size when known. Resuming at offset k is safe only if the partial file and new response refer to the same artifact revision. Use a strong ETag with If-Range where the server supports it, validate the returned range begins at k, and restart from zero if the validator changed or the server returned a full 200 response. An ETag is a representation validator, not automatically a cryptographic checksum.
Storage is another independent limit. A multi-gigabyte artifact must not be accumulated as an array of chunks and concatenated into one ArrayBuffer; that can double peak memory while weights compete with the model runtime for the same device budget. Stream into a temporary file or an appropriately managed cache, account for quota and eviction, then publish the object only after byte-count and integrity checks pass. The Storage API estimate is advisory: the browser may deny a write later or evict data under pressure.
Worked example
Suppose a model shard is 1,536 MiB and the server streams it at a steady 24 MiB/s. The expected transfer duration is 1,536 / 24 = 64 seconds. With 4 MiB chunks, the browser observes 384 writes, about six progress updates per second. A UI can coalesce those observations to one paint per frame while preserving the exact byte counter internally. If the response exposes no compatible total, those same observations still support a truthful message such as “1,024 MiB received”; they do not justify “67 percent.”
For a cross-origin artifact host, the download contract must expose the artifact-size field to the browser and identify which representation it measures. The server should also pin the artifact revision and integrity digest in a manifest. If the browser's byte count disagrees with the declared size, stop and discard the staged file instead of marking the model ready.
Trade-offs
| Choice | Benefit | Cost or limit |
|---|---|---|
| Show percent from a verified size | Easy to compare and predict | Requires the size to match the streamed representation |
| Show received bytes with unknown total | Remains truthful with chunked or hidden lengths | Does not communicate remaining time |
| Resume with byte ranges | Avoids retransmitting completed segments | Requires validators, range validation, and careful partial-file recovery |
| Stream into temporary storage | Keeps peak JavaScript memory bounded | Storage quota, permissions, and cleanup become part of the flow |
An estimated completion time adds noise when throughput varies across Wi-Fi, device sleep, and competing downloads. If shown, derive speed from a smoothed window rather than one chunk, label the estimate as approximate, and reset it after a retry or a long pause. Accessibility needs similar restraint: expose the current phase and occasional progress updates, not an assertive announcement for every network chunk.
Failure modes and misconceptions
- The percentage passes 100 percent.
Content-Lengthcan describe an encoded representation while JavaScript reads decoded bytes. Serve model weights without content compression or use a compatible artifact-size contract; never hide the mismatch by clamping it. - A resumed file joins two model revisions. A mutable URL can point to a different object after a network failure. Bind the resume offset to a strong validator, check
Content-Range, and restart if the version changes. - A partial file is treated as a complete shard. A successful range request only proves a range arrived. Do not close the staged artifact as complete until the expected total and digest have been verified.
- The network completes but the device cannot load the model. Storage quota, GPU memory, unsupported operators, and corrupt tensor metadata happen after transfer. Report these as verification or loading failures rather than moving the transfer bar backward.
- A cancel leaves a visible half-file. Abort the reader and the temporary writer, then remove partial metadata. A retry should start from a validated offset or cleanly begin again.
Decision scenario
Your browser client downloads a 1.5 GiB model from a CDN. On one device, the bar reaches 108 percent; on another, it stops at 93 percent although the request reports success. The CDN applies compression to one response path and sometimes serves byte ranges from a newly published revision. Keep the progress UI indeterminate until the CDN serves identity-encoded artifacts with a matching size contract, and make resume conditional on an unchanged strong validator. In both cases, report transfer completion separately from checksum verification and model initialization.
Diagram and measurement
The progress pipeline is manifest and quota check, streamed artifact fetch, byte accounting, digest and revision verification, then runtime initialization. A transfer ratio describes only its own phase; it is not a model-readiness score.
Implementation pattern
This browser example writes each chunk to a temporary file rather than retaining a multi-gigabyte model in JavaScript memory. The artifact host exposes X-Artifact-Size only when it equals the bytes delivered to this reader. A missing or invalid size produces byte-count progress without a percentage.
typescripttype DownloadProgress = { receivedBytes: number; totalBytes?: number };function parseArtifactSize(raw: string | null): number | undefined {if (!raw || !/^(0|[1-9]\d*)$/.test(raw)) return undefined;const size = Number(raw);return Number.isSafeInteger(size) && size > 0 ? size : undefined;}export async function downloadShard(url: string,handle: FileSystemFileHandle,signal: AbortSignal,onProgress: (progress: DownloadProgress) => void,): Promise<number> {const response = await fetch(url, { signal });if (response.status !== 200) throw new Error(`Expected a full artifact, received ${response.status}`);const totalBytes = parseArtifactSize(response.headers.get("x-artifact-size"));const reader = response.body?.getReader();if (!reader) throw new Error("The response has no readable body");const writer = await handle.createWritable({ keepExistingData: false });let receivedBytes = 0;try {while (true) {const { done, value } = await reader.read();if (done) break;await writer.write(value);receivedBytes += value.byteLength;if (totalBytes !== undefined && receivedBytes > totalBytes) {throw new Error("Artifact body exceeded its declared size");}onProgress({ receivedBytes, totalBytes });}if (totalBytes !== undefined && receivedBytes !== totalBytes) {throw new Error("Artifact body ended before its declared size");}await writer.close();onProgress({ receivedBytes, totalBytes });return receivedBytes;} catch (error) {await reader.cancel(error).catch(() => undefined);await writer.abort(error).catch(() => undefined);throw error;}}
After this function closes the file, verify the manifest digest and artifact revision before exposing it to the inference runtime. A successful byte transfer is not proof that the model is intact or loadable.