Skip to content
Hrushiekesh Reddy Kanjula
A single glowing event loop hub with teal coroutine threads branching outward

Python Async Programming: asyncio, aiohttp, and When to Actually Use It

asyncio is not a general speed-up; it fixes time wasted waiting on I/O, and this post covers when it wins and when it costs more than it saves.

Published
February 2, 2026
Author
Hrushiekesh Reddy Kanjula
Read time
~5 min
Category
engineering

A single glowing event loop hub with teal coroutine threads branching outward

I ran a script against 500 API endpoints. The synchronous version took four minutes. The async version with aiohttp took eighteen seconds.

I had avoided asyncio for a long time. I had working code: a loop, requests, a list of URLs. It ran fine, and I doubted the complexity was worth it.

The thing nobody says up front is that async does not make Python faster. It makes Python stop wasting time. Those are different problems. Mixing them up is how you end up with async code that runs slower than what you started with.

The event loop

A single chef can have five dishes going at once. Stir one, wait for another to boil, plate a third. Nothing runs in parallel. The chef just does not stand idle while water heats. That is the event loop, Python's internal task scheduler, doing cooperative multitasking.

When your code hits an await, it tells the loop: "I'm blocked on something external. Run something else." The loop finds the next ready task and runs it until its next await. When the network call responds, the original task is picked back up.

The key word is cooperative. The kernel can preempt an OS thread at any moment. Async tasks yield control voluntarily. That is a strength, because there are no race conditions on shared state and no locks. It is also a trap, because one blocking call freezes the whole loop.

A coroutine, defined with async def, is not a thread. It is a lightweight Python object, a suspended function with its own execution state. You can have tens of thousands in flight. Threads cost roughly 1 MB each on Linux. Coroutines cost kilobytes.

aiohttp, not requests

Asyncio event loop scheduling aiohttp sessions across multiple concurrent HTTP connections

requests is the right tool for synchronous HTTP. Inside an async function it is the wrong one. When requests.get(url) waits on the server, it does not yield to the loop. It freezes the whole thread, and every other coroutine waits. You have added overhead and gained no concurrency.

aiohttp is built around the event loop. Every network operation yields properly. This is the pattern I use:

import asyncio
import aiohttp
 
async def fetch(session: aiohttp.ClientSession, url: str) -> str:
    async with session.get(url) as response:
        return await response.text()
 
async def fetch_all(urls: list[str]) -> list[str]:
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        return await asyncio.gather(*tasks)
 
results = asyncio.run(fetch_all(urls))

Two points get misunderstood.

First, create ClientSession once and share it. Do not create one per request. The session manages a connection pool, SSL handshakes and cookie state. Recreating it each time is like hiring a taxi driver, firing them at the destination, and hiring a new one for the return trip. Reusing the session cuts per-request latency by 30-50% in practice.

Second, asyncio.gather schedules all the coroutines at once and collects results when they finish. It is the async version of a thread pool, without the thread overhead. At 300+ concurrent requests, aiohttp consistently benchmarks at 1.5-5x the throughput of a thread-based approach. At 5,000 simultaneous connections the gap widens further.

When async is the right tool

Hundreds of glowing amber data packets flowing simultaneously through a network — async throughput advantage

Before I write any async def, I ask what the bottleneck is.

If it is waiting (network calls, database queries, file reads), async fills the wait with useful work. Published benchmarks of asyncio with aiohttp generally show higher throughput and lower tail latency than equivalent synchronous code for I/O-bound work. The exact gain depends on the workload, so measure your own. For a scraper or a service making many outbound API calls, async is the right tool.

If it is computation (parsing large datasets, image processing, numerical work), async adds overhead and gives nothing. The CPU is already busy. Use multiprocessing or ProcessPoolExecutor, which spread work across cores.

My rule: async for I/O, multiprocessing for CPU, threads when you want simplicity and the concurrency is low.

The traps

A forked glowing path in deep space — one branch clean and flowing, one tangled in amber loops — the tension of async complexity

Async spreads. Once one function is async, every caller that wants to await it must be async too. That climbs your call stack fast. Decide on async deliberately. Do not start with a "small async helper."

Error handling needs care. By default, asyncio.gather re-raises the first exception and cancels the rest. In a scraper or batch job you usually want all results and all errors together. Pass return_exceptions=True.

The sneakiest trap is blocking the loop by accident. One time.sleep(5) inside an async function freezes every coroutine waiting to run. Use await asyncio.sleep(5) instead. For third-party synchronous code you cannot change, loop.run_in_executor offloads it to a thread pool and keeps the loop free. Missing one blocking call in a large async codebase is the debugging experience I would least like to repeat.

Debugging is also harder. Stack traces skip the frames where coroutines were suspended, so the call chain is less obvious. Python 3.11+ improved this with better traceback annotations. It is still not as clean as synchronous code.

The decision

The practical code surface is small. A handful of patterns covers most real use. The docs front-load a lot of theory before showing anything useful, and I think that causes more avoidance than the complexity does.

If you have real I/O concurrency (a scraper, a service making many outbound calls, a WebSocket handler), async is worth learning. If you do not, skip it.

I use these patterns in the Assembly Hub. Async API calls to Mouser and DigiKey cut lookup times from minutes to seconds. The code lives there if you want to see it in context.

Hire me