Python asyncio Tutorial: TaskGroup vs gather, Timeouts, Semaphore and to_thread (2026)

Efficient Code Dec 02, 2026

Watch on YouTube

Most Python programs spend their time waiting: for an API to answer, a database to return rows, or a file to arrive. asyncio lets one thread do something useful during those waits, and in 2026 it is the engine behind FastAPI, httpx, LLM streaming clients and most modern Python web tools. The API has also changed a lot since the old loop.run_until_complete() tutorials: asyncio.TaskGroup and asyncio.timeout() arrived in Python 3.11, as_completed() became an async iterator in 3.13, and Python 3.15 (October 2026) added TaskGroup.cancel() and deprecated the event loop policy system. In this tutorial we write five small scripts that cover what you actually need in production: running tasks concurrently, handling errors without leaking tasks, deadlines, limiting concurrency with a semaphore and real HTTP requests, and calling blocking code safely. Every output block is the real output of the script above it, run on Python 3.15.2.

asyncio in one minute

  • Coroutine: a function defined with async def. Calling it does not run it; it returns a coroutine object that must be awaited.
  • await: pauses the current coroutine until the awaited thing is done and lets the event loop run other work meanwhile.
  • Task: a coroutine scheduled to run on the event loop concurrently with others. You create tasks with TaskGroup.create_task() (preferred) or asyncio.create_task().
  • Event loop: the scheduler. asyncio.run(main()) creates it, runs main() and closes it. You rarely need anything else.

asyncio is concurrency, not parallelism: all coroutines share one thread, so it speeds up I/O-bound work (network, disk, databases) but not CPU-heavy maths. For CPU work use processes, as shown in our multiprocessing and ProcessPoolExecutor tutorial, or the free-threaded build compared in Python No-GIL vs Rust.

Setup

Everything except Step 4 uses only the standard library. Step 4 uses httpx, the async HTTP client. Step 3 uses TaskGroup.cancel(), which needs Python 3.15; all other steps work on Python 3.11 or newer.

uv venv -p 3.15 && source .venv/bin/activate
uv pip install httpx
python step1_gather.py

Step 1: Run tasks concurrently with gather and TaskGroup

We simulate five service calls that each take half a second. asyncio.sleep() stands in for a network request: like a real socket read, it gives control back to the event loop while it waits.

import asyncio, time

async def fetch(name, delay):
    await asyncio.sleep(delay)          # stands in for a network call
    return f"{name} ok"

SERVICES = [("users", 0.5), ("orders", 0.5), ("stock", 0.5), ("prices", 0.5), ("reviews", 0.5)]

async def sequential():
    return [await fetch(n, d) for n, d in SERVICES]

async def with_gather():
    return await asyncio.gather(*(fetch(n, d) for n, d in SERVICES))

async def with_taskgroup():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(n, d), name=n) for n, d in SERVICES]
    return [t.result() for t in tasks]      # every task is done here

async def main():
    for label, fn in [("sequential", sequential), ("gather", with_gather), ("TaskGroup", with_taskgroup)]:
        t0 = time.perf_counter()
        result = await fn()
        print(f"{label:10} {time.perf_counter() - t0:.2f}s  {result}")

asyncio.run(main())
sequential 2.50s  ['users ok', 'orders ok', 'stock ok', 'prices ok', 'reviews ok']
gather     0.50s  ['users ok', 'orders ok', 'stock ok', 'prices ok', 'reviews ok']
TaskGroup  0.50s  ['users ok', 'orders ok', 'stock ok', 'prices ok', 'reviews ok']

Awaiting the calls one by one took 2.50 seconds, the sum of all delays. Both asyncio.gather() and asyncio.TaskGroup started all five calls at once and finished in 0.50 seconds, the time of the slowest call, which is 5 times faster. With gather you get the results as a list in input order. With a TaskGroup you keep the task objects and call task.result() after the async with block, because leaving the block guarantees every task has finished. Naming tasks (name=n) is optional but makes debugging and python -m asyncio ps output much easier to read.

Step 2: Error handling, why TaskGroup beats gather

Speed is the same, so why do the Python docs now recommend TaskGroup? Because of what happens when one task fails. In this script service b fails after 0.1 seconds while a and c are still working.

import asyncio

log = []

async def service(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ConnectionError(f"{name} returned 503")
        log.append(f"{name} finished")
        return name
    except asyncio.CancelledError:
        log.append(f"{name} cancelled")
        raise

async def demo_gather():
    log.clear()
    try:
        await asyncio.gather(service("a", 0.3), service("b", 0.1, fail=True), service("c", 0.3))
    except ConnectionError as e:
        print("gather raised:", repr(e))
    print("right after the error:", log, "| tasks still running:", len(asyncio.all_tasks()) - 1)
    await asyncio.sleep(0.4)
    print("0.4s later:", log)

async def demo_taskgroup():
    log.clear()
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(service("a", 0.3))
            tg.create_task(service("b", 0.1, fail=True))
            tg.create_task(service("c", 0.3))
    except* ConnectionError as eg:
        print("TaskGroup raised:", type(eg).__name__, [str(e) for e in eg.exceptions])
    print("after the block:", sorted(log), "| tasks still running:", len(asyncio.all_tasks()) - 1)

async def main():
    print("--- gather (default)")
    await demo_gather()
    print("--- TaskGroup + except*")
    await demo_taskgroup()

asyncio.run(main())
--- gather (default)
gather raised: ConnectionError('b returned 503')
right after the error: [] | tasks still running: 2
0.4s later: ['a finished', 'c finished']
--- TaskGroup + except*
TaskGroup raised: ExceptionGroup ['b returned 503']
after the block: ['a cancelled', 'c cancelled'] | tasks still running: 0

With default gather(), the first exception is raised to the caller immediately, but the other two tasks keep running unsupervised: right after the error there are still 2 tasks alive, and 0.4 seconds later they finish their work even though nobody will ever use their results. In a web server this means wasted database queries, open connections and log lines from requests that already failed.

TaskGroup follows the structured concurrency rule: when one task fails, the group cancels its siblings, waits for them to clean up, and only then raises. The log shows a and c were cancelled and 0 tasks are left running. Errors arrive as an ExceptionGroup, which you catch with except*. One except* clause can match several failures at once; loop over eg.exceptions to log each one. If you really want "collect everything, even failures", gather(..., return_exceptions=True) is still fine for that narrow case.

Step 3: Timeouts and the new TaskGroup.cancel() in Python 3.15

Never await the network without a deadline. asyncio.timeout() puts one deadline around a whole block of code, and asyncio.wait_for() wraps a single awaitable. Both raise the built-in TimeoutError. The third part of the script shows the "first answer wins" pattern with the new TaskGroup.cancel(): we ask three mirrors for the same data, keep the fastest answer and stop the rest.

import asyncio, time

async def mirror(name, delay):
    await asyncio.sleep(delay)
    return name

async def main():
    # 1) asyncio.timeout(): one deadline for a whole block
    t0 = time.perf_counter()
    try:
        async with asyncio.timeout(0.25):
            await mirror("slow api", 2)
    except TimeoutError:
        print(f"timeout() fired after {time.perf_counter() - t0:.2f}s -> TimeoutError")

    # 2) asyncio.wait_for(): deadline for one awaitable
    try:
        await asyncio.wait_for(mirror("slow api", 2), timeout=0.1)
    except TimeoutError:
        print("wait_for() raised TimeoutError")

    # 3) TaskGroup.cancel() (Python 3.15): first answer wins, stop the rest
    winner = None
    def first_wins(task):
        nonlocal winner
        if winner is None and not task.cancelled():
            winner = task.result()
            tg.cancel()                     # cancels the siblings, no exception
    t0 = time.perf_counter()
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(mirror(n, d)) for n, d in
                 [("mirror-eu", 0.30), ("mirror-us", 0.12), ("mirror-asia", 0.50)]]
        for t in tasks:
            t.add_done_callback(first_wins)
    print(f"winner={winner} in {time.perf_counter() - t0:.2f}s; cancelled={sum(t.cancelled() for t in tasks)}")
    print("TaskGroup.cancel available:", hasattr(asyncio.TaskGroup, "cancel"))

asyncio.run(main())
timeout() fired after 0.25s -> TimeoutError
wait_for() raised TimeoutError
winner=mirror-us in 0.12s; cancelled=2
TaskGroup.cancel available: True

