Retry-After header Python retry
Copy a Retry-After header Python retry for HTTP 429 responses with bounded backoff and jitter.
Published here · 3 sources · Resume reading
I use this Retry-After header Python retry so you can wait. RFC 6585 defines 429 for rate limiting, and RFC 9110 permits Retry-After as seconds or an HTTP date [1] [2].
Copy a Retry-After header Python retry
This standard-library example honors numeric Retry-After; when the header is absent or is a date, it uses bounded exponential backoff with jitter. Add date parsing if the API you call sends HTTP dates.
import random
import time
import urllib.request
from urllib.error import HTTPError
def get_with_429_retry(url, attempts=5, sleep=time.sleep):
for attempt in range(attempts):
try:
return urllib.request.urlopen(url)
except HTTPError as error:
if error.code != 429 or attempt == attempts - 1:
raise
retry_after = error.headers.get("Retry-After")
if retry_after and retry_after.isdigit():
delay = float(retry_after)
else:
delay = min(60.0, 2.0 ** attempt) + random.uniform(0.0, 1.0)
sleep(delay)You should see the request return after the server's delay or a later backoff attempt.
Handle 429 Too Many Requests
cd world2
python3 token_bucket.pyThe level illustrates why retrying immediately keeps a rate limit exhausted [3]. Read Claude Code context commands and agent tool deny rules, or browse Dev explainers.
Real APIs define their own retry policy and headers. Use that API's documentation before choosing attempts, a maximum delay, or which requests are safe to repeat.
Send this to the friend debugging repeated 429 responses.
Keep this guide
Filed under Dev explainers, Cost and context
Questions about this guide
What does 429 Too Many Requests mean?
It means the server received too many requests in a given amount of time.
What can a Retry-After header contain?
It can contain delay seconds or an HTTP date. This compact example handles numeric delay seconds.
Sources
- RFC 6585 section 4: 429 Too Many Requestsrfc-editor.org
- RFC 9110 section 10.2.3: Retry-Afterrfc-editor.org
- ALGO ARCADE token-bucket examplegithub.com