Stop Blocking the Event Loop in Python Asyncio
Why requests.get() and time.sleep() freeze async Python apps, and how httpx or asyncio.to_thread() keep them fast.
By the end of this tutorial you will know:
- Why
async defruns on a single thread (cooperative multitasking) - How one
time.sleep()orrequests.get()freezes every other user's request - How to switch to
httpx/asyncio.sleepor offload blocking code withasyncio.to_thread()
Prerequisites: Python 3.9+ installed and basic familiarity with async/await.
1. The big idea
An asyncio server (like FastAPI or aiohttp) handles thousands of concurrent requests on one thread by switching tasks whenever a task hits await. If you call a synchronous blocking function like requests.get() or time.sleep() inside async def, there is no await pause—the entire thread stops, and every other request waits behind it.
2. Reproducing the freeze
import asyncio
import time
async def worker(name: str):
print(f"{name} started")
time.sleep(1) # BLOCKS the entire event loop!
print(f"{name} finished")
async def main():
start = time.perf_counter()
await asyncio.gather(worker("A"), worker("B"), worker("C"))
print(f"Total: {time.perf_counter() - start:.2f}s")
asyncio.run(main())A started
A finished
B started
B finished
C started
C finished
Total: 3.00sNotice they ran one after another (3.00s), not concurrently!
3. The fix: await asyncio.sleep() or asyncio.to_thread()
For native async I/O, use asyncio.sleep() and async libraries like httpx.AsyncClient. If you must call a synchronous library (e.g., a blocking SDK or CPU-heavy parser), offload it to a worker thread with await asyncio.to_thread(...).
import asyncio
import time
def blocking_io(name: str):
time.sleep(1)
return f"{name} finished"
async def worker(name: str):
print(f"{name} started")
result = await asyncio.to_thread(blocking_io, name)
print(result)
async def main():
start = time.perf_counter()
await asyncio.gather(worker("A"), worker("B"), worker("C"))
print(f"Total: {time.perf_counter() - start:.2f}s")
asyncio.run(main())A started
B started
C started
A finished
B finished
C finished
Total: 1.00sRun python3 non_blocking.py. All three workers start immediately and finish in ~1.00s instead of 3.00s.
4. Common pitfalls
| Blocking Call | Async Replacement |
|---|---|
time.sleep(1) | await asyncio.sleep(1) |
requests.get(url) | httpx.AsyncClient().get(url) |
psycopg2 / sync DB driver | asyncpg or await asyncio.to_thread(...) |
5. What you learned
You now know how synchronous calls stall an asyncio event loop and how async-native clients or asyncio.to_thread() restore true concurrency.