Alex Rivera | Logout

Python asyncio.TaskGroup vs gather: when to use which in production?

Asked 2025-07-22T13:08:00Z by Alex Rivera
41
Python 3.11 introduced TaskGroup as a structured concurrency primitive. I'm refactoring a microservice that heavily uses asyncio.gather. The TaskGroup context manager feels cleaner but I'm not sure about the error propagation differences in production. Does TaskGroup always cancel sibling tasks on first exception?
Edit
Report

1 Answer

39
The critical difference is structured vs unstructured concurrency. With asyncio.gather, if task 2 raises and you don't use return_exceptions, tasks 1 and 3 are left dangling - they're still running but nobody's awaiting them. TaskGroup fixes this by cancelling all sibling tasks when one fails, which is almost always what you want in production. The one case where gather still wins: fire-and-forget fan-out where you genuinely don't care about failures in individual tasks.
answered 2025-07-22T16:42:00Z by Marcus Chen

Your Answer