asyncio
Python
concurrency
asyncio.gather
asyncio.wait

asyncio.gather vs asyncio.wait vs asyncio.TaskGroup in Python

Codemia Knowledge Hub ·

Use asyncio.gather to run coroutines concurrently and get their results back in input order. Use asyncio.wait when you need control over when to stop waiting (first result, first exception, or a timeout). Use asyncio.TaskGroup (Python 3.11+) for structured concurrency: every task finishes before the async with block exits, and one failure cancels the rest. Picking the wrong one leads to lost exceptions, orphaned tasks or needlessly complex code.

asyncio.gather: ordered results

gather takes coroutines or futures, runs them concurrently and returns a list of results in the order they were passed:

python
1import asyncio
2
3async def fetch_user(user_id):
4    await asyncio.sleep(0.5)  # simulate network call
5    return {"id": user_id, "name": f"User {user_id}"}
6
7async def main():
8    results = await asyncio.gather(
9        fetch_user(1),
10        fetch_user(2),
11        fetch_user(3),
12    )
13    for user in results:
14        print(user)
15
16asyncio.run(main())

The order matches the input regardless of which coroutine finished first, which makes gather the natural fit for "fan out, collect all", such as calling several API endpoints in parallel.

How gather handles exceptions

By default, the first exception propagates immediately. The other coroutines keep running in the background, but their results are lost:

python
1async def failing_task():
2    raise ValueError("something broke")
3
4async def main():
5    try:
6        results = await asyncio.gather(
7            fetch_user(1),
8            failing_task(),
9            fetch_user(3),
10        )
11    except ValueError as e:
12        print(f"Caught: {e}")
13        # results from fetch_user(1) and fetch_user(3) are NOT available
14
15asyncio.run(main())

With return_exceptions=True, exceptions come back as values in the results list instead of being raised:

python
1results = await asyncio.gather(
2    fetch_user(1),
3    failing_task(),
4    fetch_user(3),
5    return_exceptions=True,
6)
7# results[0] = {"id": 1, "name": "User 1"}
8# results[1] = ValueError("something broke")
9# results[2] = {"id": 3, "name": "User 3"}

asyncio.wait: done and pending sets

wait returns two sets, done and pending, based on a completion condition. Pass it asyncio.Task objects or futures, not bare coroutines: passing coroutines was deprecated in Python 3.8 and raises TypeError since Python 3.11. Wrap them with asyncio.create_task() first.

python
1import asyncio
2
3async def fetch_price(exchange, symbol):
4    delay = {"binance": 0.3, "coinbase": 0.8, "kraken": 1.2}
5    await asyncio.sleep(delay.get(exchange, 1.0))
6    return {"exchange": exchange, "symbol": symbol, "price": 42000.0}
7
8async def main():
9    tasks = [
10        asyncio.create_task(fetch_price("binance", "BTC")),
11        asyncio.create_task(fetch_price("coinbase", "BTC")),
12        asyncio.create_task(fetch_price("kraken", "BTC")),
13    ]
14
15    # Return as soon as the first exchange responds
16    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
17
18    for task in done:
19        print("First result:", task.result())
20
21    # Cancel the rest since we only needed one
22    for task in pending:
23        task.cancel()
24
25asyncio.run(main())

Completion conditions

ConditionBehavior
asyncio.ALL_COMPLETEDWait for every task to finish (default)
asyncio.FIRST_COMPLETEDReturn as soon as any one task finishes
asyncio.FIRST_EXCEPTIONReturn when the first task raises an exception, or when all complete if none raise

wait also takes a timeout. When it expires, finished tasks go into done and the rest into pending:

python
done, pending = await asyncio.wait(tasks, timeout=2.0)
print(f"{len(done)} completed, {len(pending)} still running")

After FIRST_COMPLETED or a timeout, cancel the pending tasks you no longer need, or they keep running in the background and consuming resources.

wait never raises for you

asyncio.wait does not raise task exceptions automatically. Call task.result() on each completed task to get its result or re-raise its exception. That gives full control but needs careful handling.

asyncio.TaskGroup: structured concurrency

TaskGroup, added in Python 3.11, guarantees that every task created in the group is awaited before the async with block exits. If any task raises, the remaining tasks are cancelled and the error is re-raised as an ExceptionGroup.

python
1import asyncio
2
3async def process_order(order_id):
4    await asyncio.sleep(0.5)
5    print(f"Order {order_id} processed")
6    return order_id
7
8async def main():
9    async with asyncio.TaskGroup() as tg:
10        task1 = tg.create_task(process_order(101))
11        task2 = tg.create_task(process_order(102))
12        task3 = tg.create_task(process_order(103))
13
14    # All tasks are guaranteed complete here
15    print(task1.result(), task2.result(), task3.result())
16
17asyncio.run(main())

Catching failures with except*

When a task fails, the group cancels the others, waits for the cancellation to finish, then raises an ExceptionGroup:

python
1async def risky_task(task_id):
2    if task_id == 2:
3        raise RuntimeError(f"Task {task_id} failed")
4    await asyncio.sleep(0.5)
5    return task_id
6
7async def main():
8    try:
9        async with asyncio.TaskGroup() as tg:
10            tg.create_task(risky_task(1))
11            tg.create_task(risky_task(2))
12            tg.create_task(risky_task(3))
13    except* RuntimeError as eg:
14        for exc in eg.exceptions:
15            print(f"Caught: {exc}")
16
17asyncio.run(main())

except* (Python 3.11+) matches specific exception types inside the group. This avoids the gather problem where one failure leaves the other tasks orphaned. A plain except Exception also catches the ExceptionGroup, but you lose the per-exception structure. The exceptiongroup backport package exists for older Pythons, but TaskGroup itself requires 3.11+.

Comparison table

Featureasyncio.gatherasyncio.waitasyncio.TaskGroup
Python version3.4+3.4+3.11+
Input typeCoroutines or futuresTasks or futuresCreated via tg.create_task()
Result orderPreserved (matches input)Unordered setsAccess via task.result()
Exception defaultPropagates first exceptionNo auto-propagationCancels all, raises ExceptionGroup
Partial completionNot supportedFIRST_COMPLETED, timeoutNot supported
Orphaned task riskYes, on exceptionYes, if pending not cancelledNo, structured guarantee
CancellationCancels all if gather cancelledManual per-taskAutomatic on exception
Best forFan-out, collect all resultsRace conditions, timeoutsSafety-critical concurrent work

Which one to use

asyncio.gather when you need all results in order and failures are unlikely, or acceptable to handle with return_exceptions=True. This covers most "call N endpoints in parallel" code.

asyncio.wait when you need partial results, race semantics (first response wins) or timeout-based completion, such as health checks, competing fetches or progress monitoring.

asyncio.TaskGroup when task cleanup matters. Code that starts tasks inside a request handler, a transaction or a resource scope should use it to avoid orphaned coroutines leaking memory or database connections. For new code on Python 3.11+, prefer it over gather whenever task lifecycle matters.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Interview Questions practice on Codemia

Over 11,000 interview practice questions for 300+ companies, searchable by company and role.

Browse interview questions