FROMDEV

Python Asyncio Explained: Tasks, Event Loops, and Common Pitfalls

Python Asyncio Explained: Tasks, Event Loops, and Common Pitfalls

Build Faster I/O-Bound Python Programs with Asyncio

When a Python program spends much of its time waiting for network responses, database queries, or other I/O, doing each operation one at a time can waste time. asyncio lets you coordinate many such operations on one thread, switching between them while they wait. This guide explains how Python’s event loop and tasks work, shows a practical concurrent-I/O example, and covers the pitfalls that commonly make asynchronous code slower or harder to debug.

What Python Asyncio Is—and When to Use It

asyncio is Python’s standard-library framework for writing concurrent code with async and await. It is especially useful when a program has many I/O-bound operations, such as making HTTP requests or reading from asynchronous streams.

Asyncio is cooperative: a task runs until it reaches an await point where it can pause, allowing the event loop to run other ready tasks. It does not make blocking code non-blocking, and it does not automatically use multiple CPU cores.

For example, a developer gathering web data might use concurrent I/O to request multiple pages. Related Python workflows include scraping real estate data with Python and performing SEO analysis with Python. Asyncio can help coordinate requests, but it does not remove the need to respect site terms, rate limits, or robots policies.

How Async Functions, Coroutines, and Await Work

A function declared with async def is an asynchronous function. Calling it creates a coroutine object; the function body does not run to completion just because it was called. The coroutine must be awaited or scheduled as a task.

import asyncio

async def get_status():
    print("Checking...")
    await asyncio.sleep(1)
    return "ready"

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

asyncio.run(main())

Here, asyncio.sleep() suspends the current coroutine without blocking the thread. While it waits, the event loop can run other work. By contrast, time.sleep() blocks the thread and prevents the event loop from making progress during the sleep.

await is not a universal way to make any operation asynchronous. It must be applied to an awaitable, such as a coroutine or task. A synchronous operation can still block even when it appears inside an async def function.

The Event Loop and Asyncio Tasks

The event loop is the coordinator that runs asynchronous work. It keeps track of tasks that are ready to run and resumes them when their awaited operations can continue. In typical asyncio applications, one event loop runs in a thread; tasks take turns at suspension points rather than running Python instructions simultaneously.

Coroutines versus tasks

A coroutine describes asynchronous work. A task wraps a coroutine so the event loop can schedule and manage it. Awaiting a coroutine directly is useful when its result is needed before continuing. Scheduling tasks is useful when independent operations can make progress concurrently.

async def fetch_one(name):
    await asyncio.sleep(1)
    return f"result for {name}"

async def main():
    task_a = asyncio.create_task(fetch_one("A"))
    task_b = asyncio.create_task(fetch_one("B"))

    result_a = await task_a
    result_b = await task_b
    print(result_a, result_b)

asyncio.run(main())

The tasks can overlap during their waits. This example demonstrates concurrency, not parallel execution: the two coroutines do not run CPU instructions at the same time on separate cores.

For a group of related tasks, asyncio.TaskGroup provides structured concurrency in Python 3.11 and later. It waits for child tasks when the group exits and handles failures by cancelling remaining tasks in the group. Use asyncio.gather() when collecting results from a known set of awaitables is a better fit; understand its exception behavior before using it in failure-sensitive code.

Practical Example: Run Concurrent I/O Requests

The following example uses the third-party aiohttp library for HTTP requests. Install it with python -m pip install aiohttp. The semaphore limits how many requests are active at once, and the session reuses connection resources.

import asyncio
import aiohttp

URLS = [
    "https://example.com/",
    "https://www.python.org/",
    "https://httpbin.org/get",
]

async def fetch(session, url, limit):
    async with limit:
        try:
            async with session.get(
                url,
                timeout=aiohttp.ClientTimeout(total=10),
            ) as response:
                response.raise_for_status()
                body = await response.text()
                return url, response.status, len(body)
        except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
            return url, "error", str(exc)

