Python asyncio and Asynchronous Programming

Learn Python asyncio and Asynchronous Programming with practical examples, explanations, best practices, and real-world coding techniques.

Python asyncio is the standard-library framework for writing asynchronous and concurrent code with async and await. It is especially useful when an application spends significant time waiting for external operations such as network requests, database calls, sockets, subprocesses, or other I/O. Instead of forcing the program to sit idle during every wait, asynchronous code can allow other tasks to make progress.

Asynchronous programming is not the same as simply making code run faster. Its main benefit is making better use of waiting time. This makes asyncio particularly useful for network-heavy services, API clients, crawlers, WebSocket applications, task processors, and other workloads where many operations spend time waiting on external systems.

Modern asyncio development should focus on structured task management, explicit cancellation, clear timeout boundaries, and keeping blocking work away from the event loop. Python's current asyncio documentation also positions TaskGroup as a structured alternative for managing related tasks. :contentReference[oaicite:1]{index=1}

What You Will Learn

  • What asynchronous programming means in Python
  • How the asyncio event loop works
  • How to create coroutines using async and await
  • How asyncio tasks differ from coroutines
  • How to run multiple operations concurrently
  • How TaskGroup provides structured concurrency
  • How cancellation and timeouts work
  • How to use queues, locks, semaphores, and events
  • How to handle blocking operations inside async applications
  • How to avoid common asyncio mistakes

What Is Asynchronous Programming?

In synchronous code, operations are usually performed one after another. When one operation is waiting, the current flow waits with it.

Imagine a program making three network requests. If the first request takes two seconds and the second takes another two seconds, a sequential implementation may spend several seconds waiting before producing the final result.

With asynchronous programming, the application can start one operation, suspend it while it waits, and allow another task to make progress. The event loop coordinates these tasks and resumes them when they can continue.

The key idea

Asyncio is primarily about efficiently handling waiting. It is most valuable when your workload contains many I/O operations that can make progress independently.

Asyncio Is Not the Same as Parallelism

One of the most important concepts to understand is the difference between concurrency and parallelism.

Concept Meaning Typical Use
Concurrency Multiple tasks make progress over overlapping periods. Network and I/O-heavy workloads
Parallelism Work executes simultaneously across execution resources. CPU-heavy workloads
Asynchronous I/O Tasks can suspend during waits so other work can continue. APIs, sockets, databases, WebSockets

The Event Loop

The event loop is the central mechanism that coordinates asynchronous tasks. It keeps track of work that is ready to run, waits for I/O events, and resumes suspended asynchronous operations when they can make progress.

A useful mental model is to think of the event loop as a coordinator rather than a worker that performs every operation itself. Your coroutines give it points where they can suspend using await. While one task is waiting, another ready task can run.

Task A
  |
  | await network operation
  v
Event Loop
  |
  +----> Task B runs
  |
  +----> Task C runs
  |
  +----> Resume Task A when ready

In ordinary application code, you usually do not need to manually manage the event loop. The recommended high-level entry point is asyncio.run() for running the top-level coroutine. :contentReference[oaicite:2]{index=2}

Creating a Coroutine

A coroutine function is declared using async def. Calling it produces a coroutine object. Calling the function alone does not execute its body immediately.

import asyncio


async def greet():
    print("Hello")
    await asyncio.sleep(1)
    print("World")


asyncio.run(greet())

The await expression gives the event loop an opportunity to suspend the current coroutine while the awaited operation is incomplete. Asyncio's documentation uses this async / await pattern as the preferred way to write asyncio applications. :contentReference[oaicite:3]{index=3}

Calling a Coroutine Is Not the Same as Running It

This distinction causes many beginner mistakes.

import asyncio


async def work():
    print("Working")


result = work()

print(result)

The code creates a coroutine object, but the coroutine body does not run merely because the function was called. It must be awaited, scheduled as a task, or passed to an appropriate asyncio runner. :contentReference[oaicite:4]{index=4}

Using await

The await keyword pauses the current coroutine until the awaited operation completes. It is one of the fundamental building blocks of asynchronous Python.

import asyncio


async def fetch_data():
    await asyncio.sleep(2)
    return "Data received"


