Coroutines, Tasks and Task Groups
Turn a slow sequential aggregation endpoint into a fan-out with asyncio.TaskGroup, keep results you can trust, and choose between a task group and gather when one upstream call fails.
Contentsand lesson path
On this page
- The problem
- Step 1: the sequential baseline, measured
- Step 2: fan out with a task group
- Step 3: one service is down
- Mistakes to watch for
- Check your understanding
- Apply it
- Review prompt
Lessons of Async I/O in Python
- Concurrency for I/O: The Event Loop Mental Model Concept · 20 min
- Coroutines, Tasks and Task Groups Worked example · 25 min
- Timeouts, Cancellation and Bounded Concurrency Worked example · 20 min
- Lab: Find the Call That Blocks the Loop Lab · 25 min
- Check: Sequential, Concurrent or Blocked? Knowledge check · 6 questions
What you will learn
- Explain how the event loop schedules coroutines and predict whether a piece of async code runs concurrently or sequentially.
- Run concurrent I/O with task groups or gather, bounding concurrency with a semaphore and applying timeouts and cancellation.
Prerequisites: Python Foundations
01. The problem
A reading-list service has a /summary endpoint that merges three upstream services: book information (about 0.20 s), reviews (about 0.40 s) and cover images (about 0.60 s). None of them needs the others' results, yet the current endpoint awaits them one at a time, so every request pays the full 1.2 s. The target is the slowest call, not the sum, and a clear story for what happens when one service is down.
You already know from the event loop lesson that overlapping waits needs several suspendable pieces in flight. This lesson is the practical version: start work with tasks, collect it with a task group, and decide the failure contract. The examples use a tiny local upstream you can run yourself, and every output below comes from a real run against it (Python 3.12.13, FastAPI 0.163.1, uvicorn 0.54.0, httpx 0.28.1). Timings move by some milliseconds between machines and runs, so those blocks are marked illustrative; the pattern, sum of the waits against the slowest wait, is what you should see.
"""Three slow services and one flaky, on a single FastAPI app."""
import asyncio
from fastapi import FastAPI, HTTPException
app = FastAPI()
SERVICES = {"a": 0.20, "b": 0.40, "c": 0.60}
@app.get("/services/{name}")
async def service(name: str, d: float | None = None) -> dict:
delay = SERVICES.get(name, 0.10) if d is None else d
await asyncio.sleep(delay)
return {"service": name, "delay": delay,
"items": [f"{name}-1", f"{name}-2"]}
@app.get("/flaky")
async def flaky() -> dict:
await asyncio.sleep(0.30)
raise HTTPException(status_code=500, detail="upstream exploded")uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python fastapi==0.163.1 uvicorn==0.54.0 httpx==0.28.1
.venv/bin/uvicorn upstream:app --host 127.0.0.1 --port 813702. Step 1: the sequential baseline, measured
import asyncio
import time
import httpx
BASE = "http://127.0.0.1:8137"
PATHS = ("/services/a", "/services/b", "/services/c")
async def main() -> None:
async with httpx.AsyncClient() as client:
await client.get(f"{BASE}/services/warmup") # open the pool
start = time.perf_counter()
results = {}
for path in PATHS:
response = await client.get(f"{BASE}{path}")
results[path] = response.json()["items"]
elapsed = time.perf_counter() - start
print(f"collected {len(results)} services in {elapsed:.2f} s")
print(f"results keys: {sorted(results)}")
asyncio.run(main())collected 3 services in 1.21 s
results keys: ['/services/a', '/services/b', '/services/c']About 1.2 s: the three waits (0.20 + 0.40 + 0.60 s) queued up, plus a few milliseconds of HTTP work per call, exactly as the mental model predicts. Two details are worth keeping. An httpx.AsyncClient is used as an async context manager so its connections are opened once and closed properly; the HTTP API skill shows the same pattern. And the warm-up request before the timer is deliberate: without it, the first timed call also pays for setting up the connection pool, which would muddy the comparison you are about to make. A measured baseline earns you the right to claim an improvement later.
03. Step 2: fan out with a task group
import asyncio
import time
import httpx
BASE = "http://127.0.0.1:8137"
PATHS = ("/services/a", "/services/b", "/services/c")
async def fetch(client: httpx.AsyncClient, path: str) -> dict:
response = await client.get(f"{BASE}{path}")
response.raise_for_status()
return response.json()
async def fan_out(client: httpx.AsyncClient,
paths: tuple[str, ...]) -> dict:
results: dict[str, dict] = {}
async with asyncio.TaskGroup() as tg:
tasks = {path: tg.create_task(fetch(client, path))
for path in paths}
for path, task in tasks.items():
results[path] = task.result()
return results
async def main() -> None:
async with httpx.AsyncClient() as client:
await client.get(f"{BASE}/services/warmup") # open the pool
start = time.perf_counter()
results = await fan_out(client, PATHS)
elapsed = time.perf_counter() - start
print(f"collected {len(results)} services in {elapsed:.2f} s")
print(f"results keys: {sorted(results)}")
asyncio.run(main())collected 3 services in 0.61 s
results keys: ['/services/a', '/services/b', '/services/c']About 0.6 s: the length of the slowest call, half the baseline. Reading it line by line: tg.create_task(...) wraps each fetch(...) coroutine in a task and schedules it, which means the task is queued to start, not run on the spot. The comprehension creates all three before any of them sends a request. When fan_out reaches the end of the async with asyncio.TaskGroup() block, it suspends there, the loop starts the three tasks, and the requests go out together. The block then waits until every child task has finished; leaving the block is your proof that all results exist, which is why task.result() afterwards is safe.
Note what the group does not give you: a collected list. You keep the task objects (here in a dict keyed by path) and ask each one for its result. Because you read results by key rather than by completion order, a fast service answering before a slow one cannot scramble your data. The older asyncio.gather does collect for you and returns values in input order, whatever order they finished in; both tools are fine, and the next step is about the difference that actually matters.
Task groups arrived in Python 3.11 as the recommended structure for this pattern, sometimes called structured concurrency: every child task is created inside a block, and the block does not exit until its children have finished, so no work leaks out and keeps running unattended. Older code you read will use asyncio.gather for the same job, and older still asyncio.ensure_future. You may also meet eager tasks (Python 3.12 and later, opt-in through asyncio.eager_task_factory), which run a new task's first steps inside create_task itself, up to its first real wait; the default is still the queued behaviour described above. The mental model transfers: start everything, wait for everything, and be explicit about the failure story.
04. Step 3: one service is down
Reviews now fails with a 500 after 0.30 s. The two tools react differently, and you should choose between them on purpose. The script below runs both against ("/services/a", "/flaky", "/services/c"):
import asyncio
import time
import httpx
BASE = "http://127.0.0.1:8137"
PATHS = ("/services/a", "/flaky", "/services/c")
async def fetch(client: httpx.AsyncClient, path: str) -> dict:
response = await client.get(f"{BASE}{path}")
response.raise_for_status()
return response.json()
async def with_task_group(client: httpx.AsyncClient) -> None:
print("task group: start", flush=True)
start = time.perf_counter()
try:
async with asyncio.TaskGroup() as tg:
for path in PATHS:
tg.create_task(fetch(client, path))
except* httpx.HTTPStatusError as group:
elapsed = time.perf_counter() - start
statuses = [e.response.status_code for e in group.exceptions]
print(f"task group: aborted after {elapsed:.2f} s, status {statuses}")
async def with_gather(client: httpx.AsyncClient) -> None:
print("gather: start", flush=True)
start = time.perf_counter()
outcomes = await asyncio.gather(
*(fetch(client, path) for path in PATHS),
return_exceptions=True,
)
elapsed = time.perf_counter() - start
summary = [type(o).__name__ if isinstance(o, Exception)
else "dict" for o in outcomes]
print(f"gather: finished after {elapsed:.2f} s, outcomes {summary}")
async def main() -> None:
async with httpx.AsyncClient() as client:
await client.get(f"{BASE}/services/warmup") # open the pool
await with_task_group(client)
await with_gather(client)
asyncio.run(main())task group: start
task group: aborted after 0.32 s, status [500]
gather: start
gather: finished after 0.61 s, outcomes ['dict', 'HTTPStatusError', 'dict']The task group treats one failure as fatal for the group: it cancels the siblings (poor /services/c, still 0.3 s from finishing) and raises an ExceptionGroup, which the except* form catches for just the exception types you name. Nothing partial leaks out, and you stop paying for a response you will not use. That is the right contract when the endpoint only makes sense complete.
gather(return_exceptions=True) instead lets every call finish and hands you the outcomes in order, with exception objects sitting in the list exactly where their values would have been. It waited for the slowest call, about 0.6 s, but it has the book information and the covers, and can serve a summary marked "reviews unavailable". That is the right contract when partial is better than nothing. (Plain gather without that flag is the awkward middle: it raises the first error but leaves the other calls running — reach for one of the two deliberate options instead.)
Translated into an endpoint, the contract choice becomes a status-code choice: the task-group version fails the whole response, while the gather version can answer 200 OK with a body that marks the missing piece. The API design skill covers how to signal partial success to clients; here it is enough to make the choice visible in your code rather than accidental.
05. Mistakes to watch for
06. Check your understanding
07. Apply it
Run the upstream and write the /summary endpoint from the practice for this skill: fan out to three slow services with one shared httpx.AsyncClient, measure the total, then break one service (add a /flaky route like the one above) and pick the failure contract deliberately — all-or-nothing with a task group, or partial with gather(return_exceptions=True).
Log both timings the way step 1 did. You have not finished until a reader of your log can tell, without seeing the code, whether the calls overlapped and what happened to the failed one.
08. Review prompt
From memory: write the shape of a fan-out with a task group that stores tasks in a dict and reads results after the block. Then explain to a colleague in three sentences why a task group aborted after about 0.3 s while gather with return_exceptions=True ran for about 0.6 s, and when each behaviour is the one you want.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.