async def main():
    limit = asyncio.Semaphore(5)

    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(
            *(fetch(session, url, limit) for url in URLS)
        )

    for result in results:
        print(result)

if __name__ == "__main__":
    asyncio.run(main())

asyncio.gather() schedules the supplied awaitables and returns their results in input order. The semaphore is more important when the URL list is large: without a limit, creating a task for every item can overwhelm the remote service or consume too many local resources. Choose a concurrency limit that fits the API’s rules and your application’s capacity.

For a data pipeline, the resulting records could be analyzed or charted after retrieval. For example, FromDev’s guides to Python SEO analysis and visualizing SEO metrics with Matplotlib cover downstream analysis and presentation.

Common Asyncio Pitfalls and How to Avoid Them

Calling blocking functions inside async code

Putting synchronous work inside an async def does not make it asynchronous. Calls such as time.sleep(), blocking HTTP clients, and slow file operations can stall the event loop. Use asynchronous libraries where available. For unavoidable blocking I/O, asyncio.to_thread() can run the call in a worker thread:

result = await asyncio.to_thread(blocking_function, argument)

This is primarily useful for blocking I/O. CPU-bound Python work generally needs a process pool or another strategy that can use multiple cores; moving it to a thread does not guarantee CPU parallelism.

Creating a coroutine without awaiting or scheduling it

This code creates a coroutine but does not run it:

async def work():
    return 42

work()  # The coroutine is never awaited

Await it directly or schedule it with asyncio.create_task(). Otherwise, Python may warn that the coroutine was never awaited, and the intended work will not happen.

Starting an event loop incorrectly

In a regular script, asyncio.run(main()) is the usual entry point. It creates and manages an event loop, then closes it when the top-level coroutine finishes. Do not call asyncio.run() from a thread where an event loop is already running, as commonly happens in notebooks or some web frameworks. In that environment, use the framework’s async entry point and await the coroutine in its existing loop.

Launching unlimited tasks

Creating thousands of tasks at once can use substantial memory and overload a service. Apply backpressure with a semaphore, a bounded asyncio.Queue, or a worker pool pattern. Also configure sensible timeouts so a stalled dependency does not leave tasks waiting indefinitely.

Ignoring cancellation and exceptions

Tasks can fail or be cancelled. Handle expected errors at the right level, and do not silently swallow cancellation: asyncio.CancelledError is used to stop work and should generally be allowed to propagate after any necessary cleanup. Use async with and try/finally to release resources reliably. Prefer keeping tasks within a clear scope, such as a TaskGroup, rather than creating background tasks that are never tracked.

Choosing Between Asyncio, Threads, and Processes

Asyncio is one concurrency tool, not a universal replacement for synchronous Python. The right choice depends on what the program spends time doing:

Mixing these approaches is possible, but make the boundaries explicit. A synchronous library call inside an async function can still block the loop; move it to a thread or replace it with an asynchronous alternative when appropriate.

A Practical Checklist for Reliable Async Python

  1. Confirm the workload is I/O-bound and that the libraries you need support async operations.
  2. Use asyncio.run() once at the top level of a standalone script.
  3. Use await for sequential dependencies and tasks for independent work.
  4. Set timeouts, limit concurrency, and handle expected failures.
  5. Close sessions, streams, and other resources with context managers.
  6. Test cancellation and error paths as well as successful requests.
  7. Measure the result: concurrency helps most when operations spend significant time waiting.

Conclusion

Python asyncio makes concurrent I/O practical by letting an event loop coordinate coroutines and tasks at points where they await. The key is understanding what it does—and what it does not do. Async code does not make blocking calls non-blocking, automatically parallelize CPU work, or remove the need to control resource use. Start with a small I/O-bound workflow, use timeouts and concurrency limits, and keep task lifetimes and errors visible. With those habits, asyncio can improve throughput without turning your program into a debugging puzzle.

Exit mobile version