KatInterview

Retrying HTTP GET Client with Backoff and Rate-Limit Handling

System DesignModel answer
EasyModel answerSystem Designpythonrequestsretries

Last 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

  1. Retryable failures. Retry up to max_retries times (so at most max_retries + 1 calls in total) when you see:

    • an HTTP status of 500, 502, 503 or 504, or
    • a requests.exceptions.Timeout or requests.exceptions.ConnectionError.

    After the failed attempt with 0-based index k, wait base_backoff * 2**k seconds before the next attempt. With base_backoff=0.5 the waits are 0.5s, 1s, 2s, and so on. Do not sleep after the final attempt.

  2. Throttling (429). Treat it as retryable under the same retry limit. If the response has a Retry-After header 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.

  3. Fail fast on client mistakes. Any 4xx other than 429 ends the call immediately with no retry.

  4. Body validation. For a 2xx response, decode the body with .json(). If decoding raises requests.exceptions.JSONDecodeError (or a plain ValueError), do not retry. Return a failure that says the JSON was invalid.

  5. Result shape. Always return a dictionary with these keys:

    • "success": True only for a 2xx response with a successfully decoded body.
    • "data": the decoded JSON on success, otherwise None.
    • "status_code": the HTTP status, or None if no response was received.
    • "error": a descriptive string on failure, otherwise None.

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.