Platform Engineering · Lesson 40

Python for APIs: HTTP, Cloud SDKs, Retries, and Concurrency

Modern automation talks to APIs: cloud providers, Git hosts, monitoring, ticketing. Doing it well is a small checklist: authenticate from the environment, set timeouts, check the status code, follow pagination to the last page, retry with exponential backoff and jitter on 429 and 5xx, respect rate limits, and run calls concurrently without overwhelming the API. This lesson builds an inventory report from a cloud API, and shows the two classic mistakes: reading only the first page, and fifty threads that retry instantly until the account is throttled.

Difficulty: Advanced · Know this first: Lesson 38, Lesson F23

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up seconds for the report. It is a worked example, not a measurement. The pagination and rate-limit hops decide whether the report is complete and whether it hurts anyone else.

Try it: workers, backoff, and the rate limit

The API allows 100 requests per second for the whole account. Choose the number of workers and the retry delay. Each worker makes about 7 requests per second, and more when it retries instantly.

1,750/srequests per second
throttledaccount state

Throttled: instant retries multiply the load far past the limit

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

API automation grows in four levels: requests, robust clients, concurrent clients, and integrations other teams rely on.

Basic — Call an API

At the basic level you can fetch and parse JSON.

  • requests.get(url, headers=..., params=..., timeout=10); r.status_code, r.json().
  • Tokens from os.environ; never in code or URLs.
  • urllib.request when no packages can be installed.

Where it breaks: no timeout, so one slow server hangs the script.

Try it: Basic

What does requests.get(url) do if the server accepts the connection and never responds, with no timeout?

Now do it: Add timeout= to every HTTP call in one of your scripts.

Intermediate — Robust clients

At the intermediate level the client handles real-world APIs.

  • Pagination loops; raise_for_status(); defensive field access.
  • Retries with exponential backoff and jitter on 429 and 5xx; honour Retry-After.
  • A shared Session for connection pooling.

Try it: Intermediate

A POST that creates a resource times out. Is it safe to retry?

Now do it: Check whether an API you use accepts an Idempotency-Key header.

Advanced — Concurrent clients

At the advanced level clients are fast and polite.

  • ThreadPoolExecutor with a small max_workers, or asyncio with a Semaphore.
  • Client-side rate limiting (a token bucket) below the provider's limit.
  • SDK configuration: adaptive retries, paginators, waiters.

Try it: Advanced

A report is slow with 1 worker. Going to 4 workers makes it 3.5 times faster; going to 32 makes it slower. Why?

Now do it: Measure your report with 1, 4, 8, and 16 workers.

Master — Integrations others depend on

At the master level integrations are observable and shared fairly.

  • Metrics per endpoint: calls, errors, 429s, latency; alerts on rising 429s.
  • Separate credentials (and so separate rate limits) for batch reports and for deploys.
  • Caching and incremental sync (changes since the last run) instead of full listings.

Trade-off: more concurrency finishes reports sooner and spends a shared budget other tools need; incremental sync is efficient and needs state to be stored and trusted.

Try it: Master

A nightly report and production deploys share one API account and its rate limit. What reduces the risk?

Now do it: List which tools share the same cloud account or API token.

Go deeper

A paginated, retrying, concurrent client using only the standard library. Point it at any JSON API that returns a next link.

import json, os, random, time, urllib.error, urllib.request
from concurrent.futures import ThreadPoolExecutor

RETRY = {429, 500, 502, 503, 504}

def get_json(url, attempts=5):
    req = urllib.request.Request(url, headers={
        "Authorization": f"Bearer {os.environ.get('API_TOKEN', '')}",
        "User-Agent": "inventory-report/1.4"})
    for attempt in range(1, attempts + 1):
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                return json.load(r)
        except urllib.error.HTTPError as e:
            if e.code not in RETRY or attempt == attempts:
                raise
            wait = float(e.headers.get("Retry-After") or min(30, 0.5 * 2 ** attempt))
        except (urllib.error.URLError, TimeoutError):
            if attempt == attempts:
                raise
            wait = min(30, 0.5 * 2 ** attempt)
        time.sleep(wait + random.uniform(0, wait / 2))      # backoff with jitter

def all_pages(url):
    while url:                                               # follow every page
        page = get_json(url)
        yield from page["items"]
        url = page.get("next")

def details(item):
    return get_json(item["url"])

items = list(all_pages("https://api.example.com/v1/instances?limit=100"))
with ThreadPoolExecutor(max_workers=6) as pool:              # bounded
    rows = list(pool.map(details, items))
print(len(rows), "instances")

The same with boto3

import boto3
from botocore.config import Config

ec2 = boto3.client("ec2", config=Config(retries={"mode": "adaptive", "max_attempts": 5}))
count = sum(len(r["Instances"]) for page in ec2.get_paginator("describe_instances").paginate()
            for r in page["Reservations"])
print(count, "instances")

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A cost report throttled a production deploy.

Timeline

  • 10:00A new cost report runs with 50 threads and SDK retries disabled in favour of a hand-written loop with no delay.
  • 10:02The provider returns 429s. Every thread retries immediately; the account's request rate rises twentyfold and the provider throttles all calls for the account.
  • 10:05A production deploy using the same account fails with throttling errors. It succeeds after the report is stopped and the throttle lifts.

What changed after

