asyncio is Python's library for writing concurrent code using the async/await syntax, and it works by letting a single thread run many tasks cooperatively, switching between them at points where they would otherwise block on I/O. Instead of waiting for a network response or file read to finish, an asyncio task suspends itself, letting the event loop run other ready tasks, then resumes when the I/O completes. This gives you concurrency — many tasks making progress at once — without the overhead of threads or processes.
Background: Why asyncio Exists
Traditional Python programs run sequentially: one line finishes before the next starts. For CPU-bound work, that's fine, but for I/O-bound work — network requests, database queries, reading files — the program spends most of its time waiting. Threads can help, but they have costs: each thread requires memory for its stack, the OS scheduler has to switch between them, and shared data needs locks to avoid corruption. Processes avoid some of those issues but are even heavier. asyncio takes a different approach: it uses a single thread and an explicit scheduler, the event loop, to manage many tasks at once. This model is sometimes called cooperative multitasking, because each task must voluntarily yield control.
The Event Loop: The Core of asyncio
The event loop is the heart of asyncio. It's a loop that repeatedly checks a queue of ready tasks and runs them one at a time. Each task is a coroutine — a function defined with async def that can pause at await points. When a task hits an await, it yields control back to the loop, which then runs the next ready task. The loop also watches a set of I/O sources (sockets, pipes, subprocesses) and marks tasks as ready when their I/O completes. In Python's implementation, the loop uses the OS's select, poll, or epoll (on Linux) to monitor file descriptors efficiently.
You can get the running loop with asyncio.get_running_loop() inside a coroutine. The loop is created automatically when you call asyncio.run(main()), which is the recommended way to start an asyncio program. asyncio.run() creates a new event loop, runs the given coroutine until it completes, and then closes the loop.
Coroutines and the await Keyword
A coroutine is defined with async def. When you call a coroutine function, it doesn't execute immediately; it returns a coroutine object. That object must be awaited or scheduled on the event loop. Inside a coroutine, await suspends the current task until the awaited object is ready. The awaited object can be another coroutine, a Future, or a Task. For example:
async def fetch_data():
# Simulate a network call
await asyncio.sleep(1)
return "data"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
Here, await asyncio.sleep(1) suspends main for one second, but the event loop can run other tasks during that time. This is the key difference from a blocking time.sleep(), which would freeze the whole thread.
Tasks: Scheduling Coroutines for Concurrency
To run multiple coroutines concurrently, you wrap them in Tasks using asyncio.create_task(). A Task is a Future that schedules a coroutine to run on the event loop. When you create a task, it's scheduled to run soon, and you can await it later. Example:
async def main():
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(fetch_data())
# Both tasks run concurrently
r1 = await task1
r2 = await task2
print(r1, r2)
Without create_task(), if you wrote await fetch_data() twice in a row, the second call wouldn't start until the first finished. Tasks let you overlap them. The asyncio.gather() function is a convenient way to run several coroutines concurrently and collect their results: results = await asyncio.gather(fetch_data(), fetch_data()).
How I/O Is Handled: Non-Blocking Sockets
Under the hood, asyncio uses non-blocking sockets. When you open a network connection with asyncio.open_connection(), the socket is set to non-blocking mode. A read or write operation returns immediately with a special status indicating “not ready.” The event loop then registers the socket with the OS's I/O multiplexing mechanism (like epoll). When the socket becomes readable or writable, the OS notifies the loop, and the loop resumes the waiting coroutine. This is how a single thread can handle thousands of connections without blocking.
For CPU-bound work, asyncio does not help — it actually adds overhead. If you have heavy computation, you'd want to offload it to a separate process using asyncio.to_thread() or concurrent.futures.ProcessPoolExecutor. asyncio is designed for I/O-bound concurrency, not parallelism.
Choosing asyncio vs Threads vs Processes
Use asyncio when your program is I/O-bound and you want high concurrency with low overhead. Typical use cases include web servers, API clients, and network crawlers. Use threads when you have blocking I/O that you can't easily convert to async (like some third-party libraries) or when you need to run multiple blocking calls in parallel. Use processes when you need CPU-bound parallelism, because asyncio and threads both run on a single CPU core due to Python's Global Interpreter Lock (GIL). The GIL is a mutex that prevents multiple threads from executing Python bytecode simultaneously, so threads don't speed up CPU-bound code. Processes each have their own interpreter, so they can run on multiple cores.
In practice, many modern Python web frameworks (like FastAPI and aiohttp) are built on asyncio. If you're writing a small script that makes a few HTTP requests, you might use requests (blocking) or httpx (supports async). The choice depends on your concurrency needs.
Common Pitfalls and Misconceptions
A frequent mistake is calling a blocking function inside an async coroutine. For example, using time.sleep() instead of asyncio.sleep() blocks the entire event loop, freezing all other tasks. Similarly, using the requests library inside an async function will block. You should use async-compatible libraries (like aiohttp for HTTP) or run blocking code in a thread pool with asyncio.to_thread().
Another misconception is that asyncio makes your code run in parallel. It does not — it runs on a single thread, so only one task executes at a time. The benefit is that the thread is never idle waiting for I/O; it always has something to do. Also, be careful with shared state: because tasks run cooperatively, they can't be interrupted at arbitrary points (only at await), but they can still interleave at those points, so you may need locks for shared data.
Frequently Asked Questions
Is asyncio faster than threads?
For I/O-bound workloads, asyncio can be faster and more memory-efficient than threads because it avoids thread creation overhead and context switching. However, the difference is often small for a handful of connections. For thousands of connections, asyncio scales much better because threads consume significant memory.
Can I use asyncio with existing blocking libraries?
Yes, but you need to run them in a separate thread using asyncio.to_thread() or loop.run_in_executor(). This prevents blocking the event loop. For example, await asyncio.to_thread(requests.get, url) runs the blocking call in a thread pool.
What is the difference between a coroutine and a task?
A coroutine is a function defined with async def that can be awaited. A task is a coroutine that has been scheduled to run on the event loop, usually via asyncio.create_task(). Tasks are subclasses of Future and represent the execution of a coroutine.
Does asyncio work on Windows?
Yes, asyncio works on Windows, but the default event loop policy uses ProactorEventLoop for better support of subprocesses and sockets. In most cases, you don't need to change anything; asyncio.run() picks the appropriate loop.
Can I use asyncio with Python 3.7 and older?
asyncio was introduced in Python 3.4, but the async/await syntax became standard in 3.5. The asyncio.run() function was added in 3.7. If you're on an older version, you need to manually manage the event loop with loop = asyncio.get_event_loop(); loop.run_until_complete(main()). However, it's recommended to use Python 3.7 or later for the simplest experience.