Retrying HTTP GET Client with Backoff and Rate-Limit Handling
System DesignModel answerLast updated
Write a Python wrapper around requests.get that retries transient failures with exponential backoff, honors Retry-After on 429, fails fast on client errors, and always returns one result shape.
Build a Fault-Tolerant GET Helper
A route-planning service for a delivery fleet polls a partner's REST API for vehicle positions. The network is flaky, the partner sometimes throttles callers, and now and then a "successful" response carries a body that is not JSON. Your task is to write a single helper that copes with all of this and gives callers a predictable result.
import requests
from typing import Any, Dict, Optional
def robust_get(
url: str,
max_retries: int = 3,
base_backoff: float = 0.5,
timeout: float = 5.0,
session: Optional[requests.Session] = None
) -> Dict[str, Any]:
...
Behavior to implement
-
Retryable failures. Retry up to
max_retriestimes (so at mostmax_retries + 1calls in total) when you see:- an HTTP status of
500,502,503or504, or - a
requests.exceptions.Timeoutorrequests.exceptions.ConnectionError.
After the failed attempt with 0-based index
k, waitbase_backoff * 2**kseconds before the next attempt. Withbase_backoff=0.5the waits are 0.5s, 1s, 2s, and so on. Do not sleep after the final attempt. - an HTTP status of
-
Throttling (
429). Treat it as retryable under the same retry limit. If the response has aRetry-Afterheader holding an integer, wait that many seconds. If the header is absent or cannot be read as an integer, use the exponential wait from rule 1. -
Fail fast on client mistakes. Any
4xxother than429ends the call immediately with no retry. -
Body validation. For a
2xxresponse, decode the body with.json(). If decoding raisesrequests.exceptions.JSONDecodeError(or a plainValueError), do not retry. Return a failure that says the JSON was invalid. -
Result shape. Always return a dictionary with these keys:
"success":Trueonly for a2xxresponse with a successfully decoded body."data": the decoded JSON on success, otherwiseNone."status_code": the HTTP status, orNoneif no response was received."error": a descriptive string on failure, otherwiseNone.
If every attempt fails with a retryable problem, return the description of the last failure.
Examples
The server answers 503, 503, then 200 with {"status": "ok"}:
robust_get("https://api.example.com/telemetry", max_retries=3)
# {"success": True, "data": {"status": "ok"}, "status_code": 200, "error": None}
The server answers 404:
robust_get("https://api.example.com/unknown", max_retries=3)
# {"success": False, "data": None, "status_code": 404, "error": "Client error: 404"}
What to deliver
Provide working code, explain how you decide what is retryable, and state the time and space complexity. Also point out the edge cases you considered.
Hints
Hint 1
Separate the three ways a call can go wrong: no response at all (an exception), a response with a bad status (a value you inspect), and a good status with a bad body. Each needs its own decision about retrying.
Hint 2
Loop over range(max_retries + 1). Each pass either returns right away (success, 4xx, bad JSON, non-transient exception) or remembers the failure and computes a delay. Only sleep when another attempt remains.
Hint 3
requests does not raise on 4xx or 5xx unless you call raise_for_status(), so check status_code yourself. Catch Timeout before ConnectionError, since ConnectTimeout inherits from both, and put the generic RequestException handler last. For Retry-After, accept only a non-negative integer and otherwise fall back to the exponential delay.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core of a good answer is to treat three failure layers differently instead of wrapping everything in one broad try/except with raise_for_status().
| Layer | How it shows up | Retry? |
|---|---|---|
| Transport | Exception: Timeout, ConnectionError | Yes |
| HTTP status | Value: 500/502/503/504, 429 | Yes |
| HTTP status | Value: other 4xx | No |
| Payload | 2xx but .json() raises ValueError | No |
| Anything else | Other RequestException (bad URL, missing scheme), unexpected statuses such as 301 or 501 | No |
Reasoning behind the table: a transient problem may disappear on its own, so retrying is worthwhile. A 404 or a malformed body is deterministic, and repeating the request only wastes the upstream's capacity.
Algorithm
- Pick the callable:
session.getif a session was injected, otherwiserequests.get. This also makes the function easy to mock in tests. - Run
max_retries + 1attempts. In each one:- Make the call with
timeout=timeout. - On an exception: for
TimeoutorConnectionError, remember the failure withstatus_code=Noneand continue. For any otherRequestException, return immediately. - On a response:
2xxgoes to JSON decoding, and the result is returned either way.429and the transient 5xx codes are remembered as failures. Other4xxcodes return immediately. Everything else returns as "unexpected status".
- Make the call with
- If another attempt remains, sleep for the computed delay, which is
base_backoff * 2**attemptor, for a 429 with a valid header, theRetry-Aftervalue. - After the loop, return the last remembered failure.
Code
import time
import requests
from typing import Any, Dict, Optional
RETRYABLE_CODES = frozenset({500, 502, 503, 504})
def _outcome(ok: bool, data: Any, code: Optional[int], err: Optional[str]) -> Dict[str, Any]:
return {"success": ok, "data": data, "status_code": code, "error": err}
def _retry_after_seconds(resp: requests.Response) -> Optional[int]:
raw = resp.headers.get("Retry-After")
if raw is None:
return None
try:
secs = int(str(raw).strip())
except ValueError:
return None # HTTP-date, empty string, garbage
return secs if secs >= 0 else None
def robust_get(
url: str,
max_retries: int = 3,
base_backoff: float = 0.5,
timeout: float = 5.0,
session: Optional[requests.Session] = None,
) -> Dict[str, Any]:
fetch = session.get if session is not None else requests.get
last_failure = _outcome(False, None, None, "No attempt was made")
for attempt in range(max_retries + 1):
wait = base_backoff * (2 ** attempt)
try:
resp = fetch(url, timeout=timeout)
except requests.exceptions.Timeout as exc:
last_failure = _outcome(False, None, None, f"Timeout: {exc}")
except requests.exceptions.ConnectionError as exc:
last_failure = _outcome(False, None, None, f"Connection error: {exc}")
except requests.exceptions.RequestException as exc:
return _outcome(False, None, None, f"Request failed: {exc}")
else:
code = resp.status_code
if 200 <= code < 300:
try:
payload = resp.json()
except ValueError as exc: # also covers requests' JSONDecodeError
return _outcome(False, None, code, f"Invalid JSON: {exc}")
return _outcome(True, payload, code, None)
if code == 429:
last_failure = _outcome(False, None, code, "Rate limited: 429")
hinted = _retry_after_seconds(resp)
if hinted is not None:
wait = hinted
elif code in RETRYABLE_CODES:
last_failure = _outcome(False, None, code, f"Server error: {code}")
elif 400 <= code < 500:
return _outcome(False, None, code, f"Client error: {code}")
else:
return _outcome(False, None, code, f"Unexpected status: {code}")
if attempt < max_retries:
time.sleep(wait)
return last_failure
Trace of Example 1: attempt 0 gets 503 and sleeps 0.5s. Attempt 1 gets 503 and sleeps 1s. Attempt 2 gets 200, decodes {"status": "ok"} and returns success. Example 2 gets 404 on the first call and returns "Client error: 404" with no sleep.
Why the details matter
- Exception order.
ConnectTimeoutinherits from bothTimeoutandConnectionError. CatchingTimeoutfirst gives a precise message. The genericRequestExceptionhandler must come last, so that only non-transient problems such asMissingSchemaorInvalidURLreach it. ValueErrorfor JSON. In requests 2.27 and later,JSONDecodeErrorsubclassesValueError. Older versions raise a plainValueError. CatchingValueErrorworks on both.status_codesemantics. It isNoneonly if the last attempt produced no response. A sequence like 503, then timeout, then exhaustion therefore reportsNone.- No trailing sleep. Sleeping after the last attempt only delays the caller's failure.
Complexity
- Attempts: O(max_retries + 1), each a constant amount of local work.
- Space: O(1) beyond the decoded payload.
- Worst-case wall time: the sum of the backoff waits,
base_backoff * (2^0 + ... + 2^(max_retries-1)), plus up tomax_retries + 1request timeouts. With the defaults that is 3.5s of sleeping. Note thattimeoutin requests applies to individual connect and read operations. It is not an overall deadline, so a slow trickle of bytes can exceed it.
Edge cases
max_retries=0: exactly one call and no sleep.Retry-After: "120": sleep 120s. An HTTP-date,""or"-5": fall back to exponential backoff.- 501, 505, 3xx, 1xx: not in the retryable set, so return immediately as unexpected.
- A
2xxcarrying a JSON list ornull: still a success, anddatais whatever.json()returned. - An empty body on a 204:
.json()raises, so it is reported as invalid JSON. Mention this and ask whether the caller expects it to be treated differently.
Common mistakes
- Calling
raise_for_status()inside one bigtryand retrying everyHTTPError, which retries 404s. - Retrying on JSON decode failure.
- Forgetting the
timeoutargument, which lets a call hang forever. - Sleeping after the final attempt.
- Treating
max_retriesas the total number of calls instead of the number of retries.
Production follow-ups
- Jitter. Add random jitter (for example, full jitter) so many clients do not retry in lockstep.
- Cap the delay. Bound both exponential backoff and server-supplied
Retry-Aftervalues, say at 30 to 60s. - Total deadline. Track an overall time budget across attempts.
- Idempotency. Retrying is safe for GET. For POST you would need idempotency keys.
- HTTP-date
Retry-After. Parse it withemail.utils.parsedate_to_datetimeand compute the difference from now. - Library support.
urllib3.util.Retrymounted on anHTTPAdaptercan do much of this declaratively, but writing it by hand makes the policy explicit and testable. - Testing. Patch
time.sleepand the get callable, feed scripted sequences of responses and exceptions, and assert both the result and the sleep arguments, for example[0.5, 1.0]for Example 1.