StackPractices
intermediate By Mathias Paulenko

Concurrent Async Tasks with asyncio.gather and Task Groups

Compare asyncio.gather and TaskGroup in Python. Handle failures, cancellation, timeouts, concurrency limits, and results as tasks finish.

Overview

A fan-out operation might read a user, a post, and a to-do endpoint. Starting those requests together lets their I/O waits overlap. In Python 3.11+, asyncio.gather and asyncio.TaskGroup both schedule awaitables concurrently, but they react differently when one child fails.

When to Use This

  • Fetching a user, a post, and a to-do item from separate endpoints
  • Parallel database queries across shards or services
  • Batch processing I/O-bound operations (file reads, network calls)
  • Fetching independent resources for one page, such as a profile, recent posts, and notifications. For an HTTP-focused example, see concurrent requests with aiohttp.

These APIs won’t make a CPU-heavy pure-Python function run in parallel: while that code runs, it occupies the event-loop thread. Move it to a process pool if it needs to run alongside other work.

Prerequisites

  • Python 3.11+
  • aiohttp for HTTP examples
  • The HTTP snippets reuse the fetch_url helper below. For event-loop and coroutine basics, see the Python asyncio guide.

Solution

1. Basic asyncio.gather

import asyncio
import aiohttp
import time

async def fetch_url(
    session: aiohttp.ClientSession,
    url: str,
) -> dict[str, object]:
    async with session.get(url) as response:
        response.raise_for_status()
        data = await response.json()
        return {"url": url, "status": response.status, "data": data}

async def fetch_all(urls: list[str]) -> list[dict[str, object]]:
    async with aiohttp.ClientSession() as session:
        tasks = [fetch_url(session, url) for url in urls]
        return await asyncio.gather(*tasks)

# Usage
urls = [
    "https://jsonplaceholder.typicode.com/users/1",
    "https://jsonplaceholder.typicode.com/posts/1",
    "https://jsonplaceholder.typicode.com/todos/1",
]

start = time.perf_counter()
results = asyncio.run(fetch_all(urls))
print(f"Fetched {len(results)} URLs in {time.perf_counter() - start:.2f}s")

2. Error Handling with return_exceptions

import asyncio

async def risky_operation(task_id: int) -> str:
    await asyncio.sleep(0.1)
    if task_id == 2:
        raise ValueError(f"Task {task_id} failed")
    return f"Task {task_id} succeeded"

async def main():
    # Keep each outcome in the result list so the batch can be inspected.
    results = await asyncio.gather(
        risky_operation(1),
        risky_operation(2),
        risky_operation(3),
        return_exceptions=True,
    )

    for result in results:
        if isinstance(result, BaseException):
            print(f"Error: {result}")
        else:
            print(f"Success: {result}")

asyncio.run(main())
# Output:
# Success: Task 1 succeeded
# Error: Task 2 failed
# Success: Task 3 succeeded

3. asyncio.TaskGroup (Python 3.11+)

import asyncio
import aiohttp

async def fetch_with_task_group(urls: list[str]) -> list[dict[str, object]]:
    async with aiohttp.ClientSession() as session:
        async with asyncio.TaskGroup() as group:
            tasks = [
                group.create_task(fetch_url(session, url))
                for url in urls
            ]

    # Read results in input order after every task has completed successfully.
    return [task.result() for task in tasks]

async def main() -> None:
    urls = ["https://jsonplaceholder.typicode.com/users/1"]
    try:
        results = await fetch_with_task_group(urls)
    except* (aiohttp.ClientError, TimeoutError) as errors:
        for error in errors.exceptions:
            print(f"Request failed: {error}")

asyncio.run(main())

If a child raises, TaskGroup cancels its siblings, waits for cancellation to finish, then raises an ExceptionGroup. Handle expected HTTP and timeout failures at the call site with except*; saving each returned task handle is enough to collect results.

4. Timeouts with asyncio.wait_for

import asyncio

async def slow_api_call(endpoint: str) -> dict[str, object]:
    await asyncio.sleep(10)  # Simulate a slow dependency.
    return {"endpoint": endpoint, "data": "result"}

async def fetch_with_timeout(
    url: str,
    timeout: float = 5.0,
) -> dict[str, object]:
    try:
        result = await asyncio.wait_for(slow_api_call(url), timeout=timeout)
        return result
    except TimeoutError:
        return {"endpoint": url, "error": "timeout"}

async def fetch_all_with_timeout(
    urls: list[str],
    timeout: float = 5.0,
) -> list[dict[str, object]]:
    tasks = [fetch_with_timeout(url, timeout) for url in urls]
    return await asyncio.gather(*tasks)

results = asyncio.run(fetch_all_with_timeout(
    ["https://jsonplaceholder.typicode.com/posts/1"],
    timeout=3.0,
))

5. Semaphore for a Concurrency Limit