async def main():
    result = await fetch_data()
    print(result)


asyncio.run(main())

This example is still sequential because main() waits for fetch_data() before doing anything else.

Sequential Async Code

Using asyncio does not automatically make every operation concurrent. You can write an async program that still executes operations one after another.

import asyncio


async def fetch(name):
    print(f"Starting {name}")
    await asyncio.sleep(2)
    print(f"Finished {name}")


async def main():
    await fetch("A")
    await fetch("B")
    await fetch("C")


asyncio.run(main())

Each operation waits for the previous one to finish. The fact that the functions are asynchronous does not by itself create concurrency.

Creating Tasks

A task schedules a coroutine to run concurrently with other work managed by the event loop. The most common API is asyncio.create_task().

import asyncio


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


async def main():
    task_a = asyncio.create_task(
        fetch("A", 2)
    )

    task_b = asyncio.create_task(
        fetch("B", 1)
    )

    result_a = await task_a
    result_b = await task_b

    print(result_a)
    print(result_b)


asyncio.run(main())

The tasks are scheduled independently, allowing their waiting periods to overlap. Current Python documentation also recommends keeping references to created tasks, and highlights TaskGroup for safer structured task management. :contentReference[oaicite:5]{index=5}

asyncio.gather()

asyncio.gather() is useful when several awaitable operations should run concurrently and their results should be collected together.

import asyncio


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


async def main():
    results = await asyncio.gather(
        fetch("Users", 2),
        fetch("Orders", 1),
        fetch("Products", 3)
    )

    for result in results:
        print(result)


asyncio.run(main())

The results returned by gather() correspond to the order of the awaitables supplied to it, even if the individual operations finish at different times. :contentReference[oaicite:6]{index=6}

TaskGroup and Structured Concurrency

Modern asyncio code often benefits from asyncio.TaskGroup. A task group provides a structured lifetime for related tasks: tasks are created inside the group and the context manager waits for them when it exits.

import asyncio


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


async def main():
    async with asyncio.TaskGroup() as group:
        task_a = group.create_task(
            fetch("Users", 2)
        )

        task_b = group.create_task(
            fetch("Orders", 1)
        )

        task_c = group.create_task(
            fetch("Products", 3)
        )

    print(task_a.result())
    print(task_b.result())
    print(task_c.result())


asyncio.run(main())

Task groups provide stronger safety guarantees for related tasks. In particular, when a task in a task group fails, the group coordinates cancellation of the remaining tasks instead of leaving unrelated work running as a side effect. :contentReference[oaicite:7]{index=7}

TaskGroup vs gather()

Both can run asynchronous operations concurrently. Use gather() when collecting a group of results is the main goal. Use TaskGroup when related tasks have a shared lifecycle and structured failure handling is important.

Returning Values from Coroutines

Async functions can return ordinary Python values just like synchronous functions.

import asyncio


async def calculate_total():
    await asyncio.sleep(1)
    return 450


async def main():
    total = await calculate_total()
    print(f"Total: {total}")


asyncio.run(main())

Cancellation

Cancellation is an essential part of production asyncio programming. A task may need to stop because a request has been disconnected, an operation exceeded a timeout, the application is shutting down, or another related task failed.

Cancellation is normally delivered through asyncio.CancelledError. Cleanup code should generally allow cancellation to propagate unless there is a deliberate reason to handle it differently.

import asyncio


async def worker():
    try:
        while True:
            print("Working...")
            await asyncio.sleep(1)
    except asyncio.CancelledError:
        print("Worker cancelled")
        raise


async def main():
    task = asyncio.create_task(worker())

    await asyncio.sleep(3)

    task.cancel()

    try:
        await task
    except asyncio.CancelledError:
        print("Main received cancellation")


asyncio.run(main())

The finally block is also useful for cleanup that must happen regardless of whether a task completes, fails, or is cancelled.

Timeouts

External operations should not necessarily be allowed to wait forever. Asyncio provides timeout mechanisms so applications can place explicit limits around asynchronous work.

import asyncio


async def slow_operation():
    await asyncio.sleep(10)
    return "Finished"


async def main():
    try:
        async with asyncio.timeout(3):
            result = await slow_operation()
            print(result)

    except TimeoutError:
        print("Operation timed out")


