Re-downloading the Same 20,000 Images Every Night: Conditional Requests, If-Range and Resumable Downloads in the Browser
A collector that runs on a schedule has a boring failure mode, and it is not a bug in the parser. It is the network. The first run is pleasant. You point the crawler at a gallery site, it walks the DOM, resolves a few t
A collector that runs on a schedule has a boring failure mode, and it is not a bug in the parser. It is the network.
The first run is pleasant. You point the crawler at a gallery site, it walks the DOM, resolves a few thousand image URLs, and downloads them at whatever concurrency the tabs allow. Three seconds per image, most of it spent on a 200 response that hands you bytes you already had on disk from the previous run. Run it nightly and you are spending your bandwidth, your target site's bandwidth and your rate-limit budget re-fetching an archive that changed by forty files.
The fix is not "check the file size before downloading". It is HTTP cache revalidation plus byte-range resume, and in a browser both are awkward enough that most extensions skip them entirely.
What the response headers actually promise
Every download carries a validator. Two kinds matter:
-
ETag β an opaque string the server assigns.
"abc123"is a strong validator,W/"abc123"is weak, and theW/prefix is not decoration: a weak validator only promises semantic equivalence, so it is legal for a 304 check and illegal for a range resume. - Last-Modified β a timestamp, at best one-second resolution, and therefore weaker than any ETag in practice.
On the next run you send If-None-Match: "abc123" and, if you only have the timestamp, If-Modified-Since: Tue, 24 Nov 2026 09:14:00 GMT. When the validator still matches, the server answers 304 Not Modified with no body. Per RFC 9110, a 304 must not carry a body, and a recipient is expected to merge the new headers into the stored representation rather than replace the metadata wholesale. If you naively overwrite your cached entry with the 304's headers, you throw away Content-Length and Content-Type and your local copy becomes unusable even though the bytes on disk are perfectly fine.
The other half is freshness: Cache-Control: max-age=86400 means you do not need to revalidate at all inside that window, immutable means the resource will never change at that URL (so even a reload skips revalidation), and no-cache is the confusing one β it does not mean "do not store", it means "store, but revalidate before every reuse". A collecting tool wants the opposite of what a browser wants: browsers may serve stale images to avoid a request, while a collector must never accept stale bytes for a file it believes it just captured.
And then Vary. If the response says Vary: Accept or Vary: User-Agent, the same URL can legitimately yield different bytes to different clients, so a validator is only meaningful inside the exact request context that produced it. CDNs serving AVIF to modern clients and JPEG to old ones use exactly this, which is why the same gallery URL can hand you image/avif on one run and image/jpeg on the next.
Ranges, and what If-Range is for
Accept-Ranges: bytes advertises that the origin understands byte ranges, and a well-formed request looks like Range: bytes=0-1048575. A successful partial answer is 206 Partial Content with Content-Range: bytes 0-1048575/6291456 β the total after the slash is the full resource length, and that number is the only trustworthy way to know how much is left. A request past the end of the resource returns 416 Range Not Satisfiable with Content-Range: bytes */6291456.
The trap is resume. Suppose you cached the first 1 MB of a 6 MB image last night and the file has since been replaced on the server. Sending Range: bytes=1048576- alone gives you bytes from the new file appended to the old prefix β a corrupt image that decodes into confetti. That is what If-Range prevents: send If-Range: "abc123" with your strong ETag and the server either resumes (206) or, if the validator changed, ignores the range and answers 200 OK with the entire body, which is exactly the safe fallback. Two rules that bite people:
-
If-Rangeaccepts an ETag or an HTTP-date, never both, and the date form requires the origin to be able to tell "unmodified" without ambiguity β one-second granularity makes it risky. - Only a strong validator is legal here. A weak
W/"..."must not be used withIf-Range; if you do, servers are free to honour it and hand you mismatched bytes.
Multi-range requests (bytes=0-100,500-600) are advisory, may come back as multipart/byteranges or as a plain 200, and are not worth implementing in a collector.
Getting this right in a browser extension
You cannot spawn curl. What you have is fetch with AbortController, a ReadableStream body, IndexedDB for the bytes, and a background service worker that may be killed mid-flight.
A workable shape for one asset:
const cached = await idb.get(url); // {etag, size, chunks[], contentType}
const headers = cached?.etag ? { "If-None-Match": cached.etag } : {};
if (cached?.etag && cached.size && cached.chunks.length) {
headers["If-Range"] = cached.etag;
headers["Range"] = `bytes=${cached.size}-`;
}
const ac = new AbortController();
const res = await fetch(url, { headers, signal: ac.signal, credentials: "include" });
if (res.status === 304) return { path: cached.path, fresh: true };
if (res.status === 206) return append(res, cached); // verify Content-Range total
if (res.status === 200) return store(res); // validator changed: start over
Each branch has its own hazards, and they only show up in production:
-
A CDN that ignores
Rangeanswers 200 with the whole file. Appending that to an existing prefix corrupts the asset, so the 200 branch must always discard cached chunks rather than assume "the server sent me the rest". -
Content-Encoding: gzipbreaks byte arithmetic. If the origin compresses a response, the range applies to the encoded representation andContent-Lengthdescribes the compressed size, so a resumed prefix plus a new suffix is not the concatenation you think it is. SendAccept-Encoding: identityfor binary assets. - Signed URLs that change per request β token in the query string β usually change the ETag too, which silently defeats revalidation: every run looks like a brand-new file. If the path is stable, key the cache on the path, not the full URL.
-
HEAD is not a probe. Plenty of image CDNs answer
HEADwithoutAccept-Rangesor withoutContent-Length, so discovering range support via a HEAD costs one request and often returns nothing useful. -
The service worker gets killed. Manifest V3 event pages terminate, and a half-written IndexedDB transaction that was supposed to be atomic leaves you with a fragment that claims its full length. Persist progress in a separate metadata record, and reconcile
Content-Rangeagainst it before trusting anything. - Concurrency duplicates work. Two tabs crawling the same page enqueue the same URL; without a per-URL in-flight lock in a shared worker, both write the same chunks and one clobbers the other.
Do this for twenty thousand images and the accounting is unforgiving: every resume needs a validator, every validator needs a cache entry with normalised keys, every cache entry needs garbage collection, and the whole thing has to survive a killed worker without silently producing truncated JPEGs that only fail when someone opens the file three weeks later.
Where OmniPic fits
That is the entire scaffolding I ended up building: a persistent local index, strong-validator revalidation, byte-range resume, content-addressed dedupe, and a worker that survives being torn down. OmniPic AI Studio Pro ships it as an extension, so the crawl-and-store loop already behaves this way on the sites you visit.
It walks the whole page β including lazy-loaded and CSS-background images β normalises thumbnail URLs back to the original CDN assets on Alibaba OSS, Tencent COS and Qiniu, and keeps everything in a local index with 100% on-device processing, so no bytes and no browsing history leave your machine. Near-duplicates collapse onto a single entry via 64-bit perceptual hashing, and when you are done the batch export streams an archive of two thousand-plus files without holding the whole set in memory.
On top of that: reverse image search running entirely on-device (MobileNet features with WebGPU acceleration), one-click export into Eagle or Billfish, and a ZIP pipeline that streams to disk instead of buffering in RAM.
The extension is live on Chrome, Edge and Firefox:
https://chromewebstore.google.com/detail/omnipic-studio-pro/cokoeaaaglgcljahaffjeijomhmkljlc
A short checklist
If you are writing your own collector, keep these four habits: send If-None-Match on every repeat visit and merge 304 headers instead of replacing them, use If-Range with a strong ETag whenever you resume, request Accept-Encoding: identity for binary assets, and treat Content-Range's total as the authority over your own bookkeeping. Everything else β dedupe, export, library integration β can come later, once you are no longer paying for the same megabyte twice.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.