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:
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:
With return_exceptions=True, exceptions come back as values in the results list instead of being raised:
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.
Completion conditions
| Condition | Behavior |
asyncio.ALL_COMPLETED | Wait for every task to finish (default) |
asyncio.FIRST_COMPLETED | Return as soon as any one task finishes |
asyncio.FIRST_EXCEPTION | Return 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:
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.
Catching failures with except*
When a task fails, the group cancels the others, waits for the cancellation to finish, then raises an ExceptionGroup:
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
| Feature | asyncio.gather | asyncio.wait | asyncio.TaskGroup |
| Python version | 3.4+ | 3.4+ | 3.11+ |
| Input type | Coroutines or futures | Tasks or futures | Created via tg.create_task() |
| Result order | Preserved (matches input) | Unordered sets | Access via task.result() |
| Exception default | Propagates first exception | No auto-propagation | Cancels all, raises ExceptionGroup |
| Partial completion | Not supported | FIRST_COMPLETED, timeout | Not supported |
| Orphaned task risk | Yes, on exception | Yes, if pending not cancelled | No, structured guarantee |
| Cancellation | Cancels all if gather cancelled | Manual per-task | Automatic on exception |
| Best for | Fan-out, collect all results | Race conditions, timeouts | Safety-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.
Related reading
- asyncio.run cannot be called from a running event loop when using Jupyter Notebook
- asyncio.sleep vs time.sleep
- AsyncOperation Reading and Writing
- Async.Start vs Async.StartChild
- AttributeError __enter__ from with tf.Session as sess
- AttributeError 'Adam' object has no attribute 'build' during unpickling
- AsyncTask threads never die
- Asynctask vs Thread in android
Course lessons on this
System design interview problems on this topic
- Design a Distributed Locking System: solution and walkthrough
- Design a Distributed Counter: solution and walkthrough
- Design Ticketmaster: solution and walkthrough
- Design a Flash Sale System: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseInterview Questions practice on Codemia
Over 11,000 interview practice questions for 300+ companies, searchable by company and role.