HTTP Range Requests: 206, 416 and Safe Download Resumption
Debug HTTP partial downloads with byte ranges, Content-Range, strong If-Range validators and a tested local Python and curl lab.
A partial download is useful only when its bytes belong to the same representation as the bytes already saved. A server can answer a Range request with 206, ignore it and send 200, or reject an unsatisfied range with 416. A downloader must make a different storage decision for each result. This guide connects those responses to a small reproducible experiment, then turns the observations into a conservative resume workflow.
Read offsets as byte positions, not quantities
Take a 36-byte artifact containing the ASCII characters 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ, with no trailing newline. The first position is zero and the final position is 35. Requesting bytes=0-15 asks for sixteen bytes. Requesting bytes=16- asks for the remainder, while bytes=-4 asks for the last four bytes. These requests identify positions in a selected representation; they do not identify records, lines, or Unicode characters.
For a single-part response to the first request, expect Content-Range: bytes 0-15/36 and a sixteen-byte body. Content-Length describes that response content, whereas the number after the slash describes the complete representation length. Confusing the two can make a progress bar show completion after one small chunk.
Keep a paper expectation before testing a large file: saved prefix length, requested start, expected final position, and expected complete size. For the fixture, the prefix length sixteen means the next start is sixteen. Starting at fifteen duplicates a byte; starting at seventeen skips one. A final size check catches either mistake, but a trusted digest catches more kinds of corruption.
| Request for 36-byte fixture | Body positions if honored | Body size |
|---|---|---|
| bytes=0-15 | 0 through 15 | 16 |
| bytes=16- | 16 through 35 | 20 |
| bytes=-4 | 32 through 35 | 4 |
| bytes=30-99 | 30 through 35 | 6 |
| bytes=36- | No satisfiable positions | 416 response |
Treat the status as an instruction about storage
A 206 response is a candidate for assembly, not permission to append blindly. Check that a single Content-Range starts at the requested offset, ends consistently with its body length, and refers to the expected representation. Reject a multipart response unless your client deliberately parses its boundaries and each part. Never concatenate the entire multipart wire body as artifact bytes.
A 200 response contains the full selected representation. Write it to a separate replacement file starting at offset zero; appending it to an existing prefix produces a duplicated or mixed artifact. This can happen even when the earlier response advertised Accept-Ranges: bytes. That header is useful advice, but the next actual GET response is the evidence.
A 416 response can report the current size using Content-Range: bytes */36. An offset at or beyond that size has no bytes to return. If your local file is exactly that length, it might already be complete, but equal length is not proof of identity. Verify its expected version and digest before accepting it. If it is longer, preserve it for diagnosis and restart into a fresh file instead of trimming it by guesswork.
Pin the representation before resuming it
Store the final download URL, strong ETag, content encoding, and known complete size alongside the partial file. Keep the request headers that affect representation selection consistent. A URL can return a different body tomorrow, or a different body for another language, authorization context, or encoding. An offset alone cannot identify which bytes should follow the saved prefix.
Send the stored strong ETag in If-Range together with Range. A matching validator allows normal range processing; a mismatch makes the server ignore Range and transfer the full representation instead. That fallback is the reason the client must distinguish 200 from 206. A weak tag prefixed W/ is unsuitable for If-Range. An HTTP date has additional strong-validator requirements, so prefer a supplied strong entity tag for this workflow.
Do not confuse this with cache revalidation. If-None-Match can produce 304, which is not a missing download segment. If-Range answers a different question: whether the server can continue the representation you already partly possess. Keep your cache-check logic and resume-file logic separate even if both store an ETag.
Source: RFC 9110: HTTP Semantics, range and conditional requests ↗
A local fixture that exposes the three decisions
Save the following as range_lab.py and run python range_lab.py. It binds only to loopback and serves a constant 36-byte body at /fixture. Leave that terminal running and use another terminal for the curl commands. Stop it with Ctrl+C when finished. The lab does not publish a server, access outside files, or modify your website.
This is deliberately a small teaching fixture, not a production file server. It supports one byte range and one fixed strong entity tag. It ignores malformed, unsupported, and multiple-range values by sending the complete body; valid but unsatisfied single ranges receive 416. Date validators are not implemented and fall back to 200. HEAD describes the full GET response rather than serving a range.
The parser bounds numeric field length for this experiment. A real download service also needs authentication, authorization, request limits, streaming, correct storage semantics, and tests for its framework and proxy chain. A passing loopback lab establishes how these examples behave; it says nothing about whether a CDN or object store uses the same configuration.
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
DATA = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ETAG = '"fixture-v1"'
def select_range(value, size):
# None means ignore Range. ValueError means a valid, unsatisfied range.
m = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", value)
if not m or not any(m.groups()):
return None
first, last = m.groups()
if not first:
count = int(last)
if count == 0 or size == 0:
raise ValueError("unsatisfied")
return max(0, size - count), size - 1
start = int(first)
end = int(last) if last else size - 1
if last and end < start:
return None
if start >= size:
raise ValueError("unsatisfied")
return start, min(end, size - 1)
class Handler(BaseHTTPRequestHandler):
def do_HEAD(self):
self.respond(head=True)
def do_GET(self):
self.respond(head=False)
def respond(self, head):
if self.path != "/fixture":
self.send_error(404)
return
status, body, content_range = 200, DATA, None
requested = self.headers.get("Range")
validator = self.headers.get("If-Range")
if not head and requested and (validator is None or validator == ETAG):
try:
selected = select_range(requested, len(DATA))
if selected is not None:
start, end = selected
status, body = 206, DATA[start:end + 1]
content_range = f"bytes {start}-{end}/{len(DATA)}"
except ValueError:
status, body = 416, b""
content_range = f"bytes */{len(DATA)}"
self.send_response(status)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Accept-Ranges", "bytes")
self.send_header("ETag", ETAG)
self.send_header("Content-Length", str(len(body)))
if content_range is not None:
self.send_header("Content-Range", content_range)
self.end_headers()
if not head:
self.wfile.write(body)
if __name__ == "__main__":
print("Fixture: http://127.0.0.1:8765/fixture", flush=True)
with ThreadingHTTPServer(("127.0.0.1", 8765), Handler) as server:
try:
server.serve_forever()
except KeyboardInterrupt:
passObserve a good continuation and a changed-version fallback
Run these commands in an empty temporary directory. The first two requests save their bodies separately so inspecting a surprising response cannot silently corrupt an existing download. The header files make it possible to compare status, ETag, Content-Length, and Content-Range before doing any assembly.
For this fixed fixture, part-a.bin should contain 0123456789ABCDEF and part-b.bin should contain GHIJKLMNOPQRSTUVWXYZ. The changed-validator request should produce 200 and the entire 36-byte body in replacement.bin. The out-of-bounds request should produce 416 and advertise the complete length. These are expected outcomes of this lab, not promises about another server.
curl --continue-at - can derive a resume offset from an existing output file, while --range selects an explicit interval. Do not combine the options in one transfer. Supplying an offset does not automatically prove the remote object is the same version. Keep the original validator and inspect failures; do not turn a resume error into an unconditional shell append.
curl -sS -D first.headers --range 0-15 -o part-a.bin http://127.0.0.1:8765/fixture
curl -sS -D next.headers --range 16- -H 'If-Range: "fixture-v1"' -o part-b.bin http://127.0.0.1:8765/fixture
curl -sS -D changed.headers --range 16- -H 'If-Range: "old-version"' -o replacement.bin http://127.0.0.1:8765/fixture
curl -sS -D unsatisfied.headers --range 36- -o unsatisfied.bin http://127.0.0.1:8765/fixtureVerify assembly against bytes you independently know
Only for the known fixture, verify both parts before creating the combined output below. The explicit expected values make this an independent check of the transfer. A general downloader cannot use these constants; it needs the actual artifact metadata, range validation, and a trusted expected digest where one is available.
The local checks for this article exercised real loopback HTTP requests and curl transfers, including bounded, open-ended, suffix, clipped, invalid, unsatisfied, and validator-mismatch cases. They also verified exact byte reconstruction and a curl resume. They did not test TLS, a public origin, browser fetching, intermediaries, or a large-file streaming implementation.
For a real artifact, keep the partial file private until all required intervals are present and verification succeeds. Rename a completed temporary file into its final location on the same filesystem when atomic replacement is needed. Retain the old valid artifact until the replacement is ready; a failed network request should not destroy the last usable copy.
from pathlib import Path
expected = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
a = Path("part-a.bin").read_bytes()
b = Path("part-b.bin").read_bytes()
assert a == expected[:16]
assert b == expected[16:]
assert Path("replacement.bin").read_bytes() == expected
assert a + b == expected
Path("combined.bin").write_bytes(a + b)
print("Verified 36 fixture bytes")Keep compression and intermediaries in the investigation
Byte offsets refer to representation data, so a content-coded body needs consistent treatment. If one request stores decoded bytes and a later request resumes offsets into encoded bytes, the pieces are not compatible. For a simple diagnostic, request Accept-Encoding: identity consistently and verify that the response has no unexpected Content-Encoding. Do not assume a preference sent by the client is proof of what arrived.
Compare the same request through the origin and through the delivery endpoint when you control both. Record final URL, status, content encoding, validator, and range fields, without copying authorization secrets into logs. A redirect to a login page can return a successful HTML body instead of your artifact. Content type, expected size, and a trusted digest help catch that failure before release.
When browser JavaScript cannot read a response header that curl can see, investigate CORS separately. ETag, Content-Range, and Accept-Ranges are not all exposed automatically to cross-origin scripts; the server may need an explicit Access-Control-Expose-Headers policy. That policy makes metadata readable and does not grant access to the artifact by itself.
A resume decision that survives a failed request
Before a request, freeze the local prefix length and its metadata. Receive new bytes into a candidate file. For a validated 206, check the returned interval and body length before assembly. For 200, verify a complete replacement. For 416, compare current length and identity evidence, then either verify completion or restart. For transport errors or unexpected statuses, preserve the prefix and stop that attempt.
If the transfer is interrupted again, retain only a prefix whose relationship to the original representation is established. Do not mark a file complete because the server closed a connection or because the progress counter reached a guessed total. Bound retries and timeouts, and record the error that determined your next action.
The practical test is whether a changed object, an ignored Range header, or an off-by-one offset can corrupt a file without being noticed. Build your acceptance cases around those failures. Correct status handling, stable identity, and independent final verification make resumption an explainable operation rather than a hopeful concatenation.
Your next steps
- A byte interval is zero-indexed and inclusive; validate the actual Content-Range.
- Use a strong If-Range validator and handle a 200 replacement separately from a 206 segment.
- Equal lengths and successful requests do not replace artifact identity and integrity verification.
Sources & official resources
Linked resources checked on 2026-10-28. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →