Skip to content
CleanProxies
Get Started

429 Too Many Requests: What It Means and How to Handle It in Python and Node

18 Min Read

A 429 Too Many Requests response means the server is rate limiting you: you sent more requests than it allows in a time window, so it refused this one and is asking you to slow down. The fix in code is to stop, wait as long as the Retry-After header says (or back off exponentially when there is no header), retry only safe requests, and pace yourself so the 429 stops coming back.

This guide shows how, with complete Python and Node scripts. If the IP you send from is shared with other users (a cloud range or an office network) and its rate allowance is used up by them, CleanProxies ISP proxies give you dedicated static US IPs of your own, as low as $0.75/IP a month at 10,000 IPs. All outputs shown were produced on 23 November 2026 against a local test server (included below) with Python 3.12.15, requests 2.34.2, urllib3 2.8.0, aiohttp 3.14.5 and Node 24.22.1.

Quick reference

# requests + urllib3 2.x: retry 429/5xx, honour Retry-After, back off when it is missing
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=5, status_forcelist=[429, 500, 502, 503, 504],
              allowed_methods=["GET", "HEAD", "OPTIONS"], backoff_factor=1,
              backoff_max=60, respect_retry_after_header=True, raise_on_status=False)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
SituationWhat to do
429 with Retry-After: 30Wait 30 seconds, then retry
429 with a very long Retry-After (hours)Stop and schedule the job for later; do not retry early
429 with Retry-After: Wed, 25 Nov 2026 10:00:00 GMTWait until that time (add a second; HTTP-dates are rounded to the second)
429 with no headerExponential backoff with jitter: about 1 s, 2 s, 4 s, 8 s, capped
429 on a POST or payment callDo not auto-retry unless the API documents an idempotency key
429 keeps coming backLower your rate or concurrency; retries alone will not fix it

What 429 Too Many Requests means

Status 429 is defined in RFC 6585: the user has sent too many requests in a given amount of time. The server may add a Retry-After header that says how long to wait. The rule behind it differs by site, and that decides the right fix:

Limit is counted perTypical exampleWhat helps
IP addressPublic pages, search forms, open endpointsA slower pace; an IP that is not shared with other users
Account or API keyREST APIs with plans and quotasSlower pace, a higher plan, batching; more IPs do not help
Token or sessionLogin flows, OAuth appsReuse sessions, cache tokens; more IPs do not help
EndpointExpensive search or export callsCache results, call the cheap endpoint instead

Many APIs also send RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (or X-RateLimit-* versions). When they are there, read them and slow down before you hit zero. The rate limiting glossary entry covers the common algorithms (fixed window, sliding window, token bucket).

A 429 is easy to confuse with nearby codes:

CodeMeaningRetry?
429 Too Many RequestsYou are over the site's rate limitYes, after Retry-After or a backoff
503 Service UnavailableThe server is overloaded or down; may also carry Retry-AfterYes, with backoff
403 ForbiddenYou are not allowed to see this resourceNo; retrying changes nothing
407 Proxy Authentication RequiredYour proxy got missing or wrong credentialsNo; fix the proxy username and password

The 407 row matters when you use a proxy: it comes from the proxy, not the site, and no amount of waiting fixes it. Our guide to 407 Proxy Authentication Required walks through that one, and the wider list of proxy errors covers timeouts and SSL failures.

A local server that returns 429

To see the retry logic work without hammering anyone's site, run this small server. It lets each client make 3 requests per 10-second window, then answers 429 with Retry-After in seconds (or as an HTTP-date on /date).

# Local test server: each client gets 3 requests per 10-second window, then 429 + Retry-After.
# /date answers with an HTTP-date Retry-After instead of seconds.
import threading
import time
from email.utils import formatdate
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LIMIT, WINDOW = 3, 10
hits = {}
lock = threading.Lock()

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        now = time.time()
        client = self.client_address[0]
        with lock:
            start, count = hits.get(client, (now, 0))
            if now - start >= WINDOW:
                start, count = now, 0
            count += 1
            hits[client] = (start, count)
        if count > LIMIT:
            wait = int(start + WINDOW - now) + 1
            self.send_response(429)
            if self.path.startswith("/date"):
                self.send_header("Retry-After", formatdate(now + wait, usegmt=True))
            else:
                self.send_header("Retry-After", str(wait))
            self.end_headers()
            self.wfile.write(b"Too Many Requests\n")
            return
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"ok\n")

    def log_message(self, *args):
        pass

ThreadingHTTPServer(("127.0.0.1", 8429), Handler).serve_forever()

Start it with python3 server429.py in one terminal and run the clients below in another. Every client takes a URL as its first argument, so you can point it at a real endpoint later.

Parse Retry-After in Python (seconds or HTTP-date)

Retry-After comes in two forms: a number of seconds (Retry-After: 120) or an HTTP-date (Retry-After: Wed, 25 Nov 2026 10:00:00 GMT). Handle both. When the wait is longer than your job can block (here 120 seconds), stop and come back later instead of retrying early. Fall back to exponential backoff with jitter when the header is missing, and do not sleep after the last attempt.

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

import requests

MAX_WAIT = 120  # longest wait we accept; a longer Retry-After means: stop and try later


def parse_retry_after(value):
    """Return seconds to wait from a Retry-After header, or None if missing or invalid."""
    if not value:
        return None
    value = value.strip()
    if value.isdigit():
        return int(value)
    try:
        when = parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    if when is None:
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    seconds = (when - datetime.now(timezone.utc)).total_seconds()
    return max(seconds, 0) + 1  # +1s: HTTP-dates are rounded to the second


def get_politely(session, url, max_tries=5, **kwargs):
    for attempt in range(max_tries):
        resp = session.get(url, timeout=30, **kwargs)
        if resp.status_code != 429:
            return resp
        if attempt == max_tries - 1:
            break
        wait = parse_retry_after(resp.headers.get("Retry-After"))
        if wait is None:
            wait = min(2 ** attempt, 60) + random.uniform(0, 1)  # no header: exponential backoff + jitter
        elif wait > MAX_WAIT:
            raise RuntimeError(f"server asked us to wait {wait:.0f}s: stop and come back later")
        print(f"429 on try {attempt + 1}, waiting {wait:.1f}s")
        time.sleep(wait)
    resp.raise_for_status()


if __name__ == "__main__":
    import sys

    url = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8429/"
    with requests.Session() as s:
        for i in range(5):
            r = get_politely(s, url)
            print(i + 1, r.status_code, r.text.strip())

Output against the local server (python3 retry_after.py), ran on 23 Nov 2026:

1 200 ok
2 200 ok
3 200 ok
429 on try 1, waiting 10.0s
4 200 ok
5 200 ok