asyncio.run(main())

Timeout boundaries are particularly useful for network calls, remote services, database operations, and background work where indefinite waiting would tie up application capacity.

Do Not Block the Event Loop

One of the most important asyncio rules is to avoid long-running blocking operations inside the event loop thread. A blocking operation prevents the loop from servicing other ready tasks.

This can happen when asynchronous code accidentally calls synchronous functions that spend significant time waiting.

import asyncio
import time


async def bad_example():
    time.sleep(5)

    return "Done"


async def main():
    await bad_example()


asyncio.run(main())

The time.sleep() call blocks the thread. It does not provide the cooperative suspension behavior of await asyncio.sleep().

Use asyncio.sleep() for Async Delays

import asyncio


async def good_example():
    await asyncio.sleep(5)

    return "Done"


async def main():
    task = asyncio.create_task(
        good_example()
    )

    print("Other work can continue...")

    result = await task

    print(result)


asyncio.run(main())

During the asynchronous sleep, the event loop can continue scheduling other ready tasks.

Handling Blocking Functions with to_thread()

Sometimes an application needs to call a blocking function because a library does not provide an async API. In suitable cases, asyncio.to_thread() can run that blocking function in a separate thread without directly blocking the event loop.

import asyncio
import time


def blocking_work():
    time.sleep(3)
    return "Blocking work completed"


async def main():
    result = await asyncio.to_thread(
        blocking_work
    )

    print(result)


asyncio.run(main())

This pattern is useful for integrating blocking libraries into async applications. It does not magically turn CPU-heavy work into efficient asynchronous work; expensive CPU processing usually requires a different execution strategy.

Running Multiple I/O Operations

One of asyncio's most useful patterns is launching independent I/O operations concurrently instead of waiting for every operation sequentially.

import asyncio


async def fetch_user():
    await asyncio.sleep(2)
    return {"id": 1, "name": "Alex"}


async def fetch_orders():
    await asyncio.sleep(3)
    return ["Order 1", "Order 2"]


async def fetch_notifications():
    await asyncio.sleep(1)
    return ["Welcome"]


async def main():
    user, orders, notifications = await asyncio.gather(
        fetch_user(),
        fetch_orders(),
        fetch_notifications()
    )

    print(user)
    print(orders)
    print(notifications)


asyncio.run(main())

These operations can overlap because none of them requires the others to finish before it begins.

Async Queues

asyncio.Queue is useful when one group of tasks produces work and another group consumes it. This is a common pattern for background processing systems.

import asyncio


async def producer(queue):
    for item in range(5):
        await queue.put(item)
        print(f"Produced: {item}")


async def consumer(queue):
    while True:
        item = await queue.get()

        try:
            print(f"Processing: {item}")
            await asyncio.sleep(1)

        finally:
            queue.task_done()


async def main():
    queue = asyncio.Queue()

    consumer_task = asyncio.create_task(
        consumer(queue)
    )

    await producer(queue)
    await queue.join()

    consumer_task.cancel()

    try:
        await consumer_task
    except asyncio.CancelledError:
        pass


asyncio.run(main())

Queues provide a clean way to control the flow of work between asynchronous producers and consumers and are especially useful for worker-style architectures.

Limiting Concurrency with Semaphore

Starting hundreds or thousands of network operations simultaneously may overload a remote service, consume connection resources, or create unnecessary pressure on your own application. A semaphore can limit the number of operations allowed to run at once.

import asyncio


async def fetch(item, semaphore):
    async with semaphore:
        print(f"Fetching {item}")
        await asyncio.sleep(2)
        print(f"Finished {item}")


async def main():
    semaphore = asyncio.Semaphore(3)

    tasks = [
        fetch(i, semaphore)
        for i in range(10)
    ]

    await asyncio.gather(*tasks)


asyncio.run(main())

The semaphore allows only a limited number of operations to hold the resource at the same time.

Async Locks

Asynchronous tasks may still interfere with shared state. Asyncio provides synchronization primitives such as Lock, Event, Condition, and Semaphore for coordinating concurrent tasks.

import asyncio


counter = 0
lock = asyncio.Lock()


