Programming languages · Intermediate · 20 min
Run many network calls at once with Python asyncio
By Padding · Updated 18 Nov 2026
Python 3.15.2 · httpx 0.28.1 · uv 0.13 · python:3.15-slim
You will turn a 20-second price fetcher into one that finishes in about a second with asyncio and httpx, then give it a deadline, a concurrency limit, clean failure handling and a fix for blocking code.
On this page
Most of the time a program that calls an API is not working. It is waiting: for DNS, for the connection, for the server to think, for the bytes to arrive. Call twenty endpoints one after another and you wait twenty times in a row. asyncio, Python's built-in library for concurrent I/O, lets one thread start all twenty requests and handle each answer as it lands, so the waits overlap.
You will build a small price checker. It asks a local stand-in API for the prices of 20 market items, and the API takes one second to answer each request, the way a slow upstream service would. The first version takes about 20 seconds. The async version takes about one. Then you make it safe to use for real: a deadline for the whole batch, a cap on how many requests run at once, a clear report when one request fails, and the fix for the most common asyncio mistake, which is calling blocking code inside a coroutine.
The gain is biggest on slow links. On a mobile connection on prepaid data, where a single round trip can take several hundred milliseconds, overlapping requests saves far more time than it does on a fast office line.
Step 1 · Create the project
Make a throwaway project folder and add httpx, which has both a normal client and an async one. The range allows patch releases of 0.28 and nothing newer:
mkdir -p ~/asyncio-demo
cd ~/asyncio-demo
uv init --no-package
uv add "httpx>=0.28,<0.29"Every script in this tutorial asks for the same 20 items from the same address, so put those in one small module the scripts import:
cat > common.py <<'PY'
BASE_URL = "http://127.0.0.1:8010"
ITEMS = [
"rice", "beans", "maize", "yam", "cassava",
"plantain", "onions", "tomatoes", "pepper", "eggs",
"bread", "milk", "sugar", "salt", "tea",
"coffee", "lentils", "potatoes", "apples", "oranges",
]
PYCheck it worked
uv run python -c "import httpx, common; print(httpx.__version__, len(common.ITEMS))"The command prints 0.28.1 20, or a later 0.28 release followed by 20.
Step 2 · Start a slow stand-in API
Create server.py. It uses only the standard library. GET /price/<item> sleeps for one second and then answers with JSON. One special item, broken, fails with a 500 after a fifth of a second, which you will use later to watch a failure spread:
cat > server.py <<'PY'
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
DELAY_SECONDS = 1.0
def price_for(item):
# A made-up but repeatable price in whole currency units.
return 100 + sum(ord(letter) for letter in item) % 900
class Handler(BaseHTTPRequestHandler):
def send_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
parts = self.path.strip("/").split("/")
if len(parts) != 2 or parts[0] != "price":
return self.send_json(404, {"error": "not found"})
item = parts[1]
if item == "broken":
time.sleep(0.2)
return self.send_json(500, {"error": "price feed down"})
time.sleep(DELAY_SECONDS)
self.send_json(200, {"item": item, "price": price_for(item)})
def log_message(self, format, *args):
pass
class Server(ThreadingHTTPServer):
# Room for many connections arriving at the same moment.
request_queue_size = 64
print("Stand-in API on http://127.0.0.1:8010", flush=True)
Server(("127.0.0.1", 8010), Handler).serve_forever()
PYThreadingHTTPServer gives each request its own thread, so it can serve 20 slow requests side by side, as a real service would. The standard library's default queue for waiting connections is only 5, which is why the script raises request_queue_size: without it, a burst of 20 connections can be held back and blur the timings you are about to measure.
Start it in the second terminal, from ~/asyncio-demo, and leave it running:
uv run server.pyCheck it worked
The second terminal prints Stand-in API on http://127.0.0.1:8010. In your first terminal, ask for one price:
uv run python -c "import httpx; print(httpx.get('http://127.0.0.1:8010/price/rice', timeout=10).json())"After a one-second pause it prints {'item': 'rice', 'price': 519}.
Step 3 · Fetch the prices one after another
Start with the plain version, so you have a number to beat. sequential.py uses the normal httpx.Client and asks for each item in turn:
cat > sequential.py <<'PY'
import time
import httpx
from common import BASE_URL, ITEMS
def main():
started = time.perf_counter()
prices = {}
with httpx.Client(base_url=BASE_URL, timeout=10.0) as client:
for item in ITEMS:
response = client.get(f"/price/{item}")
response.raise_for_status()
prices[item] = response.json()["price"]
elapsed = time.perf_counter() - started
print(f"fetched {len(prices)} prices in {elapsed:.1f} s")
main()
PYRun it and wait:
uv run sequential.pyEach client.get blocks the whole program until its answer arrives. Nothing else can happen during those 20 one-second waits, even though the computer is idle.
Check it worked
After about 20 seconds the script prints fetched 20 prices in 20.1 s, or a figure a little above 20.
Step 4 · Fetch them all at once with a TaskGroup
Now the async version. Three pieces change:
async defmakes a coroutine function. Calling it does not run it; it gives you a coroutine that runs when something awaits it or wraps it in a task.awaitmarks the places where the coroutine may pause. While one request waits for the network, the event loop runs the others.asyncio.TaskGroupstarts each coroutine as a task and, at the end of itsasync withblock, waits until every task has finished.
cat > all_at_once.py <<'PY'
import asyncio
import time
import httpx
from common import BASE_URL, ITEMS
async def fetch_price(client, item):
response = await client.get(f"/price/{item}")
response.raise_for_status()
return response.json()["price"]
async def main():
started = time.perf_counter()
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as client:
async with asyncio.TaskGroup() as group:
tasks = {item: group.create_task(fetch_price(client, item)) for item in ITEMS}
prices = {item: task.result() for item, task in tasks.items()}
elapsed = time.perf_counter() - started
print(f"fetched {len(prices)} prices in {elapsed:.1f} s")
print("rice costs", prices["rice"])
asyncio.run(main())
PYuv run all_at_once.pyasyncio.run(main()) creates the event loop, runs main until it returns and closes the loop. The dictionary keeps each task next to its item, and task.result() reads the return value once the group has finished. One thread does all of this: asyncio does not make Python compute faster, it stops it from sitting idle.
The file is called all_at_once.py, not concurrent.py, for a reason: Python puts the script's folder first on its import path, so a script named after a standard library module (asyncio, concurrent, http, json and so on) hides the real one, and import asyncio breaks with 'concurrent' is not a package.
A common slip is to forget an await. Write response = client.get(...) inside a coroutine and response is a coroutine object, not a response, so the next line fails with an AttributeError, and Python warns that a coroutine "was never awaited". When you see that warning, look for the missing await.
Check it worked
The script prints fetched 20 prices in 1.0 s (a figure between 1.0 and about 1.3 is normal) and rice costs 519. Same work, roughly a twentieth of the time.
Step 5 · Put a deadline on the whole batch
The timeout=10.0 on the client limits each phase of each request. It does not limit the batch: twenty requests that each take nine seconds would all succeed and still keep a user waiting. asyncio.timeout sets one deadline around any block of async code. When it expires, it cancels what is still running inside and raises TimeoutError.
cat > deadline.py <<'PY'
import asyncio
import httpx
from common import BASE_URL, ITEMS
async def fetch_price(client, item):
response = await client.get(f"/price/{item}")
response.raise_for_status()
return response.json()["price"]
async def fetch_all(client, seconds):
async with asyncio.timeout(seconds):
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(fetch_price(client, item)) for item in ITEMS]
return [task.result() for task in tasks]
async def main():
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as client:
try:
await fetch_all(client, 0.5)
except TimeoutError:
print("0.5 s deadline: gave up with TimeoutError")
prices = await fetch_all(client, 5)
print(f"5 s deadline: got {len(prices)} prices")
asyncio.run(main())
PYuv run deadline.pyHalf a second is shorter than the API's one-second delay, so the first batch is cancelled. The second has plenty of time. In a web app, a deadline like this is how you keep a page fast when a service behind it is struggling: show what you have, or an error, instead of hanging.
Check it worked
The output is 0.5 s deadline: gave up with TimeoutError, then about a second later 5 s deadline: got 20 prices. The second terminal may print a BrokenPipeError or ConnectionResetError traceback: that is the stand-in API trying to answer requests the client already abandoned, and it is harmless.
Step 6 · Limit how many requests run at once
Firing every request at once is fine for 20. For 2,000 it can overload the service, trip its rate limit or use up your own connections. An asyncio.Semaphore is a counter of free slots: async with gate: takes a slot, or waits until one is free, and gives it back at the end of the block. This version allows five requests at a time and records the most it ever saw running together:
cat > limited.py <<'PY'
import asyncio
import time
import httpx
from common import BASE_URL, ITEMS
LIMIT = 5
running = 0
busiest = 0
async def fetch_price(client, gate, item):
global running, busiest
async with gate:
running += 1
busiest = max(busiest, running)
try:
response = await client.get(f"/price/{item}")
response.raise_for_status()
return response.json()["price"]
finally:
running -= 1
async def main():
gate = asyncio.Semaphore(LIMIT)
started = time.perf_counter()
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as client:
async with asyncio.TaskGroup() as group:
for item in ITEMS:
group.create_task(fetch_price(client, gate, item))
elapsed = time.perf_counter() - started
print(f"fetched {len(ITEMS)} prices in {elapsed:.1f} s, at most {busiest} at once")
asyncio.run(main())
PYuv run limited.pyThe plain global counters are safe here because every task runs on the same thread and can only be interrupted at an await, never in the middle of running += 1. httpx can also cap connections at the pool level with httpx.AsyncClient(limits=httpx.Limits(max_connections=5)); its default is 100. The semaphore is more flexible, because it can wrap any work, such as a request plus the database write that follows it.
Check it worked
The script prints fetched 20 prices in 4.0 s, at most 5 at once. Twenty requests in groups of five take four rounds of one second. Change LIMIT to 10 and run it again: it takes about two seconds and reports at most 10 at once.
Step 7 · Watch one failure cancel the rest
When one task in a TaskGroup raises an exception, the group cancels every other task still running, waits for them to stop, and raises an ExceptionGroup holding the errors. That is usually what you want: if one part of a page fails, there is no point finishing the rest in the background. except* catches the errors of one type from inside the group:
cat > failure.py <<'PY'
import asyncio
import time
import httpx
from common import BASE_URL, ITEMS
finished = []
async def fetch_price(client, item):
response = await client.get(f"/price/{item}")
response.raise_for_status()
finished.append(item)
return response.json()["price"]
async def main():
started = time.perf_counter()
async with httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) as client:
try:
async with asyncio.TaskGroup() as group:
for item in ITEMS + ["broken"]:
group.create_task(fetch_price(client, item))
except* httpx.HTTPStatusError as errors:
for error in errors.exceptions:
print("failed:", error.request.url.path, error.response.status_code)
elapsed = time.perf_counter() - started
print(f"finished before the failure: {len(finished)}")
print(f"stopped after {elapsed:.1f} s")
asyncio.run(main())
PYuv run failure.pybroken fails after 0.2 seconds, while the other 20 requests are still waiting for their one-second answers. They are cancelled, so none of them reaches finished.append. errors is itself an ExceptionGroup, and errors.exceptions lists each error in it, so two failures would print two lines. Any error that is not an HTTPStatusError, such as a refused connection, is not caught by this clause and goes on up.
Remove the try and except* lines (and dedent the block) and the traceback ends with something like ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception), with the original HTTPStatusError printed inside it. When you would rather keep the prices that did arrive, catch the error inside fetch_price and return None, or use asyncio.gather(..., return_exceptions=True), which collects errors as results and does not cancel anything.
Check it worked
The output is failed: /price/broken 500, finished before the failure: 0 and stopped after 0.2 s. The program stopped in a fifth of a second, not one. As in the deadline step, the stand-in API terminal may print BrokenPipeError or ConnectionResetError tracebacks for the 20 cancelled requests; the server is fine.
Step 8 · Fix blocking code inside a coroutine
asyncio only overlaps waits that await. A function that blocks, such as time.sleep, requests.get or the normal httpx.get, holds the one thread until it returns, and every other task freezes with it. The code still runs and still gives the right answer, so the mistake is easy to miss. asyncio.to_thread runs a blocking function in a worker thread and gives you something to await:
cat > blocking.py <<'PY'
import asyncio
import time
import httpx
from common import BASE_URL, ITEMS
def fetch_price_blocking(item):
# Stands in for any synchronous library: requests, an old SDK, a database driver.
response = httpx.get(f"{BASE_URL}/price/{item}", timeout=10.0)
response.raise_for_status()
return response.json()["price"]
async def wrong(item):
return fetch_price_blocking(item)
async def right(item):
return await asyncio.to_thread(fetch_price_blocking, item)
async def timed(label, worker):
started = time.perf_counter()
async with asyncio.TaskGroup() as group:
for item in ITEMS[:5]:
group.create_task(worker(item))
elapsed = time.perf_counter() - started
print(f"{label}: 5 prices in {elapsed:.1f} s")
async def main():
await timed("blocking call in a coroutine", wrong)
await timed("same call in asyncio.to_thread", right)
asyncio.run(main())
PYuv run blocking.pyThe first five run one after another although they sit in a TaskGroup, because none of them ever reaches an await that yields to the loop. The same rule applies to pauses: inside a coroutine use await asyncio.sleep(1), never time.sleep(1). Reach for to_thread when a library has no async version; prefer a native async client, such as httpx.AsyncClient, when one exists, because a thread per call costs more than a task.
To catch blocking calls in your own code, turn on asyncio's debug mode. It logs any step that holds the event loop for more than 100 milliseconds:
PYTHONASYNCIODEBUG=1 uv run blocking.pyCheck it worked
The first run prints blocking call in a coroutine: 5 prices in 5.0 s and then same call in asyncio.to_thread: 5 prices in 1.0 s. With debug mode on, warnings like Executing <Task ...> took 1.004 seconds appear for the blocking version only.
Step 9 · Clean up
Stop the stand-in API with Ctrl+C in the second terminal. Then remove the demo project. Python and uv stay installed:
cd ~
rm -rf ~/asyncio-demoCheck it worked
ls ~/asyncio-demo reports that there is no such file or directory, and http://127.0.0.1:8010 no longer answers.
Next steps
- Compare asyncio with threads and processes, and see when each one helps: speed up Python with threads and processes.
- The same idea in JavaScript, where the event loop is built in: wait for slow work with promises and async/await.
- Go back over timeouts, errors and the reusable client for single calls: call a web API from Python with httpx.
- Test async code without a live API: test Python code with pytest.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials