Structured concurrency with asyncio.TaskGroup

suggest change

asyncio.TaskGroup (Python 3.11+) is an async context manager that owns a set of tasks. You start tasks with tg.create_task() inside an async with block, and when the block exits every one of those tasks has finished. If one of them fails, the group cancels the rest and reports the error.

This is called structured concurrency: the lifetime of concurrent tasks is tied to a block of code, the same way a with open(...) block ties the lifetime of a file to it. You never end up with a background task that nobody awaits, whose exception is lost, or that keeps running after the function that started it has returned.

asyncio.gather() asyncio.TaskGroup
Available since 3.4 3.11
On first failure raises it; other tasks keep running cancels the other tasks, waits for them, then raises
Several failures only the first is raised all of them, in an ExceptionGroup
Adding tasks later no, the list is fixed yes, any task can call tg.create_task()
Results list in argument order task.result() on each task

All examples were run with Python 3.13 unless the text says otherwise. For timeouts around a group and the details of task cancellation see Cancellation and timeouts; for async/await basics see Coroutine Syntax.

Basic usage

Create the group with async with, start tasks with tg.create_task(), and read the results after the block:

import asyncio
import time

async def fetch(name, delay):
    await asyncio.sleep(delay)
    return f"{name}: {delay}s"

async def main():
    start = time.perf_counter()
    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(fetch("users", 0.3))
        t2 = tg.create_task(fetch("orders", 0.2))
        t3 = tg.create_task(fetch("stock", 0.1))
    # all three tasks are finished here
    print(t1.result(), t2.result(), t3.result(), sep="\n")
    print(f"took {time.perf_counter() - start:.1f}s")

asyncio.run(main())
users: 0.3s
orders: 0.2s
stock: 0.1s
took 0.3s

The tasks run concurrently, so the whole thing takes as long as the slowest task (0.3s), not the sum. The async with block doesn't exit until all tasks are done, so calling result() after it is always safe.

tg.create_task(coro, *, name=None, context=None) returns an ordinary asyncio.Task. The tasks start running at the next await, which is at the latest the implicit await when the block exits.

Collecting results

For many tasks, keep them in a list or dict and read the results after the block. A list comprehension keeps the input order, no matter in which order the tasks finish:

import asyncio

async def square(n):
    await asyncio.sleep(0.1 * (5 - n))   # finish in reverse order
    return n * n

async def main():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(square(n)) for n in range(1, 5)]
    results = [t.result() for t in tasks]
    print(results)

    # or keep a mapping from input to task
    async with asyncio.TaskGroup() as tg:
        by_name = {name: tg.create_task(square(len(name)))
                   for name in ["ab", "abc", "a"]}
    print({name: t.result() for name, t in by_name.items()})

asyncio.run(main())
[1, 4, 9, 16]
{'ab': 4, 'abc': 9, 'a': 1}

This is the TaskGroup equivalent of results = await asyncio.gather(*coros). It's a bit more verbose, but the error handling is much better, as the next section shows.

TaskGroup vs gather: what happens on failure

asyncio.gather() raises the first exception, but it doesn't cancel the other awaitables. They keep running in the background, unowned, and their results or errors are lost. TaskGroup cancels the siblings and waits for them to finish before it raises:

import asyncio

