asyncio is Python’s built-in framework for asynchronous programming.It lets your program handle many I/O-bound tasks concurrently (network calls, disk I/O, APIs, timers) without using multiple threads.
asyncio ExistsTraditional Python code is blocking:
While waiting for an API response ⏳ → CPU sits idle
While reading a file 📂 → nothing else runs
asyncio solves this by allowing other tasks to run while one is waiting.
Key idea:
Don’t wait idly — switch to another task.
Think of asyncio like a single chef cooking multiple dishes 🍳:
If one dish is baking (waiting)
Chef starts chopping vegetables for another dish
No extra chefs (threads) needed
This is called cooperative multitasking.
asyncioThe brain of asyncio.
Runs forever
Decides which task runs next
Switches tasks when they are waiting
import asyncio
loop = asyncio.get_event_loop()
👉 You usually don’t manage it manually anymore.
async def) 🔁A function that can pause and resume.
async def my_task():
print("Start")
await asyncio.sleep(1)
print("End")
async def → defines a coroutine
Calling it does NOT run it immediately
await ⏸️Tells Python:
“Pause here, let other tasks run, resume me later.”
await asyncio.sleep(1)
⚠️ await only works:
Inside async def
On awaitable objects
A scheduled coroutine.
task = asyncio.create_task(my_task())
Task runs concurrently
Managed by the event loop
asyncio.run() 🚀The modern entry point.
async def main():
await my_task()
asyncio.run(main())
Creates event loop
Runs coroutine
Closes loop safely
| Concept | Meaning |
|---|---|
| Concurrency | Tasks take turns |
| Parallelism | Tasks run simultaneously |
asyncio = Concurrency, not CPU parallelism.
import time
def task():
time.sleep(2)
print("Done")
task()
task()
⏱️ Takes 4 seconds
import asyncio
async def task():
await asyncio.sleep(2)
print("Done")
async def main():
await asyncio.gather(task(), task())
asyncio.run(main())
⏱️ Takes 2 seconds
asyncio.gather() WorksRuns multiple coroutines concurrently:
await asyncio.gather(task1(), task2(), task3())
All start together
Event loop switches between them
Waits until all finish
API calls
Web scraping
Chatbots
WebSockets
Microservices
Async databases
Background jobs
Heavy CPU computation
ML training
Image processing
👉 For CPU work → use multiprocessing.
| Task | Library |
|---|---|
| HTTP requests | aiohttp |
| File I/O | aiofiles |
| Web frameworks | FastAPI, Sanic |
| DB access | asyncpg, aiomysql |
| WebSockets | websockets |
async def bad():
time.sleep(2) # BLOCKS event loop ❌
await asyncio.sleep(2)
task() # Does nothing ❌
await task()
Start Task A
↓
Task A waits (await)
↓
Run Task B
↓
Task B waits
↓
Resume Task A
↓
Finish
asyncio?Use it when:
You are doing many I/O operations
Latency matters
You want scalability without threads
Example:
1,000 API calls with
asyncio≫ threads ≫ sequential
asynciolets Python do more work while waiting, without using more threads.
asynciois Python’s asynchronous I/O framework that uses an event loop and coroutines to handle concurrent I/O-bound tasks efficiently.