async def increment():
    global counter

    async with lock:
        current = counter

        await asyncio.sleep(0)

        counter = current + 1


async def main():
    tasks = [
        increment()
        for _ in range(100)
    ]

    await asyncio.gather(*tasks)

    print(counter)


asyncio.run(main())

The lock protects the critical section so that only one task at a time can update the shared value.

Async Events

An asyncio.Event can be used when one task needs to signal that something has become available or a particular state has been reached.

import asyncio


ready = asyncio.Event()


async def initialize():
    print("Initializing...")
    await asyncio.sleep(2)

    ready.set()

    print("System ready")


async def worker():
    print("Waiting for initialization...")

    await ready.wait()

    print("Worker started")


async def main():
    await asyncio.gather(
        initialize(),
        worker()
    )


asyncio.run(main())

Async Context Managers

Some resources require asynchronous setup and cleanup. Such APIs can implement the asynchronous context manager protocol and be used with async with.

class AsyncResource:
    async def __aenter__(self):
        print("Opening resource")
        return self

    async def __aexit__(
        self,
        exc_type,
        exc_value,
        traceback
    ):
        print("Closing resource")


async def main():
    async with AsyncResource() as resource:
        print("Using resource")


import asyncio

asyncio.run(main())

Async context managers are useful for resources whose setup or cleanup itself needs to await asynchronous operations.

Async Generators

Async generators use async def together with yield to produce values over time. They are useful when results arrive incrementally rather than all at once.

import asyncio


async def stream_data():
    for item in range(5):
        await asyncio.sleep(1)
        yield item


async def main():
    async for item in stream_data():
        print(f"Received: {item}")


asyncio.run(main())

Task Exceptions

Async tasks can fail independently. Your application should decide how task failures are handled rather than creating background work and forgetting about it.

import asyncio


async def failing_task():
    await asyncio.sleep(1)
    raise ValueError(
        "Something went wrong"
    )


async def main():
    try:
        await failing_task()
    except ValueError as exc:
        print(f"Error: {exc}")


asyncio.run(main())

When tasks are grouped through structured concurrency, failure handling becomes easier to reason about because task lifetimes and exception propagation have a defined boundary.

Combining TaskGroup with Error Handling

A task group is particularly useful when several operations form one logical unit. Suppose an API endpoint needs customer information, account permissions, and notification settings. If one critical operation fails, the remaining related work may no longer be useful.

import asyncio


async def get_customer():
    await asyncio.sleep(1)
    return "Customer"


async def get_permissions():
    await asyncio.sleep(2)
    return "Permissions"


async def get_notifications():
    await asyncio.sleep(1)
    return "Notifications"


async def main():
    try:
        async with asyncio.TaskGroup() as group:
            customer = group.create_task(
                get_customer()
            )

            permissions = group.create_task(
                get_permissions()
            )

            notifications = group.create_task(
                get_notifications()
            )

        print(customer.result())
        print(permissions.result())
        print(notifications.result())

    except Exception as exc:
        print(f"Request failed: {exc}")


asyncio.run(main())

Async HTTP Client Pattern

A common real-world use of asyncio is making multiple HTTP requests concurrently. The HTTP library itself must support asynchronous I/O for the benefit of asyncio to be realized.

The general application pattern looks like this:

async def load_dashboard():
    users = await fetch_users()
    metrics = await fetch_metrics()
    notifications = await fetch_notifications()

    return {
        "users": users,
        "metrics": metrics,
        "notifications": notifications
    }

When the requests are independent, they can instead be started together:

async def load_dashboard():
    users, metrics, notifications = await asyncio.gather(
        fetch_users(),
        fetch_metrics(),
        fetch_notifications()
    )

    return {
        "users": users,
        "metrics": metrics,
        "notifications": notifications
    }

This pattern is one of the main reasons asynchronous programming is valuable in API-heavy applications.

Sequential vs Concurrent Execution

Sequential

result_a = await task_a()
result_b = await task_b()
result_c = await task_c()

Useful when later work depends on an earlier result or ordering is intentional.

Concurrent

result_a, result_b, result_c = await asyncio.gather(
    task_a(),
    task_b(),
    task_c()
)

