← All Exercises
HTTP GET with Retry and Backoff
intermediatepython
Background
Transient network and server failures are common; retries must be bounded, backed off, and limited to safe idempotent requests such as GET.
Problem
Implement fetch_json(url, attempts=3, opener=urllib.request.urlopen, sleep=time.sleep) that retries transient HTTP 429 and 5xx responses plus URLError with exponential backoff, returns decoded JSON, and raises RuntimeError after the final attempt.
Input
A URL, an attempt budget, an opener callable returning a response object, and a sleep function.
Output
The decoded JSON value on success; permanent HTTP errors are re-raised immediately, and exhausted retries raise RuntimeError.
Sample tests
Sample 1
Input: opener returns HTTP 503 twice, then 200 with {"ok": true}; attempts = 3Expected: {'ok': True}Sample 2
Input: opener returns HTTP 404 on the first call; attempts = 3
Expected: HTTPError 404 raised immediately
Your solution
Learning objective
Add bounded exponential backoff to an HTTP client while distinguishing retryable from permanent failures.