Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Many requests at once with asyncio and httpx: limits, timeouts and retries.
How can a client overlap waiting while staying within an upstream service's limits?
An event loop can run other tasks while a request waits for the network. A concurrency limit bounds how many requests use the service at once.
Six independent requests are ready
A semaphore allows two requests in flight
Completed requests free slots for the remaining four
Six independent requests are ready
A semaphore allows two requests in flight
Completed requests free slots for the remaining four
Given Six independent requests are ready and Completed requests free slots for the remaining four, write down the missing step that connects them.
A semaphore allows two requests in flight
Now take A semaphore allows two requests in flight and the result above. Write an input and an implementation that could produce this trace.
Six independent requests are ready. Check that your implementation produces the result shown above.
What happens if each request takes one second and they all start under a limit of two?
It takes roughly three seconds plus overhead. Two requests finish in each of three waves.
Check this when debugging. Expecting async to speed up CPU-heavy work.
A program that checks prices for 200 products, or pulls pages from a dozen services, spends almost all its time waiting for answers. Asking one at a time means waiting 200 times in a row. Asking concurrently means waiting roughly once. That speed comes with duties: don't flood the service, don't hang forever on one slow reply, and retry sensibly when something fails. This lesson builds a client that does all four, using asyncio from the concurrency lesson and httpx, the async-capable cousin of requests.
About 5 seconds
One at a time is 200 × 0.5 = 100 seconds. With 20 in flight, it's about 200 / 20 = 10 rounds of 0.5 seconds: about 5 seconds. Waiting together is the whole trick.
This rests on Concurrency and async, where one event loop ran many waiting tasks, and on Rate limits, retries and idempotency, where a token bucket limited a client. A call to an API spends almost all of its time waiting for the reply, and a waiting program uses no resources. If you send 200 requests one after another, you wait 200 times; if you start many at once, the waits overlap and you wait about once. The overlap needs a cap: starting a thousand requests together is rude to the server, which answers 429 Too Many Requests or slows down for everyone. A semaphore holds a number of permits, and a task needs one to run its request. With a cap of 3, twelve one-second requests run in four rounds. The picture runs it.
All twelve tasks start at once, but only three hold a permit; the rest wait for one.
gather returns results in the order the calls were given, whatever order they finish in. What does this print: the results, and the order of finishing?import asyncio finished = [] async def fetch(name, delay): await asyncio.sleep(delay) finished.append(name) return name async def main(): results = await asyncio.gather(fetch("a", 0.03), fetch("b", 0.01), fetch("c", 0.02)) print(results, finished) asyncio.run(main())
['a', 'b', 'c'] ['b', 'c', 'a']
All three waits start together, so the shortest one finishes first: b, then c, then a. gather still hands the results back in the order you listed the calls. That makes it safe to pair each result with the request that asked for it.
import asyncio async def answer(value, delay): await asyncio.sleep(delay) return value async def main(): print(await asyncio.gather(answer("slow", 0.03), answer("fast", 0.01))) asyncio.run(main())
['slow', 'fast']
gather returns results in the order the awaitables were passed, not the order they finished, so it prints ['slow', 'fast'].
tokens = 5 served = 0 for request in range(8): if tokens >= 1: tokens -= 1 served += 1 print(served, 8 - served)
5 3
The first five requests each take a token. The bucket is then empty, and nothing has had time to refill it, so the last three are refused. A good client doesn't send everything at once. The limits section of this lesson shows how to keep a fixed number of requests in flight.
Write a sentence or two, then compare it with a good answer in the lesson.
In an async def function, await marks the places where the program waits. While one request waits for its reply, the event loop runs others. asyncio.gather starts several awaitables together and returns their results in the order you gave them, whichever finishes first.
The cells in this lesson talk to a pretend price service built with httpx.MockTransport: a function that receives each request and returns a response, here after a 0.2-second pause, like a real network call. The same tool makes async code easy to test, because the "server" is just Python.
import asyncio, time import httpx async def price_service(request): await asyncio.sleep(0.2) # the network and the server's work sku = request.url.path.rsplit("/", 1)[-1] return httpx.Response(200, json={"sku": sku, "price": int(sku[-3:]) / 4}) SKUS = [f"TE-{n}" for n in range(100, 110)] async def one_by_one(client): return [(await client.get(f"/prices/{s}")).json()["price"] for s in SKUS] async def all_at_once(client): replies = await asyncio.gather(*(client.get(f"/prices/{s}") for s in SKUS)) return [r.json()["price"] for r in replies] async def main(): transport = httpx.MockTransport(price_service) async with httpx.AsyncClient( transport=transport, base_url="https://prices.example" ) as client: for fetch in (one_by_one, all_at_once): start = time.perf_counter() prices = await fetch(client) print(f"{fetch.__name__}: {time.perf_counter() - start:.2f}s", prices[:4]) asyncio.run(main())
Ten requests one after another take ten waits; together they take about one. With 200 products the difference is 40 seconds against a fraction of one.
Note:
asyncio.runneeds a current browser (one with WebAssembly JSPI, like recent Chrome, Edge and Safari). If a cell here stops with an error about asyncio, run it on your own computer or update the browser.
Write async def fetch_all(fetch, ids): start fetch(id) for every id at once with asyncio.gather, and return a dictionary from each id to its result, in the order of ids.
import asyncio async def fetch_all(fetch, ids): results = {} for i in ids: results[i] = await fetch(i) return results async def fake_price(sku): await asyncio.sleep(0.02) return len(sku) * 10 print(asyncio.run(fetch_all(fake_price, ["TENT-2P", "MAT", "STOVE"])))
Create one httpx.AsyncClient and share it, inside async with so its connections close at the end. A client keeps connections open between requests (a connection pool), so the second request to the same server skips the slow setup of a new connection and TLS handshake. Creating a client for every request throws that away, and with hundreds of requests it can run the machine out of open connections.
Give the client a base_url and default settings once:
client = httpx.AsyncClient(
base_url="https://api.example.com/v1",
headers={"Authorization": f"Bearer {token}"},
timeout=httpx.Timeout(10.0, connect=3.0),
limits=httpx.Limits(max_connections=10),
)
timeout matters more than it looks. httpx gives up after 5 seconds by default (requests waits forever unless told otherwise), and a program without a timeout can hang for hours on one stuck connection. max_connections caps the pool, which is one way to stop a batch from flooding a server.
Starting a thousand requests at once is rude to the server and usually counterproductive: it answers 429 Too Many Requests, or slows down for everyone. Most APIs document a limit, like "at most 5 requests at a time". An asyncio.Semaphore enforces one in your own code: it holds a number of permits, and async with sem: waits until a permit is free.
import asyncio, time in_flight = 0 busiest = 0 async def fetch(i, sem): global in_flight, busiest async with sem: in_flight += 1 busiest = max(busiest, in_flight) await asyncio.sleep(0.1) # the request in_flight -= 1 return i * i async def main(): sem = asyncio.Semaphore(3) start = time.perf_counter() results = await asyncio.gather(*(fetch(i, sem) for i in range(12))) print(results) print(f"at most {busiest} at once, {time.perf_counter() - start:.2f}s") asyncio.run(main())
Twelve requests of 0.1 seconds, three at a time, take about 0.4 seconds: four rounds. All twelve tasks start at once, but only three hold a permit; the rest wait at async with sem without using any resources. Create the semaphore inside the async code (here in main), so it belongs to the running event loop.
import asyncio async def main(): limit = asyncio.Semaphore(2) in_flight = peak = 0 async def fetch(i): nonlocal in_flight, peak async with limit: in_flight += 1 peak = max(peak, in_flight) await asyncio.sleep(0.01) in_flight -= 1 await asyncio.gather(*(fetch(i) for i in range(6))) print(peak) asyncio.run(main())
2
All six tasks start, and only two can be inside the async with block at a time. The other four wait at the door. As each one leaves, the next comes in. The batch still finishes far sooner than one at a time, and the server never sees more than 2 requests from you at once.
The same semaphore as a picture of time. Each bar is one request, from the moment it holds a permit to the moment it lets go. Change 3 to 6 and run it again: the bars pack into fewer rounds.
import asyncio, time import matplotlib.pyplot as plt spans = [] async def fetch(i, sem, t0): async with sem: start = time.perf_counter() - t0 await asyncio.sleep(0.1) spans.append((i, start, time.perf_counter() - t0)) async def main(): sem = asyncio.Semaphore(3) t0 = time.perf_counter() await asyncio.gather(*(fetch(i, sem, t0) for i in range(12))) asyncio.run(main()) fig, ax = plt.subplots(figsize=(6, 3)) for i, start, end in sorted(spans): ax.barh(i, end - start, left=start) ax.set_xlabel("seconds since the first request") ax.set_ylabel("request number") print(len(spans), "requests")
Write a sentence or two, then compare it with a good answer in the lesson.
In a batch of 200 requests, something will go wrong: a timeout, a 500, a refused connection. Decide what one failure should do to the rest:
asyncio.gather(*tasks) raises the first exception, and you lose the other results.asyncio.gather(*tasks, return_exceptions=True) puts exceptions in the result list in place of values, so you can report each failure and keep every success.async with asyncio.TaskGroup() as tg: (Python 3.11 and later) cancels the remaining tasks when one fails. That's right when the results only make sense together, like the pieces of one page.Often the clearest design is a small function that fetches one item and never raises: it catches the errors it expects and returns a value or an error message. Then a plain gather collects everything.
For a deadline on the whole batch, wrap it in async with asyncio.timeout(30):, which cancels whatever is still running after 30 seconds and raises TimeoutError.
asyncio.TaskGroup do when one task fails?Cancels the remaining tasks
That is right when the results only make sense together, like the pieces of one page.
Rate limits, retries and idempotency built the rules: retry timeouts, connection errors, 429 and 502 to 504; never other 4xx; wait with backoff and jitter, or for Retry-After when the server sends it; cap the attempts; and give a POST an idempotency key. In async code the retry loop lives inside the task that holds the permit, so a task that is waiting to retry still counts against the cap and the batch cannot grow past it.
return_exceptions=True, gather hands back each failure in its place and keeps the other results. What does this print?import asyncio async def fetch(i): if i == 2: raise TimeoutError("request 2 timed out") return i * 10 async def main(): results = await asyncio.gather( *(fetch(i) for i in range(4)), return_exceptions=True ) print([r if isinstance(r, int) else "failed" for r in results]) asyncio.run(main())
[0, 10, 'failed', 30]
Request 2 raised, and its exception sits in position 2 of the results, where its answer would have been. The other three results are intact. Without the flag, gather would raise the first exception and you would lose the three good answers along with the bad one.
Write async def with_default(coro, seconds, default): wait for coro at most seconds with asyncio.wait_for, and return default instead if it takes longer (asyncio.TimeoutError).
import asyncio async def with_default(coro, seconds, default): return await coro async def slow(): await asyncio.sleep(0.2) return "late" print(asyncio.run(with_default(slow(), 0.05, "fallback")))
A status checker for five services. One is slow, one is down, one doesn't exist. Each check returns a line of text, so a single failure never hides the other results.
import asyncio import httpx async def services(request): name = request.url.host.split(".")[0] if name == "slow": await asyncio.sleep(1) if name == "down": return httpx.Response(503) if name == "gone": raise httpx.ConnectError("name not resolved", request=request) return httpx.Response(200, json={"status": "ok"}) async def check(client, name): try: async with asyncio.timeout(0.3): reply = await client.get(f"https://{name}.example/health") reply.raise_for_status() return f"{name}: up" except (TimeoutError, httpx.TimeoutException): return f"{name}: too slow (no answer in 0.3s)" except httpx.HTTPStatusError as e: return f"{name}: answered {e.response.status_code}" except httpx.RequestError as e: return f"{name}: unreachable ({e})" async def main(): async with httpx.AsyncClient(transport=httpx.MockTransport(services)) as client: names = ["shop", "slow", "down", "gone", "search"] async with asyncio.timeout(5): for line in await asyncio.gather(*(check(client, n) for n in names)): print(line) asyncio.run(main())
check gives each service 0.3 seconds with asyncio.timeout, which works whatever the transport. On a real network, httpx's own timeout setting raises httpx.TimeoutException instead, so the except catches both. raise_for_status() turns the 503 into an HTTPStatusError, which carries the response. ConnectError is one kind of RequestError, so the general except httpx.RequestError comes last. Because every check returns a string, gather always gets five results, in the order of names, and the whole batch has a five-second deadline as a safety net.
Write a sentence or two, then compare it with a good answer in the lesson.
A batch of model calls is the job this lesson was made for. Each call takes seconds of waiting, so overlapping them is a large win, and each is limited twice: by requests a minute and by tokens a minute. So the cap on calls in flight comes from the provider's limits, not from what your machine could do. One shared client keeps the connections open, and each task holds a permit while it waits. The cell runs forty "calls" to a pretend model service and records how many were in flight at once.
A pretend model service answers each call after a pause and counts how many calls it holds at once. The semaphore keeps that number at the cap.
import asyncio import httpx state = {"now": 0, "most": 0} async def pretend_model(request): state["now"] += 1 state["most"] = max(state["most"], state["now"]) await asyncio.sleep(0.02) state["now"] -= 1 return httpx.Response(200, json={"stop_reason": "end_turn"}) async def ask(client, sem, n): async with sem: reply = await client.post("/v1/messages", json={"n": n}) return reply.status_code async def main(): sem = asyncio.Semaphore(6) transport = httpx.MockTransport(pretend_model) async with httpx.AsyncClient(transport=transport, base_url="https://m.test") as c: codes = await asyncio.gather(*(ask(c, sem, n) for n in range(40))) print(len(codes), set(codes), "most in flight:", state["most"]) asyncio.run(main())
All forty tasks started together, but never more than six calls were in flight, so the provider's limit would have been respected. Real code also reads the rate-limit headers from each reply and slows the rate when the budget runs low.
The cells here end with asyncio.run(main()): one call that starts the event loop, runs main and closes the loop. A program should call it once, at the top. Inside a Jupyter notebook a loop is already running, so there you write await main() directly in a cell. In a FastAPI app the loop belongs to the server, so an async def endpoint awaits an async client that the app creates once at startup, in its lifespan function (APIs with FastAPI). When a library has only blocking functions, await asyncio.to_thread(func, ...) runs it in a thread so the loop keeps going.
On the job, two mistakes recur. A client made inside the loop of tasks, so every call pays for a new connection. No cap, so a nightly batch of thousands of calls trips the provider's limit and the whole batch is retried. Goes deeper in: Async JavaScript: promises, await and fetch does the same in JavaScript, One request through a serving stack: latency and cost shows the provider's side of the queue, and Caches, queues and background jobs moves a big batch to a queue and workers.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Why share one httpx.AsyncClient across all the requests in a batch?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write