Useful when independent operations can progress while waiting for one another.

When Asyncio Is a Good Fit

  • Applications making many network requests
  • HTTP and API clients
  • WebSocket and real-time communication
  • Network servers handling many concurrent connections
  • Asynchronous database clients
  • High-volume I/O pipelines
  • Concurrent background workers
  • Services that spend significant time waiting on external systems

When Asyncio Is Not the Best Tool

Asyncio is not automatically the best solution for every problem. A CPU-intensive algorithm that continuously consumes processor time does not become efficient simply because the surrounding function is declared async.

Examples include heavy image processing, large numerical calculations, computational simulations, and other workloads that spend most of their time executing CPU instructions rather than waiting for I/O. For such workloads, multiprocessing, native extensions, specialized libraries, or other execution strategies may be more appropriate.

Avoid Blocking Database or HTTP Libraries

An application can look asynchronous while still blocking the event loop if it calls synchronous database or HTTP clients directly inside async functions.

# Conceptual example

async def handler():
    result = synchronous_database_call()
    return result

The preferred approach is to use an asynchronous client where the library supports it. When a blocking dependency cannot be replaced, a suitable bridge such as asyncio.to_thread() may help keep the event loop responsive.

Do Not Forget to Await

Forgetting to await a coroutine is one of the most common asyncio mistakes.

async def fetch_user():
    return "Alex"


async def main():
    user = fetch_user()

    print(user)

The variable above contains a coroutine object rather than the actual result. The correct version is:

async def main():
    user = await fetch_user()

    print(user)

Do Not Create Uncontrolled Background Tasks

Creating background tasks without managing their lifecycle can cause difficult-to-debug failures, premature task cleanup, lost exceptions, or shutdown problems.

For related work that belongs to one operation, structured task management such as TaskGroup usually provides a clearer lifecycle than creating unrelated detached tasks. :contentReference[oaicite:8]{index=8}

Use Timeouts Around External Work

Network dependencies can become slow or unavailable. A production service should define appropriate timeout boundaries instead of assuming an external operation will always complete quickly.

async def call_external_service():
    try:
        async with asyncio.timeout(5):
            return await fetch_remote_data()

    except TimeoutError:
        return None

Async Retry Pattern

Retry logic can be useful for transient failures, but retries should have sensible limits and delays. Retrying indefinitely can make an outage worse by generating more traffic against an unhealthy dependency.

import asyncio


async def fetch_with_retry():
    for attempt in range(3):
        try:
            return await fetch_remote_data()

        except TemporaryError:
            if attempt == 2:
                raise

            await asyncio.sleep(
                2 ** attempt
            )

In production systems, retries should also consider which failures are actually safe to retry and whether the underlying operation is idempotent.

Rate Limiting and Concurrency Control

A semaphore limits concurrent operations, but concurrency limits and rate limits solve different problems. A semaphore controls how many operations are active at once. A rate limiter controls how frequently operations are started over time.

External APIs often impose request limits, so production clients may need both bounded concurrency and explicit request pacing.

Design Async Functions Around I/O Boundaries

Not every function in an asynchronous application needs to be async. A pure calculation that performs no asynchronous I/O can remain a normal synchronous function.

def calculate_tax(
    amount: float,
    rate: float
) -> float:
    return amount * rate


async def create_invoice():
    order = await load_order()

    tax = calculate_tax(
        order["total"],
        0.18
    )

    return {
        "total": order["total"],
        "tax": tax
    }

Keeping synchronous computation synchronous makes the boundary between I/O and ordinary business logic easier to understand.

Async Application Architecture

In a larger application, asynchronous programming should be introduced at meaningful boundaries rather than applied indiscriminately to every function.

Request Handler
      |
      v
Async Service
      |
      +----> Async Repository
      |
      +----> Async API Client
      |
      +----> Async Queue
      |
      v
Response

The service can remain focused on application behavior while the asynchronous infrastructure handles operations that genuinely need to wait.

Testing Async Code

Async functions should be tested using tools that understand coroutine execution. Tests should verify successful results, exceptions, cancellation behavior, timeout behavior, and important concurrency boundaries.

