---
title: "How to Handle 429 Errors With Exponential Backoff in Python"
description: "On a 429, honor Retry-After if it is set; otherwise wait with jittered exponential backoff. Proxy-ready requests and urllib3 Retry examples, tested locally."
url: https://proxynet.io/blog/proxy-429-exponential-backoff-python
date: 2026-12-01
author: "Acar Diveroli"
category: "Tutorial, Web Scraping"
lang: en
---

# How to Handle 429 Errors With Exponential Backoff in Python

Exponential backoff is a way to retry a failed request at increasingly long intervals. The wait ceiling doubles with each attempt, and the delay is picked at random below that ceiling. When you get a 429 error, the server often states the wait time in a `Retry-After` header. If the header is missing, this method sets the wait. This post explains how to read `Retry-After`, which status codes to retry, and Python code that runs through a proxy.

> **Note: Short answer**
>
> If `Retry-After` is set, wait that long. Otherwise wait a random time below a ceiling that doubles on each attempt, cap attempts at 4-5 and retry only on `429` and `503`.

## 429 and Retry-After

`429 Too Many Requests` is the status code that says you sent too many requests in a given time. RFC 6585 defines it and notes that the response may include a `Retry-After` header. The header is optional. How the limit is counted is also up to the server, not the standard. We covered those counting rules in [429 Too Many Requests and Rate Limit Errors Explained](/blog/http-429-too-many-requests).

`Retry-After` is defined in RFC 9110 and comes in two formats:

- **Seconds:** `Retry-After: 120`. A non-negative integer that means wait two minutes.
- **HTTP date:** `Retry-After: Tue, 01 Dec 2026 10:00:00 GMT`. It means do not retry before this moment.

The same header appears in `503 Service Unavailable` responses. There it says how long the service is expected to stay down. That is why both codes get the same wait logic.

## Exponential backoff and jitter

With exponential backoff, the wait ceiling doubles on every attempt. The formula is short: `ceiling = min(cap, base × 2^attempt)`. With a 1-second base and a 60-second cap, the ceilings grow like this:

| Attempt | Ceiling | Wait with full jitter |
|---|---|---|
| 0 | 1 s | 0-1 s |
| 1 | 2 s | 0-2 s |
| 2 | 4 s | 0-4 s |
| 3 | 8 s | 0-8 s |

Jitter is randomness added to the wait. Picture many clients hitting the same limit. If all of them wait exactly 2 seconds, they all come back at once and get another 429. A random delay spreads that wave over time. The method called "full jitter" picks the delay at random between 0 and the ceiling.

A cap is required too. A wait that doubles without limit reaches minutes within a few attempts, then hours. Limit the number of attempts as well. A limit that does not clear after five attempts is a problem with the job plan, not the loop.

## Status codes worth retrying

Retrying only makes sense for temporary errors. `429` and `503` are temporary, and the situation can change after a wait. For the rest of the 4xx family, sending the same request again brings the same response.

| Code | Retry | Why |
|---|---|---|
| `429` | ✓ | The rate limit is time-based |
| `503` | ✓ | The service is temporarily down |
| `400` | ✗ | The request is malformed; fix it first |
| `401` | ✗ | Credentials are missing or invalid |
| `403` | ✗ | The server refused the request |
| `404` | ✗ | The address does not exist |

A `407` from the proxy belongs to this group too. The proxy, not the target site, rejected your credentials. Waiting will not fix it.

The method matters as well. `GET` and `HEAD` are idempotent: however many times the same request arrives, the effect on the server is the same. RFC 9110 says a client should not automatically retry a non-idempotent request. A `POST` can submit an order or a form a second time. So it stays out of the automatic loop.

## Switching IPs is not the first fix

A 429 is a message from the site about load. The counter is often tied to an account, a session or an API key. In that case a new IP address changes nothing. Even when the counter is per IP, splitting the same pace across other addresses puts the same load on the server.

The right order is this: first lower the number of concurrent requests to the same site, then add waits between requests. Read the rules in the site's robots.txt file, and use the official API if there is one. How to read robots.txt is covered in [What Is a robots.txt File and How Do You Read It?](/blog/robots-txt).

