TL;DR: One blocking call inside an async def stalls every coroutine on the loop. asyncio.to_thread() (Python 3.9+) runs that call in a worker thread, so your loop keeps serving requests.
The problem: one blocking call, everyone waits
An event loop runs on a single thread . Coroutines cooperate by hitting await . A blocking call like time.sleep() , requests.get() , or a sync DB driver never yields, so nothing else runs.
async def handler ( ) : time . sleep ( 3 ) # the entire loop is frozen for 3 seconds
Enter fullscreen mode
Exit fullscreen mode
The fix: one line
async def handler ( ) : await asyncio . to_thread ( time . sleep , 3 ) # loop stays free
Enter fullscreen mode
Exit fullscreen mode
Signature: asyncio.to_thread(func, /, *args, **kwargs) . Pass the function and its arguments separately. Don't call it yourself.
What actually happens
to_thread hands your function to the loop's default ThreadPoolExecutor .…