Code: the simulated server
class SimulatedServer:
def __init__(self, codes):
self.codes = list(codes)
self.calls = 0
def get(self):
self.calls += 1
return self.codes.pop(0) if self.codes else 200After this lesson, you can retry a failed download, stop after a set number of attempts, and space all attempts to meet a provider’s rate limit.
A request that fails for a temporary reason, status 429 for too many requests or 500 to 504 for a server problem, gets another attempt after a wait that doubles each time, while a status such as 404 stops at once, because the address is wrong. Against a server that answers 503, 503 and 200, get_with_retries succeeds on attempt 3 after waits of 0.05 and 0.10 seconds.
\[ w_k = b \times 2^{k-1} \]
Here \(w_k\) is the wait in seconds after failed attempt \(k\) and \(b\) the first wait. Waits that grow this way are called backoff.
The simulated server returns made-up status codes from a list, one per request, and 200 once the list is empty, so nothing goes online. get_with_retries raises a RuntimeError when the status is not worth a retry or the attempts run out, and before is a function called before every attempt, by default one that does nothing. Clients that retry at the same moment often add a small random delay, called jitter.
The following box defines the retry loop and runs it on a busy server and on a wrong address.
import time
RETRYABLE = {429, 500, 502, 503, 504}
def get_with_retries(server, max_attempts=4, base_wait=0.05, before=lambda: None):
for attempt in range(1, max_attempts + 1):
before()
status = server.get()
if status == 200:
return status, attempt
if attempt == max_attempts or status not in RETRYABLE:
raise RuntimeError(f"status {status} on attempt {attempt}")
time.sleep(base_wait * 2 ** (attempt - 1))
print(get_with_retries(SimulatedServer([503, 503, 200])))
try:
get_with_retries(SimulatedServer([404, 200]))
except RuntimeError as error:
print(error)(200, 3)
status 404 on attempt 1
A provider that allows five requests per second needs at least 1 / 5 = 0.2 seconds between the starts of two requests, and RateLimiter.wait() sleeps for whatever part of that interval is still left since the last start. Six requests then take at least one second, and passing limiter.wait as before makes the retries count toward the same limit.
time.monotonic() reads a clock in seconds that never moves backward, and max(0, ...) turns a negative remainder into no wait. The limiter spaces the requests of one script, and scripts that share a quota also need to share the timing.
The following box times six requests and repeats the retries with the limiter.
class RateLimiter:
def __init__(self, per_second):
self.interval = 1 / per_second
self.last = -float("inf")
def wait(self):
time.sleep(max(0, self.interval - (time.monotonic() - self.last)))
self.last = time.monotonic()
limiter = RateLimiter(per_second=5)
start = time.monotonic()
for _ in range(6):
limiter.wait()
print(time.monotonic() - start >= 1.0)
print(get_with_retries(SimulatedServer([503, 503, 200]), base_wait=0.01, before=limiter.wait))True
(200, 3)
HTTPAdapter(max_retries=Retry(...)) from requests and urllib3 gives a session a built-in retry policy, so session.get(url, timeout=30) retries the listed status codes by itself. total=4 allows four retries after the first request, and backoff_factor=0.5 waits 0, 1, 2 and 4 seconds between them.
respect_retry_after_header=True follows a server’s Retry-After header, its instruction on how long to wait, which a 429 often carries. .mount("https://", ...) attaches the adapter to all HTTPS addresses of the session. The adapter retries inside session.get, so a limiter called before session.get cannot space those retries.
The following box builds the session offline and prints its policy.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=Retry(total=4, backoff_factor=0.5, status_forcelist=sorted(RETRYABLE), allowed_methods={"GET"}, respect_retry_after_header=True)))
print(session.adapters["https://"].max_retries)Retry(total=4, connect=None, read=None, redirect=None, status=None)
Run get_with_retries with three attempts on a server that answers 503 four times and then 200. You should see the error status 503 on attempt 3.