import asyncio
import aiohttp

async def fetch_with_limit(
    session: aiohttp.ClientSession,
    url: str,
    semaphore: asyncio.Semaphore,
) -> dict[str, object]:
    async with semaphore:
        return await fetch_url(session, url)

async def fetch_all_limited(
    urls: list[str],
    max_concurrent: int = 10,
) -> list[dict[str, object]]:
    semaphore = asyncio.Semaphore(max_concurrent)

    async with aiohttp.ClientSession() as session:
        tasks = [fetch_with_limit(session, url, semaphore) for url in urls]
        return await asyncio.gather(*tasks)

urls = [
    f"https://jsonplaceholder.typicode.com/posts/{post_id}"
    for post_id in range(1, 21)
]
results = asyncio.run(fetch_all_limited(urls, max_concurrent=10))

The semaphore caps in-flight requests but doesn’t track elapsed time. For a quota measured over a time window, use a rate limiter such as the token-bucket recipe.

6. as_completed for Progressive Results

import asyncio
import aiohttp

async def fetch_one(
    session: aiohttp.ClientSession,
    url: str,
) -> tuple[str, dict[str, object] | Exception]:
    try:
        return url, await fetch_url(session, url)
    except (aiohttp.ClientError, TimeoutError, ValueError) as exc:
        return url, exc

async def process_as_completed(urls: list[str]) -> None:
    async with aiohttp.ClientSession() as session:
        tasks = [
            asyncio.create_task(fetch_one(session, url))
            for url in urls
        ]

        try:
            # The wrapper returns the URL with its result, so no Task lookup is needed.
            for completed in asyncio.as_completed(tasks):
                url, result = await completed
                if isinstance(result, Exception):
                    print(f"Failed: {url} -> {result}")
                else:
                    print(f"Completed: {url} -> {result['status']}")
        finally:
            for task in tasks:
                if not task.done():
                    task.cancel()
            await asyncio.gather(*tasks, return_exceptions=True)

asyncio.run(process_as_completed([
    "https://jsonplaceholder.typicode.com/users/1",
    "https://jsonplaceholder.typicode.com/posts/1",
]))

7. Bounded Parallelism with Batches

import asyncio
import aiohttp

async def fetch_in_batches(
    urls: list[str],
    batch_size: int = 20,
) -> list[dict[str, object] | BaseException]:
    """Fetch a large list in batches instead of creating every task at once."""
    results = []

    async with aiohttp.ClientSession() as session:
        for i in range(0, len(urls), batch_size):
            batch = urls[i:i + batch_size]
            tasks = [fetch_url(session, url) for url in batch]
            batch_results = await asyncio.gather(*tasks, return_exceptions=True)
            results.extend(batch_results)
            print(f"Processed batch {i // batch_size + 1}")

    return results

urls = [
    f"https://jsonplaceholder.typicode.com/posts/{post_id}"
    for post_id in range(1, 101)
]
results = asyncio.run(fetch_in_batches(urls, batch_size=20))

Each input still has a slot in the list returned by gather, and a slot can hold an exception instead of a value — check the type before reading fields such as status. Batching keeps the number of task objects small when the input list is huge.

8. Combining Results from Different Sources

import asyncio

async def fetch_users() -> list:
    await asyncio.sleep(0.5)
    return [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]

async def fetch_orders() -> list:
    await asyncio.sleep(0.3)
    return [{'id': 101, 'userId': 1, 'total': 50}]

async def fetch_products() -> list:
    await asyncio.sleep(0.4)
    return [{'id': 201, 'name': 'Widget', 'price': 10}]

async def fetch_dashboard_data() -> dict:
    # All three fetches run concurrently
    users, orders, products = await asyncio.gather(
        fetch_users(),
        fetch_orders(),
        fetch_products(),
    )
    return {'users': users, 'orders': orders, 'products': products}

# The concurrent wait is roughly the longest sleep, not the sum of all three.
data = asyncio.run(fetch_dashboard_data())

How It Works

Choose based on the caller’s failure policy. gather leaves sibling work running after it propagates an error; TaskGroup cancels sibling tasks.

Decision tree comparing gather and TaskGroup when a child task fails.
Behaviorasyncio.gatherasyncio.TaskGroup
ResultsReturns values in input order.Store task handles and read .result() after the block exits successfully.
First child errorSends the first error to the caller while sibling awaitables keep running.Cancels sibling tasks, waits for cleanup, and raises an ExceptionGroup.
Partial successreturn_exceptions=True returns exceptions alongside successful values.A failing child cancels the group; catch expected errors inside a child if partial results are required.

Use gather for a fixed batch when input-order results or per-item failures matter. Use TaskGroup when child tasks share a lifetime and one failure should stop the others. The Python docs cover gather, TaskGroup, and as_completed.

asyncio.wait_for cancels the awaited operation and raises TimeoutError when the deadline expires. A semaphore grants at most max_concurrent active slots; it doesn’t space requests out over time.

Variants

Return the First Successful Result

import asyncio
import aiohttp

async def fetch_first_successful(urls: list[str]) -> dict[str, object]:
    if not urls:
        raise ValueError("urls must not be empty")

    async with aiohttp.ClientSession() as session:
        tasks = [
            asyncio.create_task(fetch_url(session, url))
            for url in urls
        ]
        errors: list[Exception] = []

        try:
            for completed in asyncio.as_completed(tasks):
                try:
                    return await completed
                except (aiohttp.ClientError, TimeoutError, ValueError) as exc:
                    errors.append(exc)

            raise ExceptionGroup("Every request failed", errors)
        finally:
            for task in tasks:
                if not task.done():
                    task.cancel()
            await asyncio.gather(*tasks, return_exceptions=True)

This loop continues after a fast failure and returns the first successful response. The finally block cancels and awaits unfinished tasks whether the function returns or raises. ExceptionGroup requires Python 3.11+; see the exception-groups reference.

Dynamic Task Creation

async def process_stream(stream, handler):
    """Create related tasks as items arrive from an async iterator."""
    async with asyncio.TaskGroup() as tg:
        async for item in stream:
            tg.create_task(handler(item))

TaskGroup waits for its children and cancels siblings after a failure, but it doesn’t cap how many children you create. If the stream can outpace its handler, use a bounded queue and a fixed number of workers.

Gather with Progress Tracking

async def fetch_with_progress(urls: list[str]) -> list[dict[str, object]]:
    completed = 0

    async with aiohttp.ClientSession() as session:
        async def fetch_and_report(url: str) -> dict[str, object]:
            nonlocal completed
            result = await fetch_url(session, url)
            completed += 1
            print(f"Completed {completed}/{len(urls)}")
            return result

        return await asyncio.gather(
            *(fetch_and_report(url) for url in urls)
        )

Best Practices

  • Choose the failure policy first: use TaskGroup when sibling tasks should stop together; use gather when you need ordered results or want to inspect each failure.
  • Give network calls a deadline. wait_for cancels the operation on timeout; use retries only when the request is safe to repeat and the API’s policy allows them.
  • Reuse one aiohttp.ClientSession for a group of requests. It manages connection pooling; call raise_for_status() so HTTP error responses don’t look like successful JSON results.
  • A semaphore has no clock: it grants a slot when one is free. If the upstream API limits calls per second or per time window, use a rate limiter instead.
  • Batch very large input lists when creating every task at once would consume too much memory. A semaphore alone doesn’t limit the number of waiting task objects.

Common Mistakes

  • Creating a coroutine without running it: a standalone script starts the loop with asyncio.run(main()). When a coroutine already owns the loop, call await main() instead — asyncio.run() refuses to open a second one.
  • Assuming gather cancels siblings on error: the first error is propagated, but other awaitables keep running. Use TaskGroup when sibling cancellation is required.
  • Treating a semaphore as a requests-per-second limit: it caps simultaneous work, not request frequency.
  • Treating an exception as response data: a failed item is a BaseException, not the JSON dictionary your caller expected. Check its type before reading response fields.
  • Creating a task for every item in an unbounded stream: use a bounded queue and a worker pool when input can outpace processing.
  • Dropping task handles in a TaskGroup: the group still waits for its children. Keep the object returned by create_task() if later code needs to call .result().
  • Mixing sync and async: Blocking calls (time.sleep, requests.get) block the event loop. Use async equivalents (asyncio.sleep, aiohttp).

Further Reading

Frequently Asked Questions

What happens to sibling tasks when one gather call fails?

With the default return_exceptions=False, gather propagates the first exception to its caller, but it doesn't cancel the other awaitables; they continue running. Set return_exceptions=True when you want to wait for every outcome and inspect failures as values. Cancelling the gather call itself cancels unfinished awaitables.

When should I choose TaskGroup?

Use it for related child tasks whose lifetimes belong to one operation. If a child fails, the group cancels its siblings and raises an ExceptionGroup; after a successful block, task handles can provide results in the order you stored them.

How can I process results as they finish?

Use asyncio.as_completed. On Python 3.11 and 3.12, the regular iterator yields awaitables rather than the original Task objects, so return the input identifier with each result instead of looking up the yielded object in a task dictionary.

Does asyncio.Semaphore enforce an API rate limit?

A per-minute quota depends on elapsed time and a semaphore only counts active calls, so the two limits solve different problems. For a temporal quota, reach for a token bucket or sliding-window limiter.

How many concurrent requests should I allow?

Set concurrency from the upstream API's quota and your connection-pool limits, then watch latency, errors, and resource use. A process pool is the option for CPU-bound Python work; adding asyncio tasks won't make those calculations run in parallel.