Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 05 / Topic 7 of 7

Concurrency with limits

A backfill over thousands of pages begs for parallelism, but an uncapped asyncio.gather is a self-inflicted denial of service on the customer's API. A semaphore caps requests in flight:

# examples/04_fetch_in_parallel_but_never_more.py
import asyncio
import httpx
from fdelab import API_TOKEN, customer_api_transport

MAX_IN_FLIGHT = 2      # caps concurrent requests; it is NOT a per-second rate limit, so keep 429 handling
in_flight = peak = 0

async def fetch_page(client, sem, page):
    global in_flight, peak
    async with sem:                                # at most MAX_IN_FLIGHT requests at a time
        in_flight += 1; peak = max(peak, in_flight)
        try:
            await asyncio.sleep(0.01)              # stand-in for network time
            r = await client.get("/v1/shipments", params={"page": page})
            r.raise_for_status()                   # add retries as in the resilient client example
            return r.json()["data"]
        finally:
            in_flight -= 1

async def main():
    sem = asyncio.Semaphore(MAX_IN_FLIGHT)
    transport = customer_api_transport(rate_limit_every=0, flaky_request=0)   # well-behaved API
    async with httpx.AsyncClient(base_url="https://api.acme.example", transport=transport,
                                 headers={"Authorization": f"Bearer {API_TOKEN}"}) as client:
        pages = await asyncio.gather(*(fetch_page(client, sem, p) for p in [1, 2, 3]))
    print("rows per page:", [len(p) for p in pages], "| total:", sum(map(len, pages)))
    print("most requests in flight at once:", peak)

asyncio.run(main())
# rows per page: [3, 3, 2] | total: 8
# most requests in flight at once: 2

Note the comment in the code: a concurrency cap is not a rate limit. Two requests in flight can still exceed a per-second quota, so the 429 handling from lesson 3 stays in even when you parallelise.

Done here? The practice set for Part 5 — 4 exercises with solutions — is on the part page.

Search the guide