Keep asynchronous tests deterministic where possible. Avoid relying on arbitrary long sleeps to prove that tasks are concurrent. Explicit events, mocks, controlled dependencies, and synchronization primitives usually produce more reliable tests.

Observability for Async Applications

Concurrent systems can be more difficult to debug because many operations may overlap. Logging and metrics should make important task boundaries and external operations visible without exposing sensitive information.

import logging


logger = logging.getLogger(__name__)


async def process_job(job_id: int):
    logger.info(
        "Starting job %s",
        job_id
    )

    result = await perform_job(job_id)

    logger.info(
        "Completed job %s",
        job_id
    )

    return result

Common Asyncio Mistakes

Blocking the Event Loop

Calling blocking functions such as long synchronous sleeps or blocking network clients can prevent unrelated async tasks from progressing.

Forgetting await

Calling an async function without awaiting or scheduling it returns a coroutine object instead of executing the expected operation.

Uncontrolled Tasks

Detached tasks can outlive their parent operation and create lifecycle, shutdown, and exception-handling problems.

No Timeout

External services can become slow or unavailable, so indefinite waits should generally be avoided at important application boundaries.

Unlimited Concurrency

Launching a huge number of operations at once can overwhelm your application or the service it is calling.

Misusing Asyncio for CPU Work

Declaring CPU-heavy code as async does not automatically make that computation concurrent or faster.

Practical Asyncio Checklist

  • Use asyncio when the workload contains meaningful asynchronous I/O.
  • Use async and await consistently across asynchronous call boundaries.
  • Use asyncio.run() as the high-level entry point for standalone applications.
  • Use TaskGroup when related tasks should have a shared structured lifecycle.
  • Use gather() when concurrent results need to be collected together.
  • Set timeout boundaries around external operations.
  • Handle cancellation correctly and allow CancelledError to propagate when appropriate.
  • Avoid blocking operations on the event loop.
  • Use to_thread() when suitable blocking functions must be integrated into async code.
  • Use queues for producer-consumer workflows.
  • Use semaphores to limit concurrency when necessary.
  • Use locks and other synchronization primitives when shared state requires coordination.
  • Do not turn every ordinary helper function into an async function unnecessarily.
  • Measure actual behavior instead of assuming asynchronous code is automatically faster.

Practical Example: Concurrent Service Calls

Consider a dashboard that needs three independent pieces of information before it can render. A clean asynchronous design can execute the independent operations concurrently while keeping the aggregation logic simple.

import asyncio


async def get_profile():
    await asyncio.sleep(1)
    return {
        "name": "Alex"
    }


async def get_projects():
    await asyncio.sleep(2)
    return [
        "Portfolio",
        "Compiler"
    ]


async def get_notifications():
    await asyncio.sleep(1)
    return [
        "New message"
    ]


async def load_dashboard():
    profile, projects, notifications = await asyncio.gather(
        get_profile(),
        get_projects(),
        get_notifications()
    )

    return {
        "profile": profile,
        "projects": projects,
        "notifications": notifications
    }


async def main():
    dashboard = await load_dashboard()

    print(dashboard)


asyncio.run(main())

The dashboard function communicates the application intent clearly: obtain the independent data sources concurrently and combine their results into one response.

Asyncio in Real Applications

Asyncio can serve as the foundation for high-concurrency network applications and is used by asynchronous web frameworks, network clients, database libraries, and other I/O-oriented systems. :contentReference[oaicite:9]{index=9}

The important lesson is not to use asyncio simply because an application is modern or because async looks more advanced. Choose it because the workload benefits from overlapping waits and because the application architecture can preserve non-blocking execution.

Best Practices Summary

  • Understand whether your workload is I/O-bound or CPU-bound before choosing asyncio.
  • Use async functions only where asynchronous behavior provides value.
  • Keep the event loop free from long blocking operations.
  • Use TaskGroup for structured groups of related tasks.
  • Use gather() when concurrent operations need their results collected together.
  • Design explicit timeout and cancellation behavior.
  • Bound concurrency when talking to external services or limited resources.
  • Use queues when producers and consumers need a clear asynchronous workflow.
  • Protect shared asynchronous state with appropriate synchronization primitives.
  • Use async-compatible libraries for network and database I/O whenever practical.
  • Use to_thread() for suitable blocking functions that cannot be replaced immediately.
  • Keep business logic understandable even when the infrastructure is asynchronous.
  • Test concurrency-related behavior deliberately instead of relying on timing assumptions.