And with the HTTP-date form (python3 retry_after.py http://127.0.0.1:8429/date):

1 200 ok
2 200 ok
3 200 ok
429 on try 1, waiting 10.7s
4 200 ok
5 200 ok

The extra second in the date branch is there for a reason. Our first version waited exactly until the date, woke up a fraction of a second early (the header has no sub-second precision) and took a second 429. Adding one second fixed it.

Python requests retry with urllib3 Retry

If you use requests, you do not have to write the loop yourself. urllib3's Retry class retries the status codes you list, reads Retry-After on 413, 429 and 503 answers, and uses exponential backoff otherwise. Its backoff starts with an immediate first retry and has no jitter unless you set backoff_jitter. This version needs urllib3 2.0 or newer (backoff_max and backoff_jitter as arguments arrived in 2.0; allowed_methods replaced method_whitelist in 1.26). Check with python3 -c "import urllib3; print(urllib3.__version__)".

import sys
import time

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(
    total=5,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["GET", "HEAD", "OPTIONS"],  # only retry idempotent requests
    backoff_factor=1,          # 0s, 2s, 4s, 8s ... (+ jitter) when there is no Retry-After
    backoff_max=60,
    backoff_jitter=1.0,        # adds up to 1s of random delay to each backoff
    respect_retry_after_header=True,
    raise_on_status=False,     # hand back the last 429 instead of raising
)

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

# Proxy: requests reads HTTP_PROXY / HTTPS_PROXY from the environment by itself, e.g.
# export HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PROXY_PORT"

url = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8429/"
t0 = time.monotonic()
for i in range(5):
    r = session.get(url, timeout=30)
    print(f"{time.monotonic() - t0:5.1f}s  {i + 1} {r.status_code} {r.text.strip()}")

Output (python3 requests_retry.py), ran on 23 Nov 2026. Request 4 hit the limit; the adapter read Retry-After: 10, slept and retried on its own:

  0.0s  1 200 ok
  0.0s  2 200 ok
  0.0s  3 200 ok
 10.0s  4 200 ok
 10.0s  5 200 ok

Three settings are worth a second look:

  • allowed_methods: keep POST out unless the API supports idempotency keys. A retried POST can create a second order or a second message.

  • raise_on_status=False: when the retries run out you get the last 429 back and can log it, instead of a MaxRetryError deep in a stack trace.

  • status_forcelist: 429 plus the 5xx codes that are usually temporary. Never add 401, 403 or 407.

  • backoff_max caps the computed backoff, not the Retry-After value: urllib3 sleeps as long as the server asks. If a long wait would hurt your job, use the hand-written loop above.

The same code works through a proxy with no change, because requests reads HTTP_PROXY and HTTPS_PROXY from the environment. The Python Requests proxy page has the other ways to set one. We ran retry_after.py with HTTP_PROXY=http://USERNAME:[email protected]:8080 through a small lab proxy on the same machine (it logs each request it forwards). The proxy logged 6 forwarded requests, the 5 in the script plus the one retry, and the client output was the same as above:

proxy forwarded http://127.0.0.1:8429/
proxy forwarded http://127.0.0.1:8429/
proxy forwarded http://127.0.0.1:8429/
proxy forwarded http://127.0.0.1:8429/
proxy forwarded http://127.0.0.1:8429/
proxy forwarded http://127.0.0.1:8429/

Then we ran requests_retry.py with wrong credentials (HTTP_PROXY=http://bad:[email protected]:8080). The proxy answered 407 to each of the 5 requests and logged exactly 5 attempts, so Retry did not retry any of them, which is what you want:

proxy 407 for http://127.0.0.1:8429/
proxy 407 for http://127.0.0.1:8429/
proxy 407 for http://127.0.0.1:8429/
proxy 407 for http://127.0.0.1:8429/
proxy 407 for http://127.0.0.1:8429/
  0.0s  1 407
  0.0s  2 407
  0.0s  3 407
  0.0s  4 407
  0.0s  5 407

For your own proxy, set HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PROXY_PORT" (URL-encode special characters in the password). If you repeat this lab, restart the test server between runs so each starts with a fresh window, and make sure NO_PROXY does not list 127.0.0.1 or localhost, or the client skips the proxy. For httpx, the Python httpx proxy page shows the client setup; the retry logic above carries over.

Async Python: aiohttp with a concurrency cap

Async code hits 429 faster, because it is easy to fire 500 requests at once. Two rules keep it polite: cap how many requests are in flight with a semaphore, and sleep outside the semaphore so a waiting task does not block a slot.

import asyncio
import random
import sys
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

import aiohttp

CONCURRENCY = 2      # requests in flight at once
MAX_TRIES = 5


MAX_WAIT = 120


def retry_after_seconds(value, attempt):
    """Seconds or HTTP-date from Retry-After; exponential backoff with jitter if missing."""
    if value:
        value = value.strip()
        if value.isdigit():
            return int(value)
        try:
            when = parsedate_to_datetime(value)
            if when.tzinfo is None:
                when = when.replace(tzinfo=timezone.utc)
            return max((when - datetime.now(timezone.utc)).total_seconds(), 0) + 1
        except (TypeError, ValueError):
            pass
    return min(2 ** attempt, 60) + random.uniform(0, 1)


async def fetch(session, sem, url, n, t0):
    for attempt in range(MAX_TRIES):
        async with sem:
            async with session.get(url) as resp:
                body = await resp.text()
                if resp.status != 429:
                    print(f"{time.monotonic() - t0:5.1f}s  #{n} {resp.status} {body.strip()}")
                    return resp.status
                wait = retry_after_seconds(resp.headers.get("Retry-After"), attempt)
        if attempt == MAX_TRIES - 1 or wait > MAX_WAIT:
            break
        print(f"{time.monotonic() - t0:5.1f}s  #{n} 429, retry in {wait:.0f}s")
        await asyncio.sleep(wait)  # sleep outside the semaphore so others can use the slot
    print(f"#{n} gave up on 429 (wait {wait:.0f}s)")
    return 429


async def main(url, count):
    sem = asyncio.Semaphore(CONCURRENCY)
    timeout = aiohttp.ClientTimeout(total=300)
    # trust_env=True makes aiohttp use HTTP_PROXY / HTTPS_PROXY from the environment
    async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
        t0 = time.monotonic()
        await asyncio.gather(*(fetch(session, sem, url, n, t0) for n in range(1, count + 1)))


if __name__ == "__main__":
    url = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8429/"
    asyncio.run(main(url, 6))

Output (python3 aiohttp_paced.py), ran on 23 Nov 2026. Three of six requests went over the limit, waited the 10 seconds the server asked for, and succeeded:

  0.0s  #1 200 ok
  0.0s  #2 200 ok
  0.0s  #3 200 ok
  0.0s  #4 429, retry in 10s
  0.0s  #5 429, retry in 10s
  0.0s  #6 429, retry in 10s
 10.0s  #4 200 ok
 10.0s  #5 200 ok
 10.0s  #6 200 ok

Against /date (HTTP-date form) the same three requests waited and succeeded at 10.3 s.

Node.js: fetch with Retry-After

Node 18 and newer ship fetch, so no package is needed. The logic is the same: read retry-after, accept seconds or a date, stop when the wait is too long, back off when the header is missing, and cancel the body of the 429 response so the connection is freed.

// Node 18+ native fetch. For a proxy on Node 24: NODE_USE_ENV_PROXY=1 HTTP_PROXY=... HTTPS_PROXY=...
const url = process.argv[2] ?? "http://127.0.0.1:8429/";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const MAX_WAIT_MS = 120_000; // a longer Retry-After means: stop and try later

function retryAfterMs(value, attempt) {
  if (value) {
    const secs = Number(value);
    if (Number.isFinite(secs) && secs >= 0) return secs * 1000;
    const date = Date.parse(value); // HTTP-date form, rounded to the second: add 1 s
    if (!Number.isNaN(date)) return Math.max(date - Date.now(), 0) + 1000;
  }
  return Math.min(2 ** attempt, 60) * 1000 + Math.random() * 1000;
}

async function getPolitely(target, maxTries = 5) {
  for (let attempt = 0; attempt < maxTries; attempt++) {
    const res = await fetch(target, { signal: AbortSignal.timeout(30_000) });
    if (res.status !== 429) return res;
    const wait = retryAfterMs(res.headers.get("retry-after"), attempt);
    await res.body?.cancel();
    if (attempt === maxTries - 1) break;
    if (wait > MAX_WAIT_MS) throw new Error(`server asked us to wait ${wait / 1000}s: stop and try later`);
    console.log(`429 on try ${attempt + 1}, waiting ${(wait / 1000).toFixed(1)}s`);
    await sleep(wait);
  }
  throw new Error(`still 429 after ${maxTries} tries: ${target}`);
}

for (let i = 1; i <= 5; i++) {
  const res = await getPolitely(url);
  console.log(i, res.status, (await res.text()).trim());
}

Output (node fetch_retry.mjs), ran on 23 Nov 2026:

1 200 ok
2 200 ok
3 200 ok
429 on try 1, waiting 10.0s
4 200 ok
5 200 ok

On Node 24, built-in fetch can use a proxy from the environment when you set NODE_USE_ENV_PROXY=1 with HTTP_PROXY / HTTPS_PROXY. We ran the script that way on Node 24.22.1 through the lab proxy. The proxy log shows that Node sent every request through a CONNECT tunnel, even though the URL was plain http://: 7 tunnels for the 6 requests (5 answers plus the one 429), as undici opened one extra connection. The client output was the same as above:

proxy tunnel to 127.0.0.1:8429
1 200 ok
proxy tunnel to 127.0.0.1:8429
2 200 ok
proxy tunnel to 127.0.0.1:8429
3 200 ok
proxy tunnel to 127.0.0.1:8429
429 on try 1, waiting 10.0s
proxy tunnel to 127.0.0.1:8429
proxy tunnel to 127.0.0.1:8429
4 200 ok
proxy tunnel to 127.0.0.1:8429
5 200 ok

An earlier version of our lab proxy did not support CONNECT, and Node failed with Proxy response (501) !== 200 when HTTP Tunneling: if you see that error, your proxy refuses tunnels. The Node.js proxy page covers undici's ProxyAgent and other clients.

Pace yourself: a token bucket

Retries recover from a 429. Pacing prevents the next one. A token bucket lets you send short bursts but holds the long-run rate to a number you choose, which is how many servers count you anyway.

import sys
import threading
import time
import urllib.error
import urllib.request


class TokenBucket:
    """Allow `rate` requests per second on average, with bursts up to `capacity`."""

    def __init__(self, rate, capacity):
        self.rate, self.capacity = rate, capacity
        self.tokens, self.updated = capacity, time.monotonic()
        self.lock = threading.Lock()

    def acquire(self):
        while True:
            with self.lock:
                now = time.monotonic()
                self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
                self.updated = now
                if self.tokens >= 1:
                    self.tokens -= 1
                    return
                wait = (1 - self.tokens) / self.rate
            time.sleep(wait)


def status_of(url):
    try:
        with urllib.request.urlopen(url, timeout=30) as resp:
            return resp.status
    except urllib.error.HTTPError as e:
        return e.code


if __name__ == "__main__":
    url = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8429/"
    bucket = TokenBucket(rate=0.25, capacity=1)  # one request every 4 s on average
    t0 = time.monotonic()
    for i in range(8):
        bucket.acquire()
        print(f"{time.monotonic() - t0:5.1f}s  request {i + 1}: {status_of(url)}")

Output (python3 token_bucket.py), ran on 23 Nov 2026 against the same test server. One request every 4 seconds keeps each 10-second window at 3 requests or fewer, so all 8 requests got a 200 and none needed a retry:

  0.0s  request 1: 200
  4.0s  request 2: 200
  8.0s  request 3: 200
 12.0s  request 4: 200
 16.0s  request 5: 200
 20.0s  request 6: 200
 24.0s  request 7: 200
 28.0s  request 8: 200

A burst size above 1 is fine for servers that count with a token bucket too, but against a fixed window like this one a burst at the end of one window plus a burst at the start of the next can still trip the limit. Keep the burst small when you do not know how the server counts.

Set the rate from the site's documentation or its RateLimit-* headers when it has them. When it does not, start low (one request every few seconds per host), watch for 429s, and raise slowly. If the site's robots.txt has a Crawl-delay, treat it as your floor.

How to fix 429 Too Many Requests: a checklist

CauseFix
Too many requests per secondToken bucket or a fixed delay per host
Too many requests at onceLower the semaphore or thread pool size
Retrying instantly in a loopHonour Retry-After; exponential backoff with jitter
All workers retry at the same momentAdd random jitter to every wait
Daily or monthly API quota used upWait for the reset (RateLimit-Reset) or move to a higher plan
Same data fetched again and againCache responses; use ETag / If-None-Match where offered
Many small callsUse the API's batch or bulk endpoint
Shared office or cloud IP already busyA dedicated IP of your own (below), still paced

When your IP is the problem

Some limits are counted per IP address, and sometimes the 429 is not about your own pace at all: you share the IP with other people. Cloud server ranges, busy office networks and carrier NAT can put many users behind one address, so the site's per-IP allowance is used up before your job starts. Retrying harder makes that worse; a clean IP of your own fixes it. Keep the same rules on that IP:

  • Pace each worker with a token bucket and honour Retry-After on every request.

  • Use the site's API and respect its terms where it has them; account, key and token limits do not change with your IP.

  • Read only public data, stay within the rate the site allows, and leave a site alone when it asks you to stop.

For steady jobs, dedicated static IPs are the simplest setup: each worker keeps the same IP all month and nobody else sends traffic from it, so the rate you plan is the rate the site sees. CleanProxies static ISP IPs are 100% dedicated, never shared, on Tier-1 carrier ASNs, with unlimited bandwidth and threads, as low as $0.75/IP a month at 10,000 IPs. For jobs that need many locations, rotating residential proxies cost as low as $0.63/GB at 10,000 GB, with sticky sessions from 5 minutes to 24 hours. To use a list of IPs in your code, see how to rotate proxies in Python, and check any IP with the free proxy checker before you put it to work.

For 100 IPs or more, the price per IP drops with volume, down to $0.75/IP at 10,000 IPs; every plan and tier is on the pricing page.

Frequently Asked Questions

It means the server is rate limiting you: you sent more requests than it allows in a time window. It is defined in RFC 6585. The server may send a Retry-After header that tells you how many seconds to wait, or until what time, before you try again.

As long as the Retry-After header says. It is either a number of seconds or an HTTP-date. If there is no header, use exponential backoff with jitter (about 1, 2, 4, 8 seconds, capped) and lower your request rate so the 429 does not come back.

Not by default. Mount an HTTPAdapter with a urllib3 Retry object that lists 429 in status_forcelist and keeps respect_retry_after_header=True. With urllib3 2.x you can also set backoff_max. Limit allowed_methods to safe methods such as GET so a POST is not sent twice.

Usually it is the client's pace: too many requests per second, too many in parallel, or retries in a tight loop. Sometimes the limit is shared, for example a cloud or office IP that other users also send traffic from. Slowing down and honouring Retry-After fixes most cases.

Only when the real cause is a shared IP: a cloud range or office network whose per-IP allowance other users have already used. A dedicated IP of your own fixes that, as long as you keep a polite pace and honour Retry-After. Limits counted per account, API key or token do not change with your IP. If the error comes from the proxy itself it is a 407 (missing or wrong proxy credentials), not a 429.

429 says you personally sent too many requests. 503 says the server is overloaded or down for everyone. Both can carry Retry-After and both are safe to retry with backoff; 403 and 407 are not.

Team CleanProxies
Proxy Infrastructure Team
Tags
  • 429
  • rate limiting
  • python
  • nodejs

Related Articles