Reports use a separate role and account with their own limits, SDK adaptive retries are mandatory, concurrency is capped at 8, and 429 rates are graphed per caller.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Serve a paginated JSON API locally to practise against.

    mkdir -p /tmp/api && cd /tmp/api && python3 -c "import json
    for p in range(1, 4):
        nxt = f'/page{p + 1}.json' if p < 3 else None
        json.dump({'items': list(range((p - 1) * 3, p * 3)), 'next': nxt}, open(f'page{p}.json', 'w'))" && (python3 -m http.server 8765 >/dev/null 2>&1 &) && sleep 1 && cd - >/dev/null
  2. One page is not the whole list.

    curl -s localhost:8765/page1.json; echo
  3. Follow every page until next is empty.

    python3 -c "import json, urllib.request
    url, items = 'http://localhost:8765/page1.json', []
    while url:
        page = json.load(urllib.request.urlopen(url, timeout=5)); items += page['items']
        url = 'http://localhost:8765' + page['next'] if page['next'] else None
    print(len(items), 'items:', items)"
  4. Status codes: a missing page is a 404 you should not retry; then stop the server.

    curl -s -o /dev/null -w "%{http_code}\n" localhost:8765/page9.json; pkill -f "http.server 8765"; rm -rf /tmp/api

2. Python: backoff_sim.py

This program simulates 300 clients against an API limited to 100 requests per second, once retrying instantly and once with exponential backoff and jitter, and counts what reaches the API. Save it as backoff_sim.py, then run it.

# backoff_sim.py
import random

def run(strategy, clients=300, limit=100, seconds=30):
    random.seed(42)
    next_try = [0.0] * clients
    attempt = [0] * clients
    done = sent = throttled = 0
    finished_at = 0.0
    for tick in range(seconds * 10):              # 100 ms ticks
        now = tick / 10
        ready = [c for c in range(clients) if next_try[c] is not None and next_try[c] <= now]
        random.shuffle(ready)
        budget = limit // 10
        for c in ready:
            sent += 1
            if budget > 0:
                budget -= 1
                done += 1
                finished_at = now
                next_try[c] = None                  # finished
            else:
                throttled += 1
                attempt[c] += 1
                if strategy == "instant retry":
                    next_try[c] = now
                else:
                    wait = min(8, 0.25 * 2 ** attempt[c])
                    next_try[c] = now + wait + random.uniform(0, wait)
    return done, sent, throttled, finished_at

for strategy in ["instant retry", "backoff + jitter"]:
    done, sent, throttled, t = run(strategy)
    print(f"{strategy:<16} finished {done}/300 by {t:4.1f} s, requests sent {sent:>5,}, of which 429s {throttled:>5,} ({throttled / sent:.0%})")

Run it, and you should see this output:

$ python3 backoff_sim.py
instant retry    finished 300/300 by  2.9 s, requests sent 4,650, of which 429s 4,350 (94%)
backoff + jitter finished 300/300 by  6.7 s, requests sent   940, of which 429s   640 (68%)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-http-apis-cloud-sdks-and-concurrency && cd ~/labs/python-http-apis-cloud-sdks-and-concurrency) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Python for APIs: HTTP, Cloud SDKs, Retries, and Concurrency", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Serve a paginated JSON API locally to practise against.'
  'One page is not the whole list.'
  'Follow every page until next is empty.'
  'Status codes: a missing page is a 404 you should not retry; then stop the server.'
)

step_1() {
mkdir -p /tmp/api && cd /tmp/api && python3 -c "import json
for p in range(1, 4):
    nxt = f'/page{p + 1}.json' if p < 3 else None
    json.dump({'items': list(range((p - 1) * 3, p * 3)), 'next': nxt}, open(f'page{p}.json', 'w'))" && (python3 -m http.server 8765 >/dev/null 2>&1 &) && sleep 1 && cd - >/dev/null
}

step_2() {
curl -s localhost:8765/page1.json; echo
}

step_3() {
python3 -c "import json, urllib.request
url, items = 'http://localhost:8765/page1.json', []
while url:
    page = json.load(urllib.request.urlopen(url, timeout=5)); items += page['items']
    url = 'http://localhost:8765' + page['next'] if page['next'] else None
print(len(items), 'items:', items)"
}

step_4() {
curl -s -o /dev/null -w "%{http_code}\n" localhost:8765/page9.json; pkill -f "http.server 8765"; rm -rf /tmp/api
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Build a nightly job that lists every repository in a Git hosting organisation and reports those without branch protection, for 3,000 repositories.

Clarifying questions to ask

How do you page through repositories? How many calls per repository, and how many in parallel? What do you do on 403, 404, 429, and 5xx? How do you keep within the API's hourly limit?

Rough sizing

Say pages of 100, two calls per repository, a limit of 5,000 requests per hour, and a run that must finish within an hour.

Shape of the answer

A token from the environment; a paginated listing; a ThreadPoolExecutor of 4 workers; a token bucket at 1.2 requests per second; retries on 429 and 5xx honouring Retry-After and the rate-limit reset header; 404 recorded as "no protection"; 403 logged and counted; a JSON report and a non-zero exit if any repository could not be checked.

Trade-offs to name

Staying under the hourly limit makes the run take most of the hour; caching unchanged repositories between runs cuts calls sharply and needs stored state to be trusted.

Saved on this device, in this browser.
Next in this series · Lesson 41
Python Testing, Typing, and Shipping Tools

Automation that changes production deserves the same safety net as the services it manages: tests with pytest that run in seconds, fakes for the network and the cloud, type hints checked by mypy, a linter and formatter (ruff)…

Go to Lesson 41 →

Or browse the full course from the Lessons index.