Project: speed up API calls
When a program calls many APIs one after another, almost all the time is spent waiting. Running the calls concurrently — with ThreadPoolExecutor for existing code or asyncio with httpx for new code — cuts the total to roughly the slowest call. Production versions add a concurrency limit, timeouts and retries.
The scenario
You need free cash flow (cash from operations minus capital expenditure) for a list of companies, and every company needs its own API request. The original version of this case study used a finance library that has since stopped working, so here we use a simulated API with realistic delays — the techniques are exactly the same for any real API.
import random
import time
DATA = {
"NEM": (2_870, 1_570), "FCX": (5_160, 4_810), "BHP": (20_670, 9_270),
"RIO": (15_600, 9_620), "VALE": (9_770, 6_400), "AAL": (3_960, 3_150),
}
def get_cash_flow(ticker: str) -> dict:
"""Pretend API: 0.5–1.0 s per call, like a real network round trip."""
time.sleep(random.uniform(0.5, 1.0))
operations, capex = DATA[ticker]
return {"ticker": ticker, "operations": operations, "capex": capex}
def free_cash_flow(row: dict) -> int:
return row["operations"] - row["capex"]Version 1: one by one
import time
from fake_api import DATA, free_cash_flow, get_cash_flow
start = time.perf_counter()
rows = [get_cash_flow(t) for t in DATA]
for row in rows:
print(f"{row['ticker']:<5}{free_cash_flow(row):>8,}")
print(f"took {time.perf_counter() - start:.1f}s")NEM 1,300 FCX 350 BHP 11,400 RIO 5,980 VALE 3,370 AAL 810 took 4.5s
Version 2: a thread pool
import time
from concurrent.futures import ThreadPoolExecutor
from fake_api import DATA, free_cash_flow, get_cash_flow
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=8) as pool:
rows = list(pool.map(get_cash_flow, DATA))
for row in rows:
print(f"{row['ticker']:<5}{free_cash_flow(row):>8,}")
print(f"took {time.perf_counter() - start:.1f}s")NEM 1,300 FCX 350 BHP 11,400 RIO 5,980 VALE 3,370 AAL 810 took 1.0s
Three changed lines, same results, about four times faster. pool.map keeps the original order, so the report doesn't change. This is the quickest win when your code already uses a blocking library such as requests.
Version 3: asyncio
import asyncio
import random
import time
from fake_api import DATA, free_cash_flow
async def get_cash_flow(ticker: str, limit: asyncio.Semaphore) -> dict:
async with limit:
await asyncio.sleep(random.uniform(0.5, 1.0))
operations, capex = DATA[ticker]
return {"ticker": ticker, "operations": operations, "capex": capex}
async def main() -> None:
limit = asyncio.Semaphore(10)
start = time.perf_counter()
rows = await asyncio.gather(*(get_cash_flow(t, limit) for t in DATA))
for row in rows:
print(f"{row['ticker']:<5}{free_cash_flow(row):>8,}")
print(f"took {time.perf_counter() - start:.1f}s")
asyncio.run(main())NEM 1,300 FCX 350 BHP 11,400 RIO 5,980 VALE 3,370 AAL 810 took 1.0s
| Version | Time for 6 calls | Best when |
|---|---|---|
| Sequential | ~4.5 s (sum of all calls) | A handful of calls, simplicity matters most |
| Thread pool | ~1 s (the slowest call) | Existing code with requests or SDKs |
| asyncio | ~1 s (the slowest call) | Hundreds of calls, async libraries, web servers |
Making it production-ready
import asyncio
import httpx
async def fetch_json(client: httpx.AsyncClient, url: str, retries: int = 3) -> dict:
for attempt in range(1, retries + 1):
try:
response = await client.get(url, timeout=10)
response.raise_for_status()
return response.json()
except (httpx.TransportError, httpx.HTTPStatusError) as err:
if attempt == retries:
raise
await asyncio.sleep(2 ** attempt) # back off: 2 s, 4 s...
raise RuntimeError("unreachable")
async def fetch_all(urls: list[str], max_concurrent: int = 5) -> list[dict]:
limit = asyncio.Semaphore(max_concurrent)
async with httpx.AsyncClient() as client:
async def guarded(url: str) -> dict:
async with limit:
return await fetch_json(client, url)
return await asyncio.gather(*(guarded(u) for u in urls))- One shared
AsyncClientreuses connections instead of opening a new one per request. timeout=10stops one hanging server from freezing the whole job.- Retries with exponential back-off survive brief outages without hammering the server.
- A
Semaphorerespects the API's rate limit. Check the provider's documented limits.
Practice
Compute free cash flow for the report. Given rows = [{"ticker": "NEM", "operations": 2870, "capex": 1570}, {"ticker": "FCX", "operations": 5160, "capex": 4810}, {"ticker": "BHP", "operations": 20670, "capex": 9270}], print each ticker with its free cash flow like NEM: 1300, then the ticker with the highest free cash flow.
NEM: 1300 FCX: 350 BHP: 11400 BHP