Skip to main content
Albero Academy

AsyncIO

Concurrent I/O with async and await — do many waits at once.

Advanced Python11 min

AsyncIO lets a single thread juggle many I/O-bound tasks concurrently. Instead of blocking while waiting for a network response, an await yields control so other work can run in the meantime. It's how Python handles thousands of simultaneous connections efficiently.

Coroutines: async and await

async def defines a coroutine; await pauses it while waiting, freeing the event loop to run other coroutines:

async / await
import asyncio
async def fetch(n):
await asyncio.sleep(1) # simulate a network call (non-blocking)
return n * 2
async def main():
result = await fetch(1) # await a single coroutine
print(result)
asyncio.run(main()) # start the event loop

Running many at once

asyncio.gather runs coroutines concurrently — three 1-second waits finish in ~1 second, not 3:

concurrent awaits
async def main():
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
print(results) # [2, 4, 6] — after ~1s total, not 3s

When to use it

Key takeaways

  1. 01async def defines a coroutine; await pauses it while waiting, freeing the event loop.
  2. 02asyncio.run starts the loop; asyncio.gather runs coroutines concurrently.
  3. 03Concurrent awaits overlap their waiting — many I/O tasks in the time of one.
  4. 04Best for I/O-bound work (network, disk, DB).
  5. 05Not a speed-up for CPU-bound work — use multiprocessing there.

Finished this chapter?

Mark it complete to track your progress through Python.