Part 12 / Topic 6 of 11
Being a good API citizen
Servers are shared by thousands of users. Be polite and your program keeps working. Think of a shop counter: do not shout the same question 100 times a second, and if the shopkeeper says "wait a minute", wait.
- Rate limits: most APIs allow only so many requests per minute or day. Too many gives
429 Too Many Requests, often with aRetry-Afterheader (seconds to wait). - Retries with backoff: some errors are temporary (
429,500,502,503,504, timeouts). Try again a few times, waiting longer each time (0.1 s, 0.2 s, 0.4 s ...). This is exponential backoff. Do not retry400,401or404: asking again will not fix them. - Caching: if the data does not change every second (a weather forecast, exchange rates), save the answer to a file with the time, and reuse it for a while instead of asking again.
import time
class TemporaryError(Exception):
pass
state = {"calls": 0}
def flaky_fetch() -> str: # pretends to be an API: fails twice
state["calls"] += 1
if state["calls"] <= 2:
raise TemporaryError("429")
return "rates data"
def retry(func, attempts=4, base_delay=0.1):
for attempt in range(1, attempts + 1):
try:
return func()
except TemporaryError:
if attempt == attempts:
raise # give up, let the caller know
delay = base_delay * 2 ** (attempt - 1)
print(f"attempt {attempt} failed, waiting {delay} s")
time.sleep(delay)
print(retry(flaky_fetch))
# attempt 1 failed, waiting 0.1 s
# attempt 2 failed, waiting 0.2 s
# rates data
A simple file cache saves the URL, the time and the data. Next time, if the URL is the same and the answer is young enough, it is reused:
import json
import time
from pathlib import Path
CACHE_FILE = Path("demo_cache.json")
MAX_AGE = 600 # seconds (10 minutes)
def get_cached(url, fetch):
if CACHE_FILE.exists():
cache = json.loads(CACHE_FILE.read_text(encoding="utf-8"))
if cache["url"] == url and time.time() - cache["saved_at"] < MAX_AGE:
return cache["data"] # no request sent
data = fetch(url)
cache = {"url": url, "saved_at": time.time(), "data": data}
CACHE_FILE.write_text(json.dumps(cache), encoding="utf-8")
return data
def fake_fetch(url):
print("asking the server ...")
return {"USD": 0.012}
print(get_cached("https://rates.example.com/inr", fake_fetch))
# asking the server ...
# {'USD': 0.012}
print(get_cached("https://rates.example.com/inr", fake_fetch))
# {'USD': 0.012} (from the file, no "asking" line)
CACHE_FILE.unlink() # clean up the demo file
Full program: examples/04_retry_and_cache.py (real 429 answers from the fake API, backoff, and a file cache that saves a request).
๐ Going deeper: real retry code also adds a little random "jitter" to each wait, so a thousand clients do not all retry at the same moment, and it respects
Retry-Afterwhen the server sends it.
Done here? The practice set for Part 12 โ 8 exercises with solutions โ is on the part page.