async def fetch(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ConnectionError(f"{name} failed")
        print(f"{name} finished")
        return name
    except asyncio.CancelledError:
        print(f"{name} cancelled")
        raise

async def with_gather():
    try:
        await asyncio.gather(
            fetch("a", 0.1, fail=True),
            fetch("b", 0.3),
        )
    except ConnectionError as e:
        print("gather raised:", e)

async def with_taskgroup():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(fetch("c", 0.1, fail=True))
            tg.create_task(fetch("d", 0.3))
    except* ConnectionError as eg:
        print("TaskGroup raised:", eg.exceptions)

async def main():
    await with_gather()
    print("-- gather returned")
    await asyncio.sleep(0.5)   # "b" is still running in the background
    print()
    await with_taskgroup()
    print("-- TaskGroup returned")
    await asyncio.sleep(0.5)

asyncio.run(main())
gather raised: a failed
-- gather returned
b finished

d cancelled
TaskGroup raised: (ConnectionError('c failed'),)
-- TaskGroup returned

b finished is printed after gather() has already returned. If b had been writing to a connection that the caller then closed, you'd get confusing errors from code that "already finished". With the task group, d is cancelled and has stopped by the time the error reaches the caller.

gather(..., return_exceptions=True) is still useful when you want every task to run to completion and collect failures as values instead of stopping at the first one.

Errors come out as an ExceptionGroup

Several tasks can fail at about the same time, so the group always wraps task errors in an ExceptionGroup, even if there is only one. Each failure is in its exceptions tuple:

import asyncio

async def check(name, delay, error=None):
    await asyncio.sleep(delay)
    if error:
        raise error
    return name

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(check("db", 0.1, ValueError("bad config")))
            tg.create_task(check("cache", 0.1, ConnectionError("cache down")))
            tg.create_task(check("queue", 1.0))
    except ExceptionGroup as eg:
        print(repr(eg))
        for e in eg.exceptions:
            print(" ", type(e).__name__, e)

asyncio.run(main())
ExceptionGroup('unhandled errors in a TaskGroup', [ValueError('bad config'), ConnectionError('cache down')])
  ValueError bad config
  ConnectionError cache down

The practical consequence: except ValueError: around a task group never matches, because what's raised is an ExceptionGroup. Use except* ValueError: to handle the ValueErrors in the group (other exceptions propagate), or catch ExceptionGroup as a whole as above. The details of exception groups and except* are a topic of their own; for how they print in a traceback see Stack traces.

What happens in the group, step by step:

  1. A task raises an exception other than CancelledError.
  2. The group cancels all other tasks that are still running, and the task running the async with body if it's waiting inside the block.
  3. It waits for all tasks to finish (they get CancelledError and can run their cleanup).
  4. It raises an ExceptionGroup with every exception that was raised, except CancelledError.

Two special cases: if a task raises KeyboardInterrupt or SystemExit, the siblings are still cancelled and awaited, but then that exception is re-raised as-is instead of an ExceptionGroup. And if the task that runs the group is itself cancelled from outside (for example by an enclosing asyncio.timeout()), you get CancelledError (or TimeoutError), not a group.

An error in the body also cancels the tasks

If the code inside the async with block raises, the group treats it like a failed task: it cancels the children, waits for them, and raises the error in an ExceptionGroup:

import asyncio

async def worker(name):
    try:
        await asyncio.sleep(1)
    finally:
        print(f"{name}: cleaned up")

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(worker("w1"))
            tg.create_task(worker("w2"))
            await asyncio.sleep(0.1)
            raise KeyError("missing setting")   # error in the body itself
    except* KeyError as eg:
        print("caught:", eg.exceptions)

asyncio.run(main())
w1: cleaned up
w2: cleaned up
caught: (KeyError('missing setting'),)

Finished tasks keep their results

Tasks that completed before the failure keep their results. After a failed group you can still inspect each task: result() for the successful ones, cancelled() for the ones the group stopped, and exception() for the one that failed:

import asyncio

async def step(name, delay, fail=False):
    await asyncio.sleep(delay)
    if fail:
        raise ValueError(f"{name} failed")
    return name

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            fast = tg.create_task(step("fast", 0.1))
            bad = tg.create_task(step("bad", 0.2, fail=True))
            slow = tg.create_task(step("slow", 1.0))
    except* ValueError:
        pass
    print("fast:", fast.result())
    print("slow cancelled:", slow.cancelled())
    print("bad exception:", repr(bad.exception()))

asyncio.run(main())
fast: fast
slow cancelled: True
bad exception: ValueError('bad failed')

Tasks can add more tasks

Unlike gather(), the set of tasks doesn't have to be known up front. Any code holding the group, including a task in it, can call tg.create_task() while the group is active, and the group waits for those new tasks too. That makes recursive fan-out, like a crawler, simple:

import asyncio

# a fake site: page -> links on that page
SITE = {
    "/": ["/a", "/b"],
    "/a": ["/a/1", "/a/2", "/"],
    "/b": ["/b/1", "/a"],
    "/a/1": [], "/a/2": ["/b/1"], "/b/1": [],
}

async def crawl(url, tg, seen):
    if url in seen:
        return
    seen.add(url)
    await asyncio.sleep(0.05)              # pretend to download the page
    print("visited", url)
    for link in SITE[url]:
        tg.create_task(crawl(link, tg, seen))  # spawn more work in the same group

async def main():
    seen = set()
    async with asyncio.TaskGroup() as tg:
        tg.create_task(crawl("/", tg, seen))
    print("done, pages:", len(seen))

asyncio.run(main())
visited /
visited /a
visited /b
visited /a/1
visited /a/2
visited /b/1
done, pages: 6

The async with block exits only when the last spawned task has finished. Once the group has exited, it can't be reused:

import asyncio

async def noop():
    await asyncio.sleep(0)

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(noop())
    coro = noop()
    try:
        tg.create_task(coro)
    except RuntimeError as e:
        print("RuntimeError:", e)

asyncio.run(main())
RuntimeError: TaskGroup <TaskGroup entered> is finished

Limiting concurrency with a Semaphore

A group runs every task at once. With 10,000 URLs that means 10,000 open connections, which a server (or your OS) won't like. TaskGroup has no built-in limit; combine it with an asyncio.Semaphore:

import asyncio
import time

active = 0
peak = 0

async def download(url, limit):
    global active, peak
    async with limit:                 # at most N downloads at a time
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.1)
        active -= 1
        return len(url)

