Stop Using asyncio: Why TaskGroups Changed Python 3.13

By Geekery Team · · 6 min read

Stop using asyncio is too blunt: asyncio remains the event loop that powers modern Python services. But if your Python 3.13 code still relies on asyncio.gather(), naked create_task() calls and hand-written cancellation logic, you are using the wrong abstraction. TaskGroups give Python developers structured concurrency with automatic cancellation and reliable error propagation. That is the change that matters.

The target keyword for this article is simple: Stop using asyncio: why TaskGroups changed the game for Python 3.13. The practical argument is not that async Python became obsolete. It is that Python 3.13 gives us a better way to manage the lifetime of concurrent work, and most teams should adopt it before adding another retry wrapper or callback.

Why asyncio.gather() is the wrong default

asyncio.gather() is convenient because it accepts awaitables and returns their results in order. That convenience hides the lifecycle problem. When one task raises, gather does not automatically cancel its siblings. The failing task completes, while the others keep running until the caller eventually handles them. In a web request handler, that can mean background work continuing after a timeout or a response has already been sent.

Many Python services compensate with a mixture of asyncio.wait_for(), asyncio.shield(), explicit task lists and done_callbacks. Each workaround solves a small edge case. Together they make failure behaviour difficult to reason about, especially under load. A BBC-style streaming pipeline or an NHS Digital integration worker should not need to implement a mini task supervisor every time it calls three services concurrently.

This is why the advice should be precise: stop using asyncio as an unstructured collection of tasks, not stop using async Python. Use one construct that owns the child tasks, reports the first failure and tears down the rest.

TaskGroups make task ownership explicit

asyncio.TaskGroup was introduced in Python 3.11 and remains a major reason to prefer modern Python 3.13 deployments. It creates a scope for child tasks and guarantees that the scope does not exit until every child has finished. If a child raises an unhandled exception, the group cancels the remaining children and then raises an ExceptionGroup.

import asyncio

async def fetch_user(user_id: int) -> dict:
    await asyncio.sleep(0.1)
    return {"id": user_id, "status": "active"}

async def fetch_account(account_id: int) -> dict:
    await asyncio.sleep(0.1)
    return {"id": account_id, "kind": "customer"}

async def load_customer(customer_id: int) -> tuple[dict, dict]:
    async with asyncio.TaskGroup() as group:
        user_task = group.create_task(fetch_user(customer_id))
        account_task = group.create_task(fetch_account(customer_id))

    return user_task.result(), account_task.result()

async def main() -> None:
    user, account = await load_customer(42)
    print(user, account)

asyncio.run(main())

The important detail is the async with block. It is a scope, not merely a convenience wrapper. The group waits on exit, propagates failures and handles cancellation. You do not call asyncio.gather(), and you do not manually cancel sibling tasks after an exception.

For production code, define tasks inside the TaskGroup and keep the result objects outside it so they can be read after the block. Do not use create_task() without a group. The whole value of the abstraction is that the parent owns the children.

Handling expected failures without hiding them

TaskGroups are deliberately strict. If one child fails, the group cancels siblings and raises an ExceptionGroup. That is usually the correct behaviour, but it means your exception handling needs to match. Catch ExceptionGroup at the boundary, inspect the individual exceptions and translate them into an application error.

import asyncio

class UpstreamUnavailable(Exception):
    pass

async def call_upstream() -> str:
    raise UpstreamUnavailable("upstream returned 503")

async def call_fallback() -> str:
    await asyncio.sleep(0.05)
    return "cached response"

async def fetch_value() -> str:
    try:
        async with asyncio.TaskGroup() as group:
            group.create_task(call_upstream())
            group.create_task(call_fallback())
    except* UpstreamUnavailable:
        return await call_fallback()

    raise RuntimeError("unreachable")

Use except* when you want to handle one exception type while allowing others to propagate. Avoid catching a broad ExceptionGroup and printing it during a request; that hides the original failure from logs and monitoring. In a GOV.UK-facing service, record the exception chain, request ID and endpoint, then let your framework return the appropriate status code.

What changes for Python 3.13 teams

Python 3.13 continues the standard library's move toward explicit, cancellable concurrency. The main upgrade work is not a new API migration; it is changing how teams write task boundaries. Replace scattered create_task() calls with TaskGroups, then remove cleanup code that only existed because gather left tasks running.

Start by searching for asyncio.gather(, asyncio.create_task( and ensure_future(. For each hit, identify the owner of the task. If the owner is the current coroutine, put the task in a TaskGroup. If it genuinely needs to outlive the current scope, make that explicit and give it its own lifecycle, cancellation policy and observability. Do not use a fire-and-forget task as a substitute for designing background work.

TaskGroups also improve shutdown semantics. A service receiving a termination signal can cancel its request coordinator, which can cancel children through the group. That gives you a cleaner path to draining work than a pile of finally blocks around individual tasks. In a containerised deployment, this matters because SIGTERM handling is not optional: Kubernetes sends termination signals, and Python applications need time to stop cleanly.

Do not expect TaskGroups to solve timeouts, retries or rate limits. Those still need explicit policy. Wrap each operation with asyncio.timeout(), use a retry library with jitter, and make cancellation visible in your logs. TaskGroups provide the concurrency boundary; they do not decide business behaviour.

Where TaskGroups still need care

The first trap is assuming every task fails at the same time. A task may finish successfully before another child raises. The group still cancels any unfinished siblings, but completed results are available through the task objects. If partial success matters, keep the tasks and inspect their outcomes deliberately.

The second trap is catching exceptions inside child coroutines and returning None. That suppresses failure and makes the group look successful. If a failure is expected, model it in the return type or raise a specific exception. If it is recoverable, handle it locally, but record enough context to diagnose it.

The third trap is mixing TaskGroups with unbounded fan-out. Creating 10,000 child tasks can consume substantial memory and overwhelm an upstream API. A TaskGroup is a structured lifetime tool, not a queue or a bulkhead. Put a limit around the work, use a worker pool, or batch requests. Monzo-style systems and high-volume HMRC integrations should treat concurrency limits as part of correctness, not an optimisation added later.

Finally, test cancellation. Add a unit test where one child raises while another is sleeping, then assert that the sibling was cancelled and no task remains pending. That test catches more real bugs than checking only the happy path.

The practical migration rule

For new Python 3.13 code, use asyncio.TaskGroup whenever you need concurrent child operations with a shared lifetime. Keep asyncio.gather() for the rare cases where independent results are genuinely all required, you do not need failure cancellation and you have considered the lifecycle. Do not use it as the default reflex.

The strongest pattern is boring: one parent scope, named child tasks, explicit timeout handling, narrow exception translation and tests for cancellation. That is a better foundation for a Python service than adding another layer of callbacks around an unstructured task list.

Three questions teams should ask

What owns each background task? If the answer is a local variable and nobody else, use a TaskGroup. If the work must survive the request, design a queue or job service with durable state instead of leaving a coroutine in memory.

What happens when one concurrent operation fails? With a TaskGroup, siblings are cancelled and the failure is raised as an ExceptionGroup. Make sure your handler preserves the cause and does not silently return partial data.

Are timeouts and retries separate from task ownership? They should be. A timeout limits one operation; a retry policy decides whether to try again; the TaskGroup guarantees that the whole concurrent scope exits cleanly. Combining all three into one helper makes failures harder to explain and harder to test.