
The problem: one blocking call stalls everything
In an asyncio app (FastAPI, aiohttp, or any async server) the event loop runs on a single thread. If a coroutine calls a slow synchronous function — time.sleep, a blocking DB or HTTP call, or CPU-heavy parsing — the whole loop freezes. Every other request sits idle until that call returns.
import asyncio, time
async def handler():
time.sleep(2) # blocks the ENTIRE event loop for 2 seconds
return "done"
# While this sleeps, no other coroutine can make progress.
# 50 concurrent requests all wait in line behind one bad call.
The fix is to hand the blocking work to a separate thread and await it, so the loop stays free to serve other requests.
The fix: asyncio.to_thread
asyncio.to_thread runs a synchronous callable in a worker thread (from the default executor) and returns an awaitable that yields control back to the loop.
import asyncio, time
def blocking_work(seconds: int) -> str:
time.sleep(seconds) # safe here — runs in a worker thread
return f"slept {seconds}s"
async def handler():
result = await asyncio.to_thread(blocking_work, 2)
return result
While blocking_work sleeps in its thread, the event loop is free to serve other requests. The loop only pauses this one coroutine — not the whole server.
A realistic example: wrapping a sync DB driver
Most DB drivers (psycopg2, pymysql, redis-py) are blocking. In an async service, offload each call so it cooperates with the loop:
import asyncio
import psycopg2
def fetch_user(uid: int) -> dict:
conn = psycopg2.connect("dbname=app user=app")
cur = conn.cursor()
cur.execute("SELECT id, name FROM users WHERE id = %s", (uid,))
row = cur.fetchone()
conn.close()
return {"id": row[0], "name": row[1]}
async def get_user(uid: int) -> dict:
return await asyncio.to_thread(fetch_user, uid)
Now get_user yields while the query runs, instead of freezing every other connection.
Three gotchas
- Pass arguments, don’t call the function. Write
await asyncio.to_thread(fn, arg), notawait asyncio.to_thread(fn(arg)). The second form evaluatesfn(arg)synchronously on the loop beforeto_threadeven schedules the thread. - Exceptions propagate. Whatever the sync function raises bubbles up through the
await, so wrap it withtry/exceptexactly as you would for a normal call. - It’s threads, not free parallelism.
to_threaduses the defaultThreadPoolExecutor(max ~32 workers by default). It is great for I/O-bound blocking calls but poor for heavy CPU work — and shared non-thread-safe state is still a race. For CPU-bound work, prefer aProcessPoolExecutorvialoop.run_in_executor.
When NOT to use it
If the library already ships an async API (asyncpg, httpx, aioredis), use that instead — it is more efficient than spinning up a thread. to_thread is for the many real-world cases where only a synchronous API exists.
TL;DR
- A blocking call inside a coroutine freezes the entire event loop.
asyncio.to_thread(fn, *args)runsfnoff the loop and lets youawaitthe result.- Pass args separately; handle exceptions normally; use it for I/O-bound sync code, not CPU-heavy work.