DEV Community

Fast Data
Fast Data

Posted on

How to retry HTTP requests in Python (httpx) without letting your fallback hide the real error

This morning my daily archive job printed this:

archived: mcp_registry, bund_tenders_rss(100, direct), defillama_stablecoins(475, direct), defillama_chains(426, direct)
failed: probe: probe HTTP 401
Enter fullscreen mode Exit fullscreen mode

Two BaFin RSS feeds were missing. "401" says authentication, so my first thought was a key problem. It wasn't. Fetching the same feed by hand a minute later worked fine: HTTP 200, 10 KB.

What actually happened: the network proxy my job runs behind dropped the connection halfway through one request (its log said ws_closed_mid_exchange). My script caught the exception, decided the direct route was dead, and switched to a fallback route, an old paid API whose token expired weeks ago. The fallback failed with 401, and that was the only error that reached the log. The real cause, a one-off dropped connection that a single retry would have fixed, was gone.

Disclosure: I run small data pipelines and AI-agent automations; this is from my own archive job. The helper below is in a public repo.

Two mistakes in one line of control flow

# what I had (simplified)
try:
    body = client.get(url).text          # one attempt
except Exception:
    body = fallback(url)                 # different system, different failure
Enter fullscreen mode Exit fullscreen mode
  1. No retry before the fallback. A transient error (connection reset, timeout) was treated like a permanent one.
  2. The fallback's error replaced the original. When both failed, I only saw the second failure, which pointed at the wrong cause.

What to retry, and what not to

The rule of thumb: retry what time can fix; fail fast on what time can't.

Failure httpx raises / returns Retry? Why
Connection reset, tunnel closed ReadError, ConnectError, ProxyError (all TransportError) Yes Usually transient
Timeout ConnectTimeout, ReadTimeout, PoolTimeout (TimeoutException) Yes, with backoff Server or path is busy
429 Too Many Requests status 429 Yes, honor Retry-After You were told to wait
502 / 503 / 504 status Yes Gateway or upstream hiccup
401 / 403 status No Bad or missing credentials; waiting won't help
404 / 410 status No The thing isn't there
Other 4xx status No Your request is wrong

In httpx all the network-level errors share the base class httpx.TransportError, so you can catch that one and leave everything else alone. (Status errors are only raised if you call raise_for_status(). I check status_code directly so the decision stays in one place.)

The helper

retry_fetch.py, core part:

RETRY_STATUS = {429, 502, 503, 504}

def fetch(url, client, attempts=3, base=1.0, cap=30.0):
    log = []
    for i in range(1, attempts + 1):
        wait = None
        try:
            r = client.get(url)
            if r.status_code < 400:
                return r
            log.append(f"try {i}: HTTP {r.status_code}")
            if r.status_code not in RETRY_STATUS:
                break                                   # permanent: stop now
            ra = r.headers.get("retry-after", "")
            wait = float(ra) if ra.isdigit() else None
        except httpx.TransportError as e:
            log.append(f"try {i}: {type(e).__name__}")
        if i < attempts:
            time.sleep(min(cap, wait if wait is not None else random.uniform(0, base * 2 ** i)))
    raise FetchFailed(url, log)
Enter fullscreen mode Exit fullscreen mode

Three details matter more than they look:

  • Every attempt is logged. If it finally fails, you see try 1: ReadError; try 2: ReadError; try 3: HTTP 503, not just the last line.
  • Full jitter (random.uniform(0, base * 2**i)). If ten scheduled jobs fail at 05:47 and all retry exactly 2 s later, they hit the server together again. Random waits spread them out.
  • A cap on the wait, and on Retry-After, so one bad header can't park your job for an hour.

A fallback that keeps both reasons

def fetch_with_fallback(url, client, fallback):
    try:
        return "direct", fetch(url, client)
    except FetchFailed as primary:
        try:
            return "fallback", fallback(url)
        except Exception as e:
            raise FetchFailed(url, primary.attempts + [f"fallback: {type(e).__name__}: {e}"]) from e
Enter fullscreen mode Exit fullscreen mode

I tested both paths with httpx.MockTransport, so no network was needed. A flaky source that fails twice and then succeeds:

mock recovered: 200 after 3 calls
Enter fullscreen mode Exit fullscreen mode

And the failure case from this morning, now with an honest message:

both failed -> https://x.test/b: try 1: ConnectError; try 2: ConnectError; try 3: ConnectError; fallback: RuntimeError: fallback HTTP 401
Enter fullscreen mode Exit fullscreen mode

With that line I would have known in five seconds that the 401 was a side effect, not the cause.

Against real endpoints:

$ python retry_fetch.py "https://www.bafin.de/DE/service/rss/_function/rssnewsfeed.xml?nn=150166"
200 10118 bytes
$ python retry_fetch.py "https://dev.to/api/articles/me"
FAILED: https://dev.to/api/articles/me: try 1: HTTP 401
Enter fullscreen mode Exit fullscreen mode

The second one stops after one try, as it should: no key, no point retrying.

Should the fallback even be there?

The other lesson from this morning has nothing to do with retries. My fallback pointed at a service I had stopped using. It had been failing every single day, invisibly, because the primary route usually worked. A fallback you never exercise is a fallback you don't have. Either test it on a schedule (a cheap health check), or delete it. A dead fallback doesn't make the job more reliable. It just makes the error message lie.

Takeaways

  • Retry transport errors and 429/5xx; don't retry 401/403/404.
  • Use exponential backoff with jitter and a cap; respect Retry-After.
  • Log every attempt, not just the last.
  • When a fallback fails too, report both errors.
  • Health-check fallbacks, or remove them.

Question: do you keep fallback data sources in your scheduled jobs, and if so, how do you make sure they still work when you actually need them?

Top comments (0)