Menu

asyncio.gather Raised an Exception but the Other Tasks Kept Running: TaskGroup vs return_exceptions
📰

asyncio.gather Raised an Exception but the Other Tasks Kept Running: TaskGroup vs return_exceptions

DEV Community: backend·Libme·1 day ago
#PqPG9UW5
#devtobackend#devto#dev#asyncio#task
Reading 0:00
15s threshold

If one coroutine in asyncio.gather() raises, the exception propagates to your await , but the sibling tasks are not cancelled . They keep running in the background, still holding connections and still writing. Since Python 3.11, asyncio.TaskGroup fixes this: the first failure cancels the siblings, and you handle the result as an ExceptionGroup . Use gather(..., return_exceptions=True) only when you genuinely want every result, failures included.

What actually happens when gather fails?

The symptom usually shows up as a "ghost" side effect: a request handler returns a 500, yet a database row or an outbound API call from a sibling coroutine still lands a second later. Here is a minimal reproduction:

import asyncio

async def worker ( name : str , delay : float , fail : bool = False ) -> None : try : await asyncio . sleep ( delay ) if fail : raise RuntimeError ( f "{name} failed" ) print ( f "{name} finished" ) except asyncio .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.