Retries, Backoff and Pagination
Two facts about real APIs shape every client that talks to them. First, requests fail for temporary reasons: rate limits (429), overloaded or restarting servers (502, 503, 504), dropped connections. Second, list endpoints never return everything at once: they return a page and a way to ask for the next one. This lesson adds both to the transport-based client from Calling REST APIs, again against an in-process fake so every run is identical.
What to retry
| Situation | Retry? |
|---|---|
| connection refused / reset, timeout | yes, if the request is safe to repeat |
| 429 Too Many Requests | yes, after the Retry-After delay if the server sends one |
| 500, 502, 503, 504 | yes, if the request is safe to repeat |
| 400, 401, 403, 404, 409, 422 | no: the same request will fail the same way |
GET, HEAD, PUT, DELETE |
idempotent by definition: safe to repeat |
POST, PATCH |
only if the API supports an idempotency key header, so a repeat is recognised |
Exponential backoff with jitter
Waiting base * 2**attempt seconds between attempts gives a struggling server room. Jitter (a random part of the
delay) stops a thousand clients that failed at the same moment from retrying at the same moment too. The "full
jitter" strategy picks a random delay between 0 and the exponential cap. The example injects sleep and the random
generator, so it can record the delays instead of really waiting, and a seed makes them repeatable:
import random
class TransientError(Exception):
"""A connection-level failure: no HTTP response at all."""
RETRY_STATUSES = {429, 500, 502, 503, 504}
IDEMPOTENT = {"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}
def with_retries(transport, *, attempts=5, base=0.5, cap=30.0, sleep, rng):
"""Wrap a transport (method, path) -> (status, headers, body) with retries."""
def call(method, path):
for attempt in range(1, attempts + 1):
try:
status, headers, body = transport(method, path)
except TransientError as e:
status, headers, body, reason = None, {}, None, f"error: {e}"
else:
reason = f"HTTP {status}"
if status not in RETRY_STATUSES:
return status, body # success, or an error retrying will not fix
if method not in IDEMPOTENT or attempt == attempts:
print(f" attempt {attempt}: {reason}, giving up")
return status, body
if "Retry-After" in headers:
delay = float(headers["Retry-After"]) # the server knows best
else:
delay = rng.uniform(0, min(cap, base * 2 ** (attempt - 1))) # full jitter
print(f" attempt {attempt}: {reason}, retrying in {delay:.2f}s")
sleep(delay)
return call
def scripted(outcomes):
"""A fake transport that returns the scripted outcomes in order."""
it = iter(outcomes)
def transport(method, path):
o = next(it)
if isinstance(o, Exception):
raise o
return o
return transport
waited = []
rng = random.Random(42)
for title, method, outcomes in [
("flaky GET", "GET", [TransientError("connection reset"), (503, {}, None), (200, {}, "ok")]),
("rate limited", "GET", [(429, {"Retry-After": "2"}, None), (200, {}, "ok")]),
("not found", "GET", [(404, {}, None)]),
("POST without idempotency key", "POST", [(503, {}, None), (201, {}, "created")]),
("down for good", "GET", [(503, {}, None)] * 5),
]:
print(title)
call = with_retries(scripted(outcomes), sleep=waited.append, rng=rng)
print(" ->", call(method, "/v1/deployments"))
print("total time spent waiting:", f"{sum(waited):.2f}s")flaky GET
attempt 1: error: connection reset, retrying in 0.32s
attempt 2: HTTP 503, retrying in 0.03s
-> (200, 'ok')
rate limited
attempt 1: HTTP 429, retrying in 2.00s
-> (200, 'ok')
not found
-> (404, None)
POST without idempotency key
attempt 1: HTTP 503, giving up
-> (503, None)
down for good
attempt 1: HTTP 503, retrying in 0.14s
attempt 2: HTTP 503, retrying in 0.22s
attempt 3: HTTP 503, retrying in 1.47s
attempt 4: HTTP 503, retrying in 2.71s
attempt 5: HTTP 503, giving up
-> (503, None)
total time spent waiting: 6.89s
- The 404 returned at once, and the POST was not repeated: a second POST could have created a second deployment.
APIs that support retries for creations accept an
Idempotency-Keyheader and return the original result for a repeat. Retry-Afteroverrode the computed delay. Servers that rate-limit tell you how long to wait; respect it.- Give up after a bounded number of attempts (or a total deadline) and surface the last error. Retrying forever turns an outage into a hung job.
In production, libraries do this for you: urllib3.util.Retry (mounted on a requests session with an
HTTPAdapter), tenacity for any function, and the cloud SDKs (boto3, the Google and Azure clients) retry their own
calls with backoff by default.
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
retry = Retry(total=5, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504],
allowed_methods={"GET", "HEAD", "PUT", "DELETE"}, respect_retry_after_header=True)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
resp = session.get("https://api.example.com/v1/deployments", timeout=10)Pagination
APIs page their lists in one of three ways:
| Style | The request | Where the next page is |
|---|---|---|
| page number / offset | ?page=3&per_page=50 |
you compute it; stop on an empty or short page |
| cursor (token) | ?cursor=abc123 |
a next_cursor / nextPageToken field in the body; stop when it is missing |
Link header |
follow the URL | Link: <https://…?page=3>; rel="next" (GitHub, many REST APIs) |
Cursors are the most robust: offsets skip or repeat items when the list changes while you read it. Whatever the style, hide it in a generator so the rest of the script just iterates over items:
import json
import re
# ---- a fake API with 7 repositories, 3 per page, in two pagination styles ----
REPOS = [{"name": f"repo-{i}", "archived": i in (2, 5)} for i in range(1, 8)]
def fake_cursor_api(path, params):
start = int(params.get("cursor", 0))
page = REPOS[start:start + 3]
body = {"items": page}
if start + 3 < len(REPOS):
body["next_cursor"] = str(start + 3)
return {}, json.dumps(body)
def fake_link_api(url):
m = re.search(r"page=(\d+)", url)
page = int(m.group(1)) if m else 1
items = REPOS[(page - 1) * 3: page * 3]
headers = {}
if page * 3 < len(REPOS):
headers["Link"] = f'<https://api.example.com/repos?page={page + 1}>; rel="next", <https://api.example.com/repos?page=3>; rel="last"'
return headers, json.dumps(items)
# ---- generic paginators ----
def paginate_cursor(call, path, max_pages=100):
params = {}
for _ in range(max_pages): # a bound, in case the API loops
_, body = call(path, params)
data = json.loads(body)
yield from data["items"]
if "next_cursor" not in data:
return
params = {"cursor": data["next_cursor"]}
raise RuntimeError(f"more than {max_pages} pages; giving up")
def next_link(link_header):
for part in link_header.split(","):
m = re.match(r'\s*<([^>]+)>\s*;\s*rel="next"', part)
if m:
return m.group(1)
return None
def paginate_links(get, url, max_pages=100):
pages = 0
while url and pages < max_pages:
headers, body = get(url)
pages += 1
print(f" fetched {url}")
yield from json.loads(body)
url = next_link(headers.get("Link", ""))
names = [r["name"] for r in paginate_cursor(fake_cursor_api, "/v1/repos")]
print("cursor style:", names)
print("Link-header style:")
active = [r["name"] for r in paginate_links(fake_link_api, "https://api.example.com/repos") if not r["archived"]]
print("active repos:", active)cursor style: ['repo-1', 'repo-2', 'repo-3', 'repo-4', 'repo-5', 'repo-6', 'repo-7']
Link-header style:
fetched https://api.example.com/repos
fetched https://api.example.com/repos?page=2
fetched https://api.example.com/repos?page=3
active repos: ['repo-1', 'repo-3', 'repo-4', 'repo-6', 'repo-7']
Because the paginators are generators, pages are fetched only as the loop needs them: next(paginate_cursor(...))
fetches one page, and a loop that breaks early never requests the rest. max_pages is a safety net against an API
bug (or your own) that keeps returning the same cursor.
Test yourself
Which response should a client retry?
- 404 Not Found
- 422 Unprocessable Entity
- 503 Service Unavailable on a GET
- 401 Unauthorized
What is jitter for in a backoff strategy?
- Making retries faster
- Spreading retries from many clients over time so they do not hit the server in synchronised waves
- Encrypting requests
- Counting attempts
Why are cursor-based pages more robust than offset pages?
- They are shorter
- Offsets can skip or repeat items when the list changes between requests; a cursor marks a position in the data
- Cursors do not need authentication
- Offsets are not allowed in REST