Sub topic 12
Range and Conditional Requests: Partial Content and Revalidation
This chapter assumes you know HTTP methods, status codes, and headers, and that you have read the CDN chapter on immutable, content-addressed URLs. It covers two HTTP features that let clients and caches avoid transferring bytes they don't need. Range requests fetch part of a file. Conditional requests ask whether a file has changed before sending it again.
Why media delivery needs both
Media files are large, and viewers rarely need all of one at once. A user who skips to minute 40 of a video doesn't need the first 40 minutes. A download that fails at 90% shouldn't restart from zero. A player that already holds a copy shouldn't download it again just to learn nothing changed.
- Range requests let the client name the bytes it wants.
- Conditional requests let the client send a validator, such as an ETag, and receive either a full response or a body-less "unchanged" answer.
Both rely on the origin or CDN returning validators and advertising range support. Object storage such as S3 and every major CDN support both, so you mostly need to avoid breaking them.
Range requests
A server announces support with a response header:
Accept-Ranges: bytesThe client then asks for a byte range. Offsets are zero-based and the end is inclusive.
| Range header | Meaning |
|---|---|
| `bytes=0-999` | The first 1000 bytes |
| `bytes=1000-` | From byte 1000 to the end |
| `bytes=-500` | The last 500 bytes |
| `bytes=0-99,200-299` | Two separate ranges |
A successful partial response uses status 206 Partial Content and a Content-Range header:
GET /media/9b1c4e/clip.mp4 HTTP/1.1
Host: cdn.example.com
Range: bytes=1000000-1999999
HTTP/1.1 206 Partial Content
Content-Type: video/mp4
Content-Length: 1000000
Content-Range: bytes 1000000-1999999/48213377
Accept-Ranges: bytes
ETag: "9b1c4e"Content-Length is the size of the returned part. The number after the slash in Content-Range is the size of the whole file.
What the server can answer
206 Partial Content: the range was satisfiable.200 OKwith the full body: the server ignoredRange. Clients must handle this. If you asked for a range and got a 200, you received the whole file.416 Range Not Satisfiable: the range starts past the end of the file. The response includesContent-Range: bytes */48213377so the client learns the real size.
Multiple ranges in one request produce a multipart/byteranges response. Many servers and CDNs handle this poorly or collapse it to a full response. Prefer sending several single-range requests.
Where ranges appear in practice
- Video seeking. Browsers send
Rangerequests for<video>elements, so a seek becomes a new range request. For MP4 files, put themoovmetadata at the start (the "faststart" option in ffmpeg), or the player must first fetch the end of the file to learn the layout. - Resumable downloads. After a failure, the client requests
bytes=N-, where N is the number of bytes it already has. - Parallel downloads. A client splits a big file into ranges and fetches them concurrently.
- Large-file readers. Tools that read only a file's header or index (for example, a PDF viewer or an archive lister) fetch just those bytes.
Here is a Python helper that requests a range and checks that the server honored it:
import urllib.request
def fetch_range(url: str, start: int, end: int):
req = urllib.request.Request(url, headers={"Range": f"bytes={start}-{end}"})
with urllib.request.urlopen(req) as res:
if res.status != 206:
raise RuntimeError(f"Range ignored, got status {res.status}")
return res.headers["Content-Range"], res.read()
if __name__ == "__main__":
content_range, data = fetch_range(
"https://cdn.example.com/media/9b1c4e/clip.mp4", 0, 1023
)
print(content_range, len(data))Conditional requests and revalidation
A validator identifies a version of a file. There are two kinds:
- ETag: an opaque string the server assigns to a version of the content.
- Last-Modified: a timestamp. It has one-second resolution, so it is the weaker choice.
The client stores the validator it received and sends it back later:
GET /playlists/live-42.m3u8 HTTP/1.1
Host: cdn.example.com
If-None-Match: "a71f03"
HTTP/1.1 304 Not Modified
ETag: "a71f03"
Cache-Control: no-cacheA 304 Not Modified response has no body. The client reuses its stored copy. If the file changed, the server returns 200 with the new body and a new ETag. If-Modified-Since works the same way with a date, and If-None-Match takes priority when both are sent.
Caches also use these headers on their own. When a cached copy goes stale, the CDN sends a conditional request to the origin. A 304 refreshes the cached copy without moving the file again.
This is the Python counterpart for a client:
import urllib.error
import urllib.request
def fetch_if_changed(url: str, etag: str | None):
headers = {"If-None-Match": etag} if etag else {}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req) as res:
return res.headers.get("ETag"), res.read()
except urllib.error.HTTPError as err:
if err.code == 304:
return etag, None # unchanged, keep the stored copy
raiseHow this fits with immutable URLs
With content-addressed URLs and Cache-Control: public, max-age=31536000, immutable, browsers don't revalidate at all, so conditional requests rarely happen for those files. Revalidation matters for the files whose URLs can't change:
- HLS and DASH playlists and manifests, which are updated in place.
- Mutable "latest" URLs such as
/users/42/avatar. - Any object where you chose a stable key.
For these, use Cache-Control: no-cache together with an ETag. Despite the name, no-cache allows storing the file. It means "revalidate before reuse." Use no-store if a response must not be stored at all.
Combining the two with If-Range
Resuming a download has a hazard. If the file changed on the server between the first attempt and the resume, appending new bytes to old ones produces a corrupt file. If-Range prevents this:
GET /exports/report.zip HTTP/1.1
Host: files.example.com
Range: bytes=52428800-
If-Range: "c0ffee"
HTTP/1.1 206 Partial Content
Content-Range: bytes 52428800-104857599/104857600
ETag: "c0ffee"If the ETag still matches, the server returns the requested range. If it doesn't, the server ignores Range and returns the full new file with 200. The client must check the status code and restart if it gets a 200.
If-Range requires a strong validator. Weak ETags (those starting with W/) don't qualify.
How CDNs and storage behave
- S3 and similar stores honor
Range,If-None-Match,If-Modified-Since, andIf-Rangeon GET. For S3, the ETag of a multipart-uploaded object is not an MD5 of the content. Treat it as an opaque version identifier, and don't compare it to a checksum you computed. - CDNs differ in how they cache ranged requests. Some fetch the whole object from the origin and slice it for each viewer. Others cache fixed-size chunks. A few forward each range to the origin as a cache miss. Check your CDN's documentation, because uncached ranges on a large video can multiply origin traffic.
- Compression complicates ranges, because offsets refer to the encoded bytes. Videos and images are already compressed, so leave them out of on-the-fly gzip or Brotli.
- Cross-origin players read
Content-RangeandETagthrough JavaScript only if the response includesAccess-Control-Expose-Headers: Content-Range, ETag, Accept-Ranges.
Common errors
- Stripping
Accept-RangesorRangein a proxy. Seeking breaks, and the browser downloads the video from the start every time. - Resuming without
If-Range. The result is a silently corrupt file after the origin object changes. - Assuming a response to
Rangeis always 206. Check the status. A 200 means the whole file is coming. - Generating ETags that differ per server. If each origin instance computes its own ETag (for example, from inode and modification time), revalidation fails across a fleet and every check returns a full 200. Derive the ETag from content or from stored object metadata.
- Streaming a proxied file without range support. If your API server serves media itself, your framework must implement
Range. Serving from object storage or a CDN avoids this work. - Using
no-cachewhere you meantno-store, or the reverse.
Exercise
A client resumes a 100 MB download with Range: bytes=60000000- and If-Range: "v1". Meanwhile the file was replaced and now has the ETag "v2". What status code does the server return, what does the body contain, and what must the client do?
Show answer
The server returns 200 OK with the full new file, because the If-Range validator doesn't match and the Range header is ignored. The client must notice the 200, discard the partial data it already saved, and write the new body from the start.
Exercise
Your HLS playlist is served at a fixed URL and updated every few seconds, while its video segments use content-hashed URLs. Which Cache-Control and validator setup fits each, and why?
Show answer
Segments: public, max-age=31536000, immutable, because their URLs change when content changes, so they never need revalidation. Playlist: no-cache plus an ETag, so clients and the CDN revalidate on each use and get a cheap 304 when nothing changed.