The deadline fired after exactly 0.25 seconds instead of waiting 2 seconds for the slow call. In the race, mirror-us answered first after 0.12 seconds. Its done callback stored the result and called tg.cancel(), which cancelled the 2 slower tasks and exited the async with block quietly, without raising CancelledError. Before Python 3.15 you needed a custom exception raised from a task and suppressed around the group to do this. We checked: on Python 3.14.10 hasattr(asyncio.TaskGroup, "cancel") is False, so keep the old pattern if you must support older versions.

Step 4: Limit concurrent requests with asyncio.Semaphore and httpx

Starting 10,000 requests at once is the classic asyncio mistake: you hit rate limits, run out of sockets, or overload the server. An asyncio.Semaphore caps how many coroutines can be inside a block at the same time. To measure it honestly, this script starts a tiny local HTTP server with asyncio.start_server() that counts how many requests are in flight, then sends 30 real requests with httpx.AsyncClient.

import asyncio, time, httpx

active = peak = 0

async def handle(reader, writer):           # tiny local HTTP server (stdlib only)
    global active, peak
    await reader.readuntil(b"\r\n\r\n")
    active += 1; peak = max(peak, active)
    await asyncio.sleep(0.2)                # each request takes 200 ms
    active -= 1
    body = b'{"ok": true}'
    writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: "
                 + str(len(body)).encode() + b"\r\nConnection: close\r\n\r\n" + body)
    await writer.drain(); writer.close()

async def crawl(client, urls, limit=None):
    sem = asyncio.Semaphore(limit) if limit else None
    async def get(url):
        if sem is None:
            return (await client.get(url)).status_code
        async with sem:                     # at most `limit` requests in flight
            return (await client.get(url)).status_code
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(get(u)) for u in urls]
    return [t.result() for t in tasks]

async def main():
    global peak
    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    urls = [f"http://127.0.0.1:{port}/item/{i}" for i in range(30)]
    limits = httpx.Limits(max_connections=100)
    async with server, httpx.AsyncClient(limits=limits, timeout=10) as client:
        for limit in (None, 5):
            peak = 0; t0 = time.perf_counter()
            codes = await crawl(client, urls, limit)
            print(f"limit={str(limit):4}  requests={len(codes)}  all200={set(codes) == {200}}  "
                  f"peak_in_flight={peak:2}  time={time.perf_counter() - t0:.2f}s")
        server.close()

asyncio.run(main())
limit=None  requests=30  all200=True  peak_in_flight=30  time=0.25s
limit=5     requests=30  all200=True  peak_in_flight= 5  time=1.24s

Without a limit, all 30 requests hit the server at the same moment and finished in 0.25 seconds. With Semaphore(5) the server never saw more than 5 requests at once, and the batch took 1.24 seconds (30 requests divided into 6 rounds of 200 ms). That is the trade-off you tune: a higher limit is faster, a lower limit is kinder to the server and to your API quota. Two practical tips: share one AsyncClient for all requests so connections are reused, and keep the semaphore close to the request call, not around the whole task. httpx also has its own connection pool limit (httpx.Limits(max_connections=...)), which is a second safety net.

Step 5: Call blocking code with asyncio.to_thread and stream results with as_completed

A single blocking call inside a coroutine, such as time.sleep(), requests.get() or a slow synchronous library, freezes the whole event loop. Every other task waits. This script runs a heartbeat task that wakes up every 50 ms and records the worst delay it sees.

import asyncio, time

def blocking_report(seconds):               # sync code: a slow library, file I/O, requests...
    time.sleep(seconds)
    return f"report built in {seconds}s"

async def heartbeat(stop):
    worst, last = 0.0, time.perf_counter()
    while not stop.is_set():
        await asyncio.sleep(0.05)
        now = time.perf_counter(); worst = max(worst, now - last - 0.05); last = now
    return worst

async def run(label, job):
    stop = asyncio.Event()
    hb = asyncio.create_task(heartbeat(stop))
    await asyncio.sleep(0)
    result = await job()
    stop.set()
    print(f"{label:24} {result} | worst event-loop stall {await hb:.2f}s")

async def bad():
    return blocking_report(0.6)             # blocks the whole event loop

async def good():
    return await asyncio.to_thread(blocking_report, 0.6)   # runs in a worker thread

async def main():
    await run("blocking call in async", bad)
    await run("asyncio.to_thread", good)
    # as_completed is an async iterator since 3.13: handle results as they arrive
    jobs = [asyncio.create_task(asyncio.sleep(d, result=f"job {d}s")) for d in (0.3, 0.1, 0.2)]
    print("as_completed order:", [await t async for t in _iter(jobs)])

async def _iter(jobs):
    async for t in asyncio.as_completed(jobs):
        yield t

asyncio.run(main())
blocking call in async   report built in 0.6s | worst event-loop stall 0.55s
asyncio.to_thread        report built in 0.6s | worst event-loop stall 0.00s
as_completed order: ['job 0.1s', 'job 0.2s', 'job 0.3s']

Calling the blocking function directly stalled the event loop for 0.55 seconds: no other request could be served during that time. Wrapping the same function in asyncio.to_thread() moved it to a worker thread, and the worst stall dropped to 0.00 seconds while we still got the same result. The last line uses asyncio.as_completed() as an async iterator (Python 3.13+), so results arrive in the order they finish (0.1 s, 0.2 s, 0.3 s) instead of the order they were started. That is ideal for progress bars or for streaming partial results to a client, like the token streaming in our FastAPI SSE tutorial.

asyncio best practices for 2026

  • Start programs with asyncio.run(main()). Do not call get_event_loop() or set loop policies; the policy system is deprecated in Python 3.15 and scheduled for removal in 3.16. Use asyncio.Runner(loop_factory=...) if you need a custom loop such as uvloop.
  • Prefer TaskGroup over bare create_task() and over gather(). If you do use create_task(), keep a reference to the task, or it may be garbage collected before it finishes.
  • Put a deadline on every network call with asyncio.timeout(), and limit fan-out with a Semaphore.
  • Never block the loop: use async libraries (httpx, asyncpg, aiosqlite, async SQLAlchemy as in our async SQLModel with FastAPI guide) or asyncio.to_thread() for sync code.
  • Do not swallow asyncio.CancelledError. Catch it only to clean up, then re-raise, exactly like the service() function in Step 2.
  • When debugging, run with PYTHONASYNCIODEBUG=1 to log slow callbacks, and use python -m asyncio ps PID or pstree PID (Python 3.14+) to see which tasks a running process is waiting on.

Common asyncio errors and their fixes

  • RuntimeWarning: coroutine 'fetch' was never awaited: you called an async def function without await or without creating a task for it.
  • RuntimeError: asyncio.run() cannot be called from a running event loop: you are already inside a loop (for example Jupyter). Use await main() directly in the notebook cell.
  • ExceptionGroup: unhandled errors in a TaskGroup: a task failed. Catch it with except* SomeError and inspect eg.exceptions.
  • Program is not faster with asyncio: the work is CPU-bound or a blocking library is used. Move CPU work to processes and sync I/O to to_thread().
  • Too many open files or HTTP 429: you started too many requests at once. Add a Semaphore and share one client.

Conclusion

Modern asyncio is much smaller than it looks. Use TaskGroup to run tasks concurrently, which was 5 times faster than awaiting one by one in our test and, unlike gather, never leaves orphan tasks behind after an error. Wrap calls in asyncio.timeout(), use the new TaskGroup.cancel() in Python 3.15 to stop work once you have what you need, cap fan-out with a Semaphore, and push blocking code to asyncio.to_thread(). With these five tools you can write fast, safe I/O code for APIs, scrapers, bots and AI agents.

FAQ

Should I use asyncio.gather or TaskGroup? Use TaskGroup for new code on Python 3.11+. It cancels the remaining tasks when one fails and reports all errors in an ExceptionGroup. Keep gather(return_exceptions=True) for the rare case where you want every result, including failures.

What is new in asyncio in Python 3.15? TaskGroup.cancel() for a clean early exit of a whole group, and the deprecation of the event loop policy functions such as set_event_loop_policy(), which will be removed in 3.16.

Is asyncio faster than threads? For many concurrent network calls it usually uses less memory and scales to thousands of connections, but it only helps I/O-bound work. For CPU-bound work use multiprocessing.

How do I limit the number of concurrent requests? Create asyncio.Semaphore(n) and wrap each request in async with sem:. In our test the server never saw more than 5 requests at once.

Can I call requests or other sync libraries from async code? Yes, with await asyncio.to_thread(func, *args), so the event loop keeps running. Switching to an async client such as httpx is better for heavy traffic.

Tested versions: Python 3.15.2 (CPython) and httpx 0.29.0 on Linux x86_64 with 8 CPU cores.

Share:
Last updated: December 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices