In the APIs lesson we fetched orders with requests, one call at a time. That's fine for a few calls. But ShopKart's nightly job needs details for thousands of orders, and each call takes a few hundred milliseconds of pure waiting: the request travels to the server, the server queries its database, the answer travels back. Your CPU does nothing during that time.
Every example below ran for real on Python 3.13 against a small local test API where each request takes 0.3 seconds, like a real API over the internet. The timings are what we measured; yours will be close.
The slow way: one request at a time
import time
import requests
BASE_URL = "http://localhost:8766"
order_ids = list(range(1001, 1021)) # 20 orders to look up
start = time.perf_counter()
orders = []
for oid in order_ids:
r = requests.get(f"{BASE_URL}/orders/{oid}", timeout=10)
r.raise_for_status()
orders.append(r.json())
elapsed = time.perf_counter() - start
print(f"{len(orders)} orders in {elapsed:.1f} s")
print(orders[0])20 orders in 6.3 s
{'order_id': 1001, 'status': 'DELIVERED', 'amount': 1536}20 requests × 0.3 s = 6 seconds, plus a little overhead. For 5,000 orders that's 25 minutes, almost all of it waiting.
The idea: wait for many things at once
Think of a chai stall. A bad vendor takes one order, makes it, serves it, and only then takes the next. A good vendor puts four pots on the stove and serves whichever is ready. Same one person, much more chai. That's concurrency: one worker, switching whenever something is waiting.
| Word | Meaning |
|---|---|
| async def | Defines a coroutine: a function that can pause while it waits |
| await | "Pause here until this finishes, and let other tasks run meanwhile" |
| event loop | The vendor: runs tasks and switches to another whenever one is waiting |
| asyncio.run(main()) | Starts the event loop, runs main(), and stops when it's done |
| asyncio.gather(a, b, c) | Runs several coroutines at the same time and returns all results, in order |
import asyncio
async def fetch(name: str, seconds: float) -> str:
print(f"start {name}")
await asyncio.sleep(seconds) # waiting: let other tasks run meanwhile
print(f"done {name}")
return name
async def main():
results = await asyncio.gather( # run all three at the same time
fetch("orders", 0.3),
fetch("customers", 0.1),
fetch("products", 0.2),
)
print(results) # gather keeps the original order
start = time.perf_counter()
asyncio.run(main())
print(f"took {time.perf_counter() - start:.1f} s (not 0.6 s)")start orders start customers start products done customers done products done orders ['orders', 'customers', 'products'] took 0.3 s (not 0.6 s)
- All three start immediately, then finish in order of how long they wait: customers (0.1 s) first.
gatherstill returns results in the order you passed them, not the order they finished.- Total time is the slowest task (0.3 s), not the sum (0.6 s).
The trap: blocking code inside async
Async only helps when tasks await something. A normal blocking call, like time.sleep or requests.get, freezes the whole event loop, so nothing else can run:
async def bad_fetch(name: str) -> None:
time.sleep(0.3) # ❌ blocking: freezes the whole event loop
print(f"done {name}")
async def main():
await asyncio.gather(bad_fetch("a"), bad_fetch("b"), bad_fetch("c"))
start = time.perf_counter()
asyncio.run(main())
print(f"took {time.perf_counter() - start:.1f} s: no faster than a normal loop")done a done b done c took 0.9 s: no faster than a normal loop
Step 1: Fetch orders with httpx
httpx works like requests but has an async client. Install it:
$pip install httpx
import httpx
async def fetch_order(client: httpx.AsyncClient, oid: int) -> dict:
r = await client.get(f"/orders/{oid}")
r.raise_for_status()
return r.json()
async def fetch_all(ids: list[int]) -> list[dict]:
# One client for all requests: it reuses connections
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10) as client:
return await asyncio.gather(*(fetch_order(client, oid) for oid in ids))
start = time.perf_counter()
orders = asyncio.run(fetch_all(order_ids))
print(f"{len(orders)} orders in {time.perf_counter() - start:.1f} s")
print(orders[0])20 orders in 0.4 s
{'order_id': 1001, 'status': 'DELIVERED', 'amount': 1536}20 orders in 0.4 s instead of 6.3 s, about 16× faster, with the same results. Two habits to copy:
- One
AsyncClientfor all requests (withasync with). It reuses connections, which is faster and kinder to the server than opening a new one per request. - Always set a timeout, so one stuck request can't hang the job forever.
Step 2: Don't flood the API (Semaphore)
Firing every request at once works for 20. For 5,000 it's a denial-of-service attack on your partner's API. Most APIs limit how many requests you can make, and answer 429 Too Many Requests when you go over. Our test API allows 5 at a time:
async def fetch_limited(client: httpx.AsyncClient, oid: int) -> int:
r = await client.get(f"/limited/orders/{oid}")
return r.status_code
async def main():
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10) as client:
codes = await asyncio.gather(*(fetch_limited(client, oid) for oid in order_ids))
print({code: codes.count(code) for code in sorted(set(codes))})
asyncio.run(main()){200: 5, 429: 15}Only 5 of 20 succeeded. The fix is an asyncio.Semaphore: a counter that lets at most N tasks into a block at once. The rest wait their turn.
async def fetch_politely(client: httpx.AsyncClient, limit: asyncio.Semaphore, oid: int) -> dict:
async with limit: # at most 5 requests in flight at once
r = await client.get(f"/limited/orders/{oid}")
r.raise_for_status()
return r.json()
async def fetch_all_politely(ids: list[int], max_at_once: int = 5) -> list[dict]:
limit = asyncio.Semaphore(max_at_once)
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10) as client:
return await asyncio.gather(*(fetch_politely(client, limit, oid) for oid in ids))
start = time.perf_counter()
orders = asyncio.run(fetch_all_politely(order_ids))
print(f"{len(orders)} orders in {time.perf_counter() - start:.1f} s, no 429s")20 orders in 1.3 s, no 429s
See how the limit changes the timeline:
When does each request run?
1.2 s for 20 requests
5× faster than the for loop
At most 5 requests are waiting at the same time. Total ≈ 4 rounds × 0.3 s. Real runs add a little overhead: we measured 1.3 s for 20 orders with a limit of 5.
Step 3: When one request fails
By default, if any task in gather raises an exception, gather raises it too, and you lose the results of the others:
asyncio.run(fetch_all([1001, 1002, 999, 1004])) # order 999 doesn't existHTTPStatusError: Client error '404 Not Found' for url 'http://localhost:8766/orders/999'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404With return_exceptions=True, errors come back as values in the result list. Keep the good results and report the bad ones:
async def fetch_all_safely(ids: list[int]) -> tuple[list[dict], list[str]]:
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10) as client:
results = await asyncio.gather(*(fetch_order(client, oid) for oid in ids),
return_exceptions=True) # errors come back as values
good = [r for r in results if not isinstance(r, Exception)]
bad = [f"{oid}: {r.response.status_code}" for oid, r in zip(ids, results)
if isinstance(r, httpx.HTTPStatusError)]
return good, bad
good, bad = asyncio.run(fetch_all_safely([1001, 1002, 999, 1004]))
print(f"{len(good)} fetched, failed: {bad}")3 fetched, failed: ['999: 404']
Step 4: Retry temporary failures
503 (busy) and 429 usually mean “try again soon”. Retry a few times with a growing wait (exponential backoff), using await asyncio.sleep so other requests keep running while one waits:
async def fetch_with_retry(client: httpx.AsyncClient, oid: int, attempts: int = 3) -> dict:
for attempt in range(1, attempts + 1):
r = await client.get(f"/flaky/orders/{oid}")
if r.status_code in (429, 500, 502, 503, 504) and attempt < attempts:
wait = 0.1 * 2 ** (attempt - 1) # 0.1 s, then 0.2 s: exponential backoff
print(f"order {oid}: got {r.status_code}, retrying in {wait} s")
await asyncio.sleep(wait) # asyncio.sleep, never time.sleep
continue
r.raise_for_status()
return r.json()
async def main():
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10) as client:
orders = await asyncio.gather(*(fetch_with_retry(client, oid) for oid in range(1001, 1016)))
print(f"{len(orders)} orders fetched")
asyncio.run(main())order 1001: got 503, retrying in 0.1 s order 1015: got 503, retrying in 0.1 s order 1008: got 503, retrying in 0.1 s 15 orders fetched
Three orders failed once and worked on the retry; all 15 arrived. The retry lines can appear in a different order each run, because tasks finish whenever their responses arrive.
Async vs threads
You can also overlap waiting with threads, as in the advanced Python lesson. With requests and ThreadPoolExecutor:
from concurrent.futures import ThreadPoolExecutor
def fetch_order_sync(oid: int) -> dict:
r = requests.get(f"{BASE_URL}/orders/{oid}", timeout=10)
r.raise_for_status()
return r.json()
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=10) as pool: # 10 requests at a time, in threads
orders = list(pool.map(fetch_order_sync, order_ids))
print(f"{len(orders)} orders in {time.perf_counter() - start:.1f} s with 10 threads")20 orders in 0.7 s with 10 threads
| Threads (ThreadPoolExecutor) | Async (asyncio + httpx) | |
|---|---|---|
| Works with | Normal blocking libraries (requests, most DB drivers) | Async libraries only (httpx, aiohttp, asyncpg) |
| Good for | Tens of concurrent calls, quick wins in existing code | Hundreds to thousands of calls, fine control |
| Our test (20 calls) | 0.7 s with 10 threads | 0.4 s |
| Cost per task | A thread each (memory, OS limits) | Very small; one thread for everything |
| Learning curve | Low | Medium: async def, await, event loop |
When async doesn't help
🌐Waiting on network or disk
API calls, downloads, DB queries → async or threads
🧮Heavy calculation
Parsing, maths, ML → multiprocessing
🗄️Huge data
Millions of rows → pandas, Polars, Spark
Async runs everything on one thread. If the slow part is your own code crunching numbers, there's no waiting to overlap, so it won't get faster.
Putting it together: 100 orders into a DataFrame
The job ShopKart actually runs: fetch details for a batch of orders politely (5 at a time), then analyse them with pandas.
import pandas as pd
ids = list(range(1001, 1101)) # 100 orders this time
start = time.perf_counter()
details = asyncio.run(fetch_all_politely(ids, max_at_once=5))
df = pd.DataFrame(details)
print(f"{len(df)} orders in {time.perf_counter() - start:.1f} s")
print(df.groupby("status")["amount"].agg(["count", "sum"]))100 orders in 6.5 s
count sum
status
CANCELLED 20 62850
DELIVERED 60 184790
PLACED 20 62110100 orders in 6.5 s with a limit of 5. One at a time it would take 30 s. Raise the limit (if the API allows it) and it gets faster still. From here, save the raw results to bronze exactly as in the APIs lesson.
Common mistakes
| Mistake | What goes wrong | Do this instead |
|---|---|---|
| requests or time.sleep inside async def | Runs one at a time, no speed-up | httpx / asyncio.sleep, or asyncio.to_thread |
| Forgetting await | You get a coroutine object, not data (and a warning) | await every async call |
| No concurrency limit | 429s, or you overload the API | asyncio.Semaphore(N) |
| A new client per request | Slow, too many connections | One AsyncClient, shared |
| No timeout | One stuck call hangs the job | httpx.AsyncClient(timeout=10) |
| One error kills the batch | 99 good results lost | return_exceptions=True, or try/except per task |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What's the difference between concurrency and parallelism?Fresher+
Q2Why doesn't async speed up CPU-bound code, and what does?1–3 yrs+
Q3How do you call a rate-limited API thousands of times efficiently?1–3 yrs+
Q4Your async job is no faster than the old sync version. How do you debug it?3+ yrs+
Key takeaways
- ✓API-heavy pipelines spend most of their time waiting; concurrency overlaps the waits.
- ✓asyncio + httpx fetched 20 orders 16× faster than a plain loop in our test.
- ✓Be polite: limit concurrency with a Semaphore, set timeouts, retry with backoff.
- ✓Handle partial failure with return_exceptions=True.
- ✓Threads are a fine alternative for small jobs; neither helps CPU-heavy work.
Next: put everything together in the ETL pipeline project.
Frequently asked questions
What is async in Python?
Async (asyncio) lets one Python program wait for many slow things at once, like API calls, database queries or file downloads. Functions defined with async def can pause at await while waiting, and the event loop runs other work in the meantime. It makes I/O-heavy code much faster without extra threads or processes.
Does async make Python code run in parallel?
No. Async runs one thing at a time on one thread, but switches whenever a task is waiting. That's concurrency, not parallelism. It speeds up waiting (network, disk), not calculating. For CPU-heavy work use multiprocessing, or a tool like Spark or Polars.
Should I use async or threads for API calls?
Both work for I/O. Threads with ThreadPoolExecutor are simplest when you already use requests and need tens of calls. Async with httpx scales better to hundreds or thousands of calls and gives fine control (limits, timeouts, cancellation). In our test, 20 calls took 0.7 s with 10 threads and 0.4 s with async.
Can I use requests with asyncio?
Not directly: requests is blocking, so it freezes the event loop while it waits. Use an async client such as httpx.AsyncClient or aiohttp. If you must call blocking code from async, wrap it in asyncio.to_thread so it runs in a thread.
Why do I get 'asyncio.run() cannot be called from a running event loop'?
Jupyter and Databricks notebooks already run an event loop. In a notebook cell, write await main() directly instead of asyncio.run(main()). In normal .py scripts, asyncio.run(main()) is correct.
🧠 Quick check: async Python
1. Your script calls 200 slow APIs one by one. What makes it much faster?
2. Inside async def, which line freezes everything?
3. An API allows 5 requests at a time. You gather 20 at once. What happens?
4. One of 100 gathered requests fails. How do you keep the other 99?
Checking your access…