Back 🐍⚡ asyncio Library in Python : built-in framework for asynchronous programming. 07 Jan, 2026

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.


🎯 Why asyncio Exists

Traditional 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.


🧠 Core Mental Model (Very Important)

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.


🧩 Key Components of asyncio

1️⃣ Event Loop 🌀

The 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.


2️⃣ Coroutine (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


3️⃣ 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


4️⃣ Task 🧵

A scheduled coroutine.

task = asyncio.create_task(my_task())
  • Task runs concurrently

  • Managed by the event loop


5️⃣ asyncio.run() 🚀

The modern entry point.

async def main():
    await my_task()

asyncio.run(main())
  • Creates event loop

  • Runs coroutine

  • Closes loop safely


🔁 Concurrency vs Parallelism (Critical Distinction)

ConceptMeaning
ConcurrencyTasks take turns
ParallelismTasks run simultaneously

asyncio = Concurrency, not CPU parallelism.


🚦 Simple Example: Blocking vs Async

❌ Blocking Code

import time

def task():
    time.sleep(2)
    print("Done")

task()
task()

⏱️ Takes 4 seconds


✅ Async Version

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


🧠 How asyncio.gather() Works

Runs multiple coroutines concurrently:

await asyncio.gather(task1(), task2(), task3())
  • All start together

  • Event loop switches between them

  • Waits until all finish


🌐 Real-World Use Cases

✅ Perfect for

  • API calls

  • Web scraping

  • Chatbots

  • WebSockets

  • Microservices

  • Async databases

  • Background jobs

❌ NOT good for

  • Heavy CPU computation

  • ML training

  • Image processing

👉 For CPU work → use multiprocessing.


🧠 Common Async I/O Libraries

TaskLibrary
HTTP requestsaiohttp
File I/Oaiofiles
Web frameworksFastAPI, Sanic
DB accessasyncpg, aiomysql
WebSocketswebsockets

⚠️ Common Mistakes (Very Common)

❌ Using blocking code inside async

async def bad():
    time.sleep(2)  # BLOCKS event loop ❌

✅ Correct

await asyncio.sleep(2)

❌ Forgetting to await

task()  # Does nothing ❌

✅ Correct

await task()

🧠 Async Flow (Visual in Words)

Start Task A
↓
Task A waits (await)
↓
Run Task B
↓
Task B waits
↓
Resume Task A
↓
Finish

🎯 When Should YOU Use 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


🟨 One-Line Summary

asyncio lets Python do more work while waiting, without using more threads.


🎓 Interview-Ready Definition

asyncio is Python’s asynchronous I/O framework that uses an event loop and coroutines to handle concurrent I/O-bound tasks efficiently.