Interview Questions to Prepare

  • What is asyncio in Python?
  • What is the difference between concurrency and parallelism?
  • What is a coroutine?
  • What happens when an async function is called without await?
  • What does await do?
  • What is an event loop?
  • What is the difference between a coroutine and a Task?
  • What is asyncio.create_task() used for?
  • What is the difference between gather() and TaskGroup?
  • How does task cancellation work?
  • Why should blocking functions not run directly on the event loop?
  • When would you use asyncio.to_thread()?
  • How can you limit concurrent operations with Semaphore?
  • How do asyncio queues support producer-consumer architectures?
  • When should asyncio not be used?

Summary

Python asyncio provides a structured way to write asynchronous applications using async, await, coroutines, tasks, and the event loop. Its greatest value comes from workloads where many operations spend significant time waiting on external systems.

Effective asyncio development goes beyond simply adding async to functions. You need to manage task lifetimes, avoid blocking the event loop, handle cancellation, define timeouts, limit concurrency where necessary, coordinate shared state, and choose appropriate asynchronous libraries.

Start with a simple asynchronous design, identify the operations that genuinely benefit from concurrency, and introduce more advanced patterns such as TaskGroup, queues, semaphores, and cancellation handling only where the application needs them.

Code Examples

Basic Async Function

python
import asyncio


async def fetch_data():
    print("Starting...")
    await asyncio.sleep(2)
    print("Finished")

    return "Data received"


async def main():
    result = await fetch_data()
    print(result)


asyncio.run(main())
    

Run Tasks Concurrently

python
import asyncio


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


async def main():
    results = await asyncio.gather(
        fetch("Users", 2),
        fetch("Orders", 1),
        fetch("Products", 3)
    )

    print(results)


asyncio.run(main())
    

Structured Concurrency with TaskGroup

python
import asyncio


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


async def main():
    async with asyncio.TaskGroup() as group:
        users = group.create_task(
            fetch("Users", 2)
        )

        orders = group.create_task(
            fetch("Orders", 1)
        )

    print(users.result())
    print(orders.result())


asyncio.run(main())
    

Async Timeout

python
import asyncio


async def slow_operation():
    await asyncio.sleep(10)
    return "Completed"


async def main():
    try:
        async with asyncio.timeout(3):
            result = await slow_operation()
            print(result)

    except TimeoutError:
        print("Operation timed out")


asyncio.run(main())
    

Run Blocking Work Without Blocking the Event Loop

python
import asyncio
import time


def blocking_work():
    time.sleep(3)
    return "Blocking work completed"


async def main():
    result = await asyncio.to_thread(
        blocking_work
    )

    print(result)


asyncio.run(main())
    

Limit Concurrency with Semaphore

python
import asyncio


async def fetch(item, semaphore):
    async with semaphore:
        print(f"Starting {item}")
        await asyncio.sleep(2)
        print(f"Finished {item}")


async def main():
    semaphore = asyncio.Semaphore(3)

    tasks = [
        fetch(i, semaphore)
        for i in range(10)
    ]

    await asyncio.gather(*tasks)


asyncio.run(main())
    

Producer Consumer Queue

python
import asyncio


async def producer(queue):
    for item in range(5):
        await queue.put(item)
        print(f"Produced: {item}")


async def consumer(queue):
    while True:
        item = await queue.get()

        try:
            print(f"Processing: {item}")
            await asyncio.sleep(1)

        finally:
            queue.task_done()


async def main():
    queue = asyncio.Queue()

    worker = asyncio.create_task(
        consumer(queue)
    )

    await producer(queue)
    await queue.join()

    worker.cancel()

    try:
        await worker
    except asyncio.CancelledError:
        pass


asyncio.run(main())
    

Pro Tip

Do not make code asynchronous just because you can. Use asyncio when your workload benefits from overlapping I/O waits, keep blocking work off the event loop, define cancellation and timeout boundaries, and prefer structured task management for related concurrent work.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.