async def main():
    urls = [f"https://example.com/item/{i}" for i in range(20)]
    limit = asyncio.Semaphore(5)
    start = time.perf_counter()
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(download(u, limit)) for u in urls]
    print("results:", sum(t.result() for t in tasks))
    print("peak concurrency:", peak)
    print(f"took {time.perf_counter() - start:.1f}s")

asyncio.run(main())
results: 530
peak concurrency: 5
took 0.4s

20 jobs of 0.1s with 5 at a time take 0.4s. This still creates all 20 task objects up front, which is fine for thousands of items. For an unbounded or very large input, use a fixed number of worker tasks reading from a queue instead (next section), so memory use stays constant.

Producer/consumer pipelines with Queue.shutdown()

A pipeline of a producer and a few consumers fits a task group well: if any stage crashes, the whole pipeline is torn down. The hard part used to be telling the consumers that there's no more work. People pushed one None sentinel per consumer, or cancelled them after queue.join().

Python 3.13 added Queue.shutdown(). After it's called, put() raises asyncio.QueueShutDown, and get() keeps returning the items that are already in the queue, then raises QueueShutDown once it's empty. Every consumer gets the signal, however many there are:

import asyncio

async def producer(queue, n):
    for i in range(n):
        await queue.put(i)
    queue.shutdown()          # Python 3.13+: no more items; consumers drain the rest
    print("producer: done")

async def consumer(name, queue, results):
    while True:
        try:
            item = await queue.get()
        except asyncio.QueueShutDown:
            print(f"{name}: queue closed, exiting")
            return
        await asyncio.sleep(0.01)
        results.append(item * 10)

async def main():
    queue = asyncio.Queue(maxsize=3)
    results = []
    async with asyncio.TaskGroup() as tg:
        tg.create_task(producer(queue, 10))
        for i in range(3):
            tg.create_task(consumer(f"c{i}", queue, results))
    print(sorted(results))

asyncio.run(main())
producer: done
c1: queue closed, exiting
c2: queue closed, exiting
c0: queue closed, exiting
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

maxsize=3 gives backpressure: the producer waits in put() when the consumers fall behind. The number of consumers is the concurrency limit, and memory use doesn't grow with the input size.

queue.shutdown(immediate=True) discards the queued items too, so blocked get() calls raise right away. Use it when you want to stop as quickly as possible rather than finish the work.

If the producer fails, you don't need to shut the queue down by hand. The group cancels the consumers that are waiting in get():

import asyncio

async def producer(queue):
    for i in range(3):
        await queue.put(i)
    raise RuntimeError("source went away")

async def consumer(queue):
    while True:
        try:
            item = await queue.get()
        except asyncio.QueueShutDown:
            return
        print("got", item)

async def main():
    queue = asyncio.Queue()
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(producer(queue))
            tg.create_task(consumer(queue))
    except* RuntimeError as eg:
        print("pipeline failed:", eg.exceptions[0])

asyncio.run(main())
got 0
got 1
got 2
pipeline failed: source went away

Stopping a group early on purpose

In Python 3.13 and 3.14 TaskGroup has no cancel() method. To stop all tasks once you have what you need, for example the first answer from several mirrors, raise an exception of your own and catch it outside the group:

import asyncio

class Found(Exception):
    def __init__(self, value):
        self.value = value

async def query(mirror, delay):
    try:
        await asyncio.sleep(delay)
    except asyncio.CancelledError:
        print(f"{mirror}: cancelled")
        raise
    raise Found(f"answer from {mirror}")

async def first_answer(mirrors):
    answer = None
    try:
        async with asyncio.TaskGroup() as tg:
            for mirror, delay in mirrors.items():
                tg.create_task(query(mirror, delay))
    except* Found as eg:
        answer = eg.exceptions[0].value   # can't 'return' inside except*
    return answer

async def main():
    mirrors = {"eu": 0.3, "us": 0.1, "asia": 0.5}
    print(await first_answer(mirrors))

asyncio.run(main())
asia: cancelled
eu: cancelled
answer from us

Note the answer = ... followed by return after the block. return, break and continue are not allowed inside an except* clause; writing return eg.exceptions[0].value there is a SyntaxError.

Eager tasks (Python 3.12+)

Normally create_task() only schedules the coroutine; it starts running at the next iteration of the event loop. Python 3.12 added asyncio.eager_task_factory. With it, create_task() starts running the coroutine immediately, up to its first await that actually suspends. If the coroutine finishes without suspending (for example it returns a cached value), it never goes through the event loop at all.

Set it on the running loop with loop.set_task_factory(). The order of execution changes:

import asyncio

async def job(name):
    print(f"{name}: started")
    await asyncio.sleep(0)
    print(f"{name}: resumed")

async def demo():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(job("a"))
        print("created a")
        tg.create_task(job("b"))
        print("created b")

async def main():
    print("-- default (lazy) tasks")
    await demo()
    print("-- eager tasks")
    asyncio.get_running_loop().set_task_factory(asyncio.eager_task_factory)
    await demo()

asyncio.run(main())
-- default (lazy) tasks
created a
created b
a: started
b: started
a: resumed
b: resumed
-- eager tasks
a: started
created a
b: started
created b
a: resumed
b: resumed

The benefit is speed when many tasks complete synchronously, which is common with caches. Here 100,000 tasks hit a warm cache and never await:

import asyncio
import time

cache = {}

async def get(key):
    if key in cache:          # fast path: no await at all
        return cache[key]
    await asyncio.sleep(0.001)
    cache[key] = key.upper()
    return cache[key]

async def run(n):
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(get("k")) for _ in range(n)]
    return tasks

async def main():
    await get("k")                         # warm the cache
    tasks = await run(3)
    print([t.result() for t in tasks])

    for eager in (False, True):
        loop = asyncio.get_running_loop()
        loop.set_task_factory(asyncio.eager_task_factory if eager else None)
        start = time.perf_counter()
        await run(100_000)
        print(f"eager={eager}: {time.perf_counter() - start:.2f}s")

asyncio.run(main())
['K', 'K', 'K']
eager=False: 0.87s
eager=True: 0.60s

The exact numbers depend on the machine; the saving grows with the share of tasks that finish without suspending. The catch is the changed ordering: code that assumes a new task doesn't run until the creator awaits (for example, it sets up state after create_task() that the task reads) can break. Turn it on for a whole application, test it, and don't mix assumptions.

Python 3.14 also lets you make a single task eager without changing the loop's factory, with eager_start=True, which TaskGroup.create_task() passes through:

import asyncio

async def job(name):
    print(f"{name}: started")
    await asyncio.sleep(0)

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(job("lazy"))
        tg.create_task(job("eager"), eager_start=True)   # Python 3.14+
        print("both created")

asyncio.run(main())
eager: started
both created
lazy: started

(Run with Python 3.14.4.)

asyncio.Runner: several runs on one loop

asyncio.run() creates a new event loop, runs one coroutine and closes the loop. asyncio.Runner (Python 3.11+) is the same thing as a context manager that keeps the loop open between calls. That's handy when a synchronous program (a CLI, a test helper, a REPL session) needs to call async code several times and share loop-bound objects such as a connection pool between the calls:

import asyncio

async def startup():
    await asyncio.sleep(0.01)
    return "config loaded"

async def handle(n):
    await asyncio.sleep(0.01)
    return n * 2

with asyncio.Runner(debug=False) as runner:
    print(runner.run(startup()))
    # the same event loop is reused for each run() call
    loop = runner.get_loop()
    print(runner.run(handle(21)))
    print("same loop:", runner.get_loop() is loop)
print("loop closed:", loop.is_closed())
config loaded
42
same loop: True
loop closed: True

On exit, the runner cancels any tasks left running, shuts down async generators and the default executor, and closes the loop, exactly like asyncio.run(). Runner(loop_factory=...) lets you choose the loop implementation, for example uvloop.new_event_loop (see Using UVLoop).

Pitfalls

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents