🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Async Deep Dive: Tasks, Semaphores, and Cancellation

Python AsyncđŸŸĸ Free Lesson

Prerequisites

  • !async and await syntax and the event loop basics
  • !Threads versus cooperative concurrency

What You'll Learn

  • 1Explain what the event loop schedules and what it does not
  • 2Choose between gather, as_completed, and TaskGroup
  • 3Limit parallel work with a semaphore without stalling the loop
  • 4Cancel tasks cleanly and react to cancellation in finally blocks
  • 5Diagnose the classic bugs: forgotten awaits, blocking calls, and leaked tasks

Concurrency in asyncio is cooperative, which changes almost every design decision you make. Nothing preempts a coroutine that forgets to await, so correctness depends on every participant yielding control at sensible points. This lesson covers the structures for launching work, the mechanisms for limiting it, and the part most tutorials skip: making cancellation real so that shutting down does not leak tasks or leave resources half-closed.

What the loop actually schedules

One event loop runs on one thread and advances coroutines only when they await something the loop understands: a sleep, an I/O completion, a lock, a queue operation. A coroutine that runs a tight computation loop without awaiting blocks everything, including timeouts and signal handling, because there is nothing else to run. The unit of scheduling is a task, an object that wraps a coroutine and drives it to completion independently, which is why two awaits in one coroutine run sequentially while two tasks run concurrently.

ConstructRunsFails whenBest for
await coro()Inline, one at a timeThe inner call errorsDependency between steps
asyncio.gather(c1, c2)ConcurrentlyFirst exception propagatesIndependent calls, all results needed
as_completed([...])As each finishesYou must drain manuallyStreaming results as they arrive
TaskGroupConcurrentlyAny failure cancels siblingsStructured, all-or-nothing work
create_taskDetachedYou forget to await itLong-lived background work

The last row is the source of the most common production warning: a task created and not referenced is garbage collected mid-flight, producing a log line about a destroyed pending task. Keep a reference, even if you never await it directly.

Gathering independent work

gather is the workhorse for fan-out patterns: several independent requests, a batch of database writes, a set of API calls whose order does not matter. It returns results in the order of the awaitables, not completion order, which keeps output predictable.

python
import asyncio
import random


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


async def main():
    urls = ["api/users", "api/orders", "api/inventory"]
    delays = [0.3, 0.1, 0.2]

    results = await asyncio.gather(
        *(fetch(url, d) for url, d in zip(urls, delays))
    )
    print(results)

    tasks = [asyncio.create_task(fetch(u, d))
             for u, d in zip(urls, delays)]
    for done in asyncio.as_completed(tasks):
        print("finished", await done)

    mixed = await asyncio.gather(
        fetch("api/one", 0.1),
        asyncio.sleep(0.05),
        return_exceptions=True,
    )
    print(mixed)   # ['api/one in 0.1s', None]

asyncio.run(main())

Two options matter here. return_exceptions=True treats an exception as a result instead of cancelling siblings and propagating immediately, which you want when one failed item should not sink the batch. Without it, gather cancels the remaining tasks as soon as one fails, which is often correct too but surprises people who expected partial results. Decide deliberately and document the choice at the call site.

Structured concurrency with TaskGroup

TaskGroup, available since Python 3.11, encodes the all-or-nothing pattern. When any child raises, the group cancels the others, waits for them to finish, and then raises an ExceptionGroup containing every failure. Waiting is the important part: no task is left running behind your exception handler.

python
import asyncio


async def worker(name, delay, failures):
    await asyncio.sleep(delay)
    if name in failures:
        raise RuntimeError(f"{name} exploded")
    return f"{name} ok"


async def run_batch(failures=()):
    results = []
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(worker(n, d, failures))
                 for n, d in [("a", 0.05), ("b", 0.1), ("c", 0.15)]]
    for task in tasks:
        results.append(task.result())
    return results


print(asyncio.run(run_batch()))
# ['a ok', 'b ok', 'c ok']

If failures includes "b", the with block exits with an exception after every sibling has been cancelled and awaited, so cleanup code above the group runs only when nothing is still in flight. That property makes TaskGroup preferable to gather for anything holding files, locks, or connections. The cost is that the results must be read after the block, and that error handling deals with a group rather than a single exception.

Bounding concurrency with a semaphore

Unbounded fan-out turns a burst of work into a burst of rate-limit errors or memory pressure. A semaphore caps how many coroutines are inside a critical region at once, and because it is async-aware, coroutines waiting for a permit still yield to the loop instead of blocking the thread.

