Sub topic 7
Respecting the Retry-After header
This chapter assumes you can read HTTP status codes and headers, write Python functions with exceptions, and have seen the retry loop with exponential backoff and jitter from earlier chapters. Here you will learn what Retry-After tells you, how to parse it safely, and how to combine it with your own backoff.
What the header means
When a server rejects a request because of load or a rate limit, it often knows when a retry has a chance of working. The Retry-After response header carries that information. It usually appears on 429 Too Many Requests and 503 Service Unavailable, and sometimes on other 5xx responses.
Your backoff schedule is a guess. Retry-After is the server's own estimate. If the server says "wait 20 seconds" and your schedule says "wait 1 second", retrying after 1 second is wasted work. The request will fail again, and it may count against your rate limit.
The header has two legal forms.
| Form | Example | Meaning |
|---|---|---|
| Delay in seconds | `Retry-After: 7` | Wait 7 seconds from now |
| HTTP date | `Retry-After: Sat, 28 Nov 2026 06:30:12 GMT` | Do not retry before this moment |
Some providers also send non-standard headers, such as a millisecond variant (retry-after-ms) or x-ratelimit-reset-* headers that say when a request or token quota refills. Check your provider's documentation. The parsing and decision logic below applies the same way. Treat every such value as a hint, not a guarantee.
Parsing the header safely
The header is data from the network, so parse it defensively. Your parser should handle both forms, return None for anything it cannot read, never return a negative number, and reject nan and inf, which Python's float() accepts.
The earlier chapter's version handled only the seconds form. This version also handles dates, and it takes now as a parameter so you can test it without waiting.
import math
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
def parse_retry_after(value, now=None):
"""Return the wait in seconds, or None if the header is missing or unreadable."""
if value is None:
return None
value = value.strip()
try:
seconds = float(value)
except ValueError:
try:
when = parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc)
now = now or datetime.now(timezone.utc)
seconds = (when - now).total_seconds()
if not math.isfinite(seconds):
return None
return max(0.0, seconds)
fixed_now = datetime(2026, 11, 28, 6, 30, 0, tzinfo=timezone.utc)
for header in ("7", "Sat, 28 Nov 2026 06:30:12 GMT", "-3", "soon", "nan", None):
print(repr(header), "->", parse_retry_after(header, fixed_now))The output is:
'7' -> 7.0
'Sat, 28 Nov 2026 06:30:12 GMT' -> 12.0
'-3' -> 0.0
'soon' -> None
'nan' -> None
None -> NoneThe date form depends on your clock. If your machine's clock is a minute fast, a date-based header will make you wait a minute too short. If it is a minute slow, you will wait a minute too long. The seconds form does not have this problem, so prefer it when both are available.
Combining the header with backoff
Treat the header as a lower bound on the wait. Your own jittered backoff still matters, because the header can be absent, and because it can be very short (Retry-After: 0 or 1) when many clients are told the same thing.
The rule is:
- Compute the jittered backoff delay as before.
- If the server gave a
Retry-After, use the larger of the two. - Add a small random amount on top, so clients that received the same header do not all return in the same instant.
- If the final wait is longer than you are willing to wait, stop and raise the error.
Step 4 is the important change from the earlier sketch, which clamped the header to cap. Clamping means you retry before the server said you could. That request will probably get another 429 and spend one of your limited attempts. When the server asks for a wait you cannot afford, surfacing the failure is the more honest choice.
import random
def plan_wait(attempt, retry_after, remaining, base=0.5, cap=30.0, max_wait=60.0):
"""Return seconds to sleep before the next attempt, or None to give up.
attempt: 1 for the first failed attempt, 2 for the second, and so on
retry_after: parsed header value in seconds, or None
remaining: seconds left before the overall deadline
"""
backoff = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
if retry_after is None:
delay = backoff
else:
if retry_after > max_wait:
return None # the server wants longer than we will wait
delay = max(backoff, retry_after)
delay += random.uniform(0, 0.1 * delay) # spread out synchronized clients
if delay > remaining:
return None # sleeping would blow the deadline
return delay
print(plan_wait(1, None, remaining=100) is not None) # True
print(plan_wait(2, 20.0, remaining=100) >= 20.0) # True
print(plan_wait(2, 20.0, remaining=10)) # None
print(plan_wait(2, 600.0, remaining=1000)) # NoneEach of the four print calls shows one branch: no header, a header that is honored, a deadline that is too close, and a header that is too long.
Using it in a retry loop
Here is plan_wait inside a loop built on httpx. It adds a deadline measured with a monotonic clock, so the whole operation, including sleeps, has a hard limit.
import time
import httpx
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
def post_with_retry_after(client, url, payload, max_attempts=5, deadline_s=90.0):
start = time.monotonic()
for attempt in range(1, max_attempts + 1):
resp = None
try:
resp = client.post(url, json=payload, timeout=30.0)
except httpx.TransportError:
if attempt == max_attempts:
raise
if resp is not None:
if resp.status_code < 400:
return resp
if resp.status_code not in RETRYABLE_STATUS or attempt == max_attempts:
resp.raise_for_status()
retry_after = None
if resp is not None:
retry_after = parse_retry_after(resp.headers.get("retry-after"))
remaining = deadline_s - (time.monotonic() - start)
delay = plan_wait(attempt, retry_after, remaining)
if delay is None:
if resp is not None:
resp.raise_for_status()
raise TimeoutError("retry deadline exceeded")
time.sleep(delay)This code reuses parse_retry_after and plan_wait from the earlier blocks, so put all three in one module. httpx header lookups ignore case, so "retry-after" matches whichever spelling the server sends. In async code, replace time.sleep with await asyncio.sleep. A blocking sleep would freeze every other task on the event loop.
Edge cases and failure modes
- A longer wait does not guarantee success. Token-per-minute limits can need more than the header suggests, especially if other processes share your key. Keep your normal attempt limit, so a wrong hint cannot cause an endless loop.
- A huge or hostile value. A server, proxy, or bug could send
Retry-After: 86400. Themax_waitcheck turns that into an error instead of a day-long sleep. Retry-After: 0. This means "retry now", but a tight loop of immediate retries is still unsafe. The jittered backoff inmax(backoff, retry_after)keeps a minimum gap.- Header on a non-retryable status. Do not retry a
400or401just because it carriesRetry-After. Classify the status first, then use the header only to time the retry. - Several workers, one key. Each worker sees the same header and sleeps the same time. The jitter added in
plan_waitis what keeps them from stampeding back together. Sharing a client-side limiter across workers is a stronger fix, covered in a later chapter. - SDKs may already do this. Many provider SDKs read
Retry-Afterthemselves and wait before retrying. If you wrap an SDK call in your own loop, you can multiply waits and attempts. Check what the SDK does before adding your own layer.
Exercise
Exercise
Your retry loop uses backoff delays of up to 2 seconds. A 429 response arrives with Retry-After: 15, you have 10 seconds left before your overall deadline, and your jitter draw is 1.3 seconds. What does plan_wait return, and why? What would it return with 40 seconds left?
Show answer
With 10 seconds left it returns None. The delay is max(1.3, 15) = 15 seconds plus up to 10% jitter, which is more than the 10 seconds remaining, so the function gives up and the caller raises the error. Retrying earlier would break the server's instruction and probably cause another 429. With 40 seconds left, 15 is under the 60 second max_wait and under the remaining time, so it returns a delay between 15 and 16.5 seconds.