The proxy comes after that. In a permitted, high-volume job, total traffic already slowed to a pace the site accepts is spread across addresses. A [Rotating Proxy](https://proxynet.io/rotating-proxy) does that spreading at the gateway. The backoff loop still lives in your code.

## Python code: requests and a proxy

The code below sends requests through a proxy with `requests` and backs off on 429 and 503. It checks `Retry-After` first and converts both formats to seconds. Without the header it applies full jitter. Proxy setup details are in [How to Use a Proxy With Python Requests](/blog/python-requests-proxy).

```python
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

import requests

PROXY = "http://user:pass@pr.proxynet.io:8000"

RETRY_STATUSES = {429, 503}  # status codes to retry
MAX_ATTEMPTS = 5             # total attempts, including the first request
BASE_DELAY = 1.0             # ceiling of the first wait (seconds)
MAX_DELAY = 60.0             # upper limit for a single wait (seconds)

class RetryLater(Exception):
    """Attempts ran out, or the server asked for a wait longer than MAX_DELAY."""

    def __init__(self, response, wait=None):
        self.response = response
        self.wait = wait
        super().__init__(f"HTTP {response.status_code}, wait requested by the server: {wait} s")

def parse_retry_after(value):
    """Converts Retry-After to seconds. Returns None if the header is missing or unreadable."""
    if value is None:
        return None
    value = value.strip()
    if value.isdigit():                      # "120" format
        return float(value)
    try:
        when = parsedate_to_datetime(value)  # "Tue, 01 Dec 2026 10:00:00 GMT" format
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())

def backoff_delay(attempt):
    """Full jitter: a random time between 0 and the exponential ceiling."""
    ceiling = min(MAX_DELAY, BASE_DELAY * 2 ** attempt)
    return random.uniform(0, ceiling)

def get_with_backoff(session, url, **kwargs):
    kwargs.setdefault("timeout", (5, 30))
    for attempt in range(MAX_ATTEMPTS):
        response = session.get(url, **kwargs)
        if response.status_code not in RETRY_STATUSES:
            return response  # 200, 403, 404... the caller decides

        wait = parse_retry_after(response.headers.get("Retry-After"))
        if wait is not None and wait > MAX_DELAY:
            raise RetryLater(response, wait)  # the layer that schedules jobs handles long waits
        if attempt == MAX_ATTEMPTS - 1:
            break
        if wait is None:
            delay = backoff_delay(attempt)
        else:
            delay = wait + random.uniform(0, 1)  # spreads out clients that return at once
        print(f"Got {response.status_code}, waiting {delay:.1f} s "
              f"(attempt {attempt + 1}/{MAX_ATTEMPTS})")
        time.sleep(delay)
    raise RetryLater(response, wait)

if __name__ == "__main__":
    with requests.Session() as session:
        session.proxies = {"http": PROXY, "https": PROXY}
        try:
            r = get_with_backoff(session, "https://example.com/")
            print(r.status_code, len(r.content), "bytes")
        except RetryLater as exc:
            print("Gave up:", exc)
```

The code makes three decisions:

- **Long waits stay out of the loop.** If `Retry-After` exceeds 60 seconds, the code raises `RetryLater` and stores the requested wait on the exception. Putting that URL back on a queue is the job of the layer that schedules work.
- **A small margin is added to `Retry-After`.** The header gives the minimum wait. A 0-1 second extra keeps clients that got the same response from returning in the same second.
- **Other codes are returned as they are.** The loop does not run for `403` or `404`. The calling code decides.

`requests` does not retry on its own: `HTTPAdapter` comes with zero retries by default. Connection errors (`requests.ConnectionError`) are not caught in this loop and propagate to the caller.

## The same job with urllib3 Retry

urllib3, which sits under `requests`, offers the same logic through its `Retry` class. The class is attached to an `HTTPAdapter` and applies to every request in the session.

```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

PROXY = "http://user:pass@pr.proxynet.io:8000"

retry = Retry(
    total=4,                          # at most 4 retries after the first request
    status_forcelist=[429, 503],
    allowed_methods=["GET", "HEAD"],  # POST is never resent automatically
    backoff_factor=1,                 # waits: 0, 2, 4, 8 s
    backoff_jitter=1,                 # random 0-1 s added to each wait
    backoff_max=60,
    respect_retry_after_header=True,  # on 429 and 503, Retry-After comes first
    retry_after_max=60,               # longer Retry-After values are clipped to 60 s
    raise_on_status=False,            # returns the last response when attempts run out
)

session = requests.Session()
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
session.proxies = {"http": PROXY, "https": PROXY}

if __name__ == "__main__":
    r = session.get("https://example.com/", timeout=(5, 30))
    print(r.status_code)
```

It is shorter, but it behaves differently from the hand-written code:

| Topic | Hand-written code | urllib3 `Retry` |
|---|---|---|
| First retry | Waits 0-1 s | No wait without the header |
| Jitter | Random below the ceiling | 0-1 s added to a fixed wait |
| `Retry-After` > 60 s | Gives up, reports the wait | Waits 60 s, retries |
| Attempts run out | Raises `RetryLater` | Returns the last 429 response |

The third row matters. urllib3 2.6.3 caps a `Retry-After` longer than 6 hours at 6 hours. `retry_after_max` sets that limit. Lowering it means retrying earlier than the server asked. If you want to handle long waits yourself, use the hand-written version.

## Debugging

If 429s continue while the backoff works, the problem is the pace. Three symptoms and their causes:

- **429 on every attempt, same `Retry-After`.** Parallel requests to the same site keep filling the counter. Lower concurrency and apply the wait to every job that hits that site.
- **The loop ends without waiting.** The response may be `403` or `407`. Print the status code; those codes do not enter the loop.
- **A date-based `Retry-After` always comes out as 0.** Your machine's clock may be ahead. Sync the system clock.

## How we tested

We ran the code on December 1, 2026, on Windows 11 with Python 3.13.17, requests 2.34.2 and urllib3 2.6.3. We set up a small HTTP server on `127.0.0.1` that behaved like a proxy. It checked `user:pass` in the `Proxy-Authorization` header and logged every request with a timestamp. We used both examples from this post, changing only the `PROXY` address to the local server. The target was an `http://` URL, so no `CONNECT` tunnel was opened. We did not separately test an HTTPS target.

| Scenario | Hand-written code | urllib3 `Retry` |
|---|---|---|
| 3 × 429, `Retry-After: 2` | Waited 2.0-2.7 s, 200 on 4th request | Waited exactly 2 s, 200 on 4th request |
| 2 × 429, date 3 s ahead | Waited 3.2 and 3.4 s, 200 | Waited until the date, 200 |
| 3 × 429, no header | 0.1 / 0.4 / 2.6 s, 200 | 0 / 2.1 / 4.3 s, 200 |
| Always 403 | One request, returned 403 | One request, returned 403 |
| `Retry-After: 3600` or 2 hours ahead | One request, `RetryLater` | Not run (clipped to 60 s) |
| Always 429 | 5 requests, `RetryLater` | 5 requests, returned the last 429 |

Instead of waiting out the clipping in urllib3, we confirmed it by calling `parse_retry_after("3600")`: with `retry_after_max=60` it returned 60. When a `POST` request got a 429, urllib3 did not retry it.

## The bottom line

Read `Retry-After`; if it is missing, use exponential backoff with jitter, and cap both attempts and waits. Limit retries to `429` and `503` and to idempotent methods. Above all, slow down: switching IPs does not fix a pace problem. For high-volume work at the pace a site allows, a [Residential Proxy](https://proxynet.io/residential-proxy) spreads the traffic across addresses.

## Sources

- RFC 6585, section 4 "429 Too Many Requests": [rfc-editor.org](https://www.rfc-editor.org/rfc/rfc6585#section-4)
- RFC 9110, 10.2.3 "Retry-After": [rfc-editor.org](https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3)
- urllib3 `Retry` class reference: [urllib3.readthedocs.io](https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.Retry)
- "Exponential Backoff and Jitter", AWS Architecture Blog: [aws.amazon.com](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)

## Frequently asked questions

### Does the requests library retry 429 on its own?

No. The `HTTPAdapter` in `requests` comes with zero retries by default. A 429 response reaches you as it is, and calling `raise_for_status()` raises `HTTPError`. To retry, either build your own loop as in this post, or pass a urllib3 `Retry` object to an `HTTPAdapter` and mount it on the session.

### What should the base delay be for exponential backoff?

One second is a good start for most jobs. The ceilings grow to 1, 2, 4 and 8 seconds. Across five attempts, the four waits add up to 15 seconds at most. If the limit uses a one-minute window, raise the base to 2-5 seconds. Either way, cap a single wait; in the example the cap is 60 seconds.

### Should I add jitter to the Retry-After value?

Yes, a small margin helps. `Retry-After` gives the minimum wait, so do not come back sooner. If many clients that got the same response all return in that exact second, the limit fills up again. A random 0-1 second extra on top of the header value spreads the returns. urllib3 `Retry` does not add this extra to a `Retry-After` wait.

### Is a POST request resent after a 429?

It should not be resent automatically. RFC 9110 says non-idempotent methods should not be retried automatically. A `POST` sent twice can create a second order or record. That is why urllib3's `allowed_methods` leaves `POST` out by default. If needed, resend it by hand once you are sure the operation is safe to repeat.

### How many attempts are enough?

Four or five attempts cover most temporary limits. If 429s keep coming, the problem is the pace, not the wait: cut concurrent requests to the same site. More attempts only add load on the server. When attempts run out, put the URL back on a queue and continue the job later at a lower rate.

### Does switching the proxy IP help after a 429?

Usually not. If the counter is tied to an account, a session or an API key, the new IP lands on the same counter. Even when it is per IP, splitting the same pace across other addresses does not reduce the server's load. Slow down first and honor `Retry-After`. IP rotation is for spreading permitted traffic that already runs at a pace the site accepts.