python
import asyncio

async def call_api(client_id, semaphore, results):
    async with semaphore:
        await asyncio.sleep(0.1)
        results.append(client_id)


async def main():
    semaphore = asyncio.Semaphore(3)
    results = []
    await asyncio.gather(*(call_api(i, semaphore, results)
                           for i in range(12)))
    print(len(results), sorted(results)[:5])


asyncio.run(main())

A semaphore is the right tool when the limit is external, such as an API's per-second quota. When the limit is about memory, consider batching instead, since a semaphore still creates all the coroutine objects. Also watch for the classic deadlock: acquiring the same non-reentrant semaphore twice inside one coroutine, which hangs forever rather than raising, and is much easier to find in code review than at three in the morning.

Cancellation and timeouts that finish the job

Cancellation in asyncio is cooperative as well: the task receives a CancelledError at its current await point, and it is the coroutine's responsibility to stop and clean up. Code that catches Exception broadly will swallow that error, because CancelledError derives from BaseException in modern Python precisely to prevent that. Wrap cleanup in try and finally, and never suppress cancellation unless you have a specific reason and re-raise afterwards.

python
import asyncio


async def worker():
    try:
        await asyncio.sleep(10)
        print("never printed")
    except asyncio.CancelledError:
        print("cleaning up")
        await asyncio.sleep(0)   # let cleanup itself be cancellable
        raise


async def main():
    task = asyncio.create_task(worker())
    await asyncio.sleep(0.1)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("task cancelled")

    async with asyncio.timeout(0.2):
        await asyncio.sleep(5)

asyncio.run(main())

The timeout helper makes the pattern explicit: leaving the block early cancels the inner work, and a timeout raises so the caller can react. On older versions, wait_for provides the same semantics with slightly different ergonomics. Whichever you use, remember that a timeout only stops work that awaits; a coroutine performing CPU-bound computation will not notice the deadline until it yields again.

Async generators and queues for pipelines

When data flows between stages rather than being fetched once, async generators and asyncio.Queue provide the plumbing. A producer pushes into a queue, consumers pull from it, and the queue's own backpressure keeps memory bounded because put waits when the queue is full. This shape scales from two stages to a full pipeline without changing the coordination logic.

The rules for staying correct are short. Never call blocking library calls directly inside a coroutine, because they stall the whole loop; run them in a thread pool with to_thread when they cannot be avoided. Do not create tasks in a loop without a reference, and close async generators deterministically so their finally blocks run. And prefer structured patterns over detached background tasks unless the task is genuinely a service that outlives the request that started it.

Debugging async code

Async bugs hide because timing changes with load. The recurring symptoms are a timeout that fires despite fast code, which usually means something blocking sits inside a coroutine; a task that never completes, which usually means an await was forgotten on a future or a lock was never released; and a shutdown that hangs, which means a task or generator was started and never awaited or closed.

Set asyncio debug mode while investigating, since it reports slow callbacks and un-awaited tasks. Log the task name alongside every request so you can correlate traces, and give long-running tasks meaningful names when creating them. When concurrency limits matter, count entries and exits of the critical section in a test rather than trusting visual inspection of a log under load.

Common Mistakes

Calling a blocking library call directly inside a coroutine

Fix: Wrap it with asyncio.to_thread, or use an async-capable client, so the loop keeps running.

Creating tasks in a loop without keeping references

Fix: Store tasks in a list or use TaskGroup so they are neither collected nor left unfinished.

Catching Exception broadly and swallowing cancellation

Fix: Catch specific exceptions, and treat CancelledError as a signal to stop rather than an error to hide.

Using a semaphore as if it prevented memory growth

Fix: Bound the number of live objects through batching when the real constraint is memory, not external rate.

Best Practices

  • Prefer TaskGroup for all-or-nothing work because it waits for every child
  • Name background tasks so traces and logs are attributable
  • Keep every await point visible in code review by avoiding deeply nested awaits
  • Set timeouts on every external call that can hang
  • Write a shutdown test that asserts no tasks remain after the loop closes

Key Takeaways

  • The event loop advances only at await points, so blocking code freezes everything
  • gather preserves input order and can collect exceptions as results
  • TaskGroup cancels and waits for siblings when any child fails
  • Semaphores bound concurrent entry without blocking the loop thread
  • Cancellation must be allowed to propagate; cleanup belongs in finally blocks
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement