# asyncio.to_thread: Stop Freezing Your Event Loop

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

```python
async def handler():
    time.sleep(3)  # the entire loop is frozen for 3 seconds
```

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqF0VFP2zAQB_Cvcru-gORA0jQRWKgSLUNM69Sp3fZCeLgkl8aqE4fYpTDod5_SlsGGEI9nW7___-RHzEzOKLHQZp2V1DqYzJIaAOD84DrBGd-u2DoIErw5lFK2fAueN4TRdYJOVXxkNXNzEB6epe3xcDSZjr_O4cfVZ5hMp98TvJFSppTvwBF4R97wKUHrVtkSUi5VnYNyCT7B-HVYf4utSTlVL_bB3fQxc_GaCd9ldlCmydoLLqBbqlBay95JzAVlwrrWLFn2gjiOwoHIjDat7PlRn4N4f-mtVe5K2W_u_8NSyvdYkVFE0V_s9DRIg_QZG0Q--fQvFr7BurrPWs7xCb1o_YHv84sWkB--qYYCK24rUjnKR3QlV91X51zQSjsUu5Nf1CpKNdvuTWFqd0mV0g8o0aOm0ezZB-u4EjDSql5-o2y-nS9N7QQkOOeFYfj5JUEBM5MaZwRcsb5jpzIScN4q0gIs1daz3KoCxTZkrn53XYJBc4-bjcB0Me5WQYmf1qVyjJs_re3X6g?type=png)

* * *

## The fix: one line

```python
async def handler():
    await asyncio.to_thread(time.sleep, 3)  # loop stays free
```

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`. Your coroutine suspends, the loop keeps working, and the result is delivered back when the thread finishes.

![Mermaid Diagram](https://mermaid.ink/img/pako:eNp1k29r2zAQxr_KTSMkBTlLXPefGYYlW-kgK6HtljeBcrbPibAsZZLctAv57kN2V6_roleSnt_p7h50O5bpnFjMer2dUMLFsOu7NVXUj6GfoqU-h_biBxqBqSTb9wxmTptJufLY--wsD4uGbK-1yck0SlREp3TyotzRo5tqqVtxTOM0Sr1oxUqh7JQurFUOxSntaFKuOqmgYnSOf6TXYVEYjkanL2FNkZ2a4TmOov5-v-_1lsrSz5pURp8FrgxWSwUAgLXTqq5SMu15g8aJTGxQOZgCWphqo2snFL3VZ17_8kB-q_XmLTD3wN3aEOYw11q-JRaeWGhTknkGl6qlDGUOzCrFwckFh_HxiEMYnXIYDcfnRy3i17V2BPqBDEz5IoYrVDnoouiAaZAksxhwi8IB2ieVCT10-t412QaFOvDYLO5aB1vbDancDj-m5kPimwVhoTBEUGgD2q3JgENb2mH32ixIknkMplb3Qt3TI2W102ZwrRVxeJV3HiTJIga0_mcAKhC5JHDPfniCVP6vLWHkfRmfcAhDb0sY_reTRQwTqbNSqBVstSmbDgo1OPKFWViToYMpjiMO44szDhdRk-Gw7zfkaqM6eRG0thuytXQwaHsJLBYEGUqZYlYe_W1VkCTTFq8ItsKtwa3pOfylPsZZRaZCkbN4x5oJZjHLqcBaOsbZ65n2TKGVu8RKyCcWswA3G0mBfbKOKg4TKVT5DbPb5nypleOwZLe00gTfvy4Zhxudaqc5XJF8ICcy5PDJCJQcLCobWDKiYLxJcit--VrG0eaR7fecpe0As5i9266FI7b_Df_lbS4?type=png)

Bonus: `to_thread` **copies the current** `contextvars` into the worker. Request IDs, trace IDs, and similar values still work inside the thread.

* * *

## Proof: three 1-second jobs finish in ~1 second

```python
import asyncio
import time

def blocking_io(n: int) -> str:
    time.sleep(1)  # stand-in for requests.get, file I/O, a sync SDK...
    return f"job {n} done"

async def heartbeat():
    for _ in range(2):
        print("loop is alive")
        await asyncio.sleep(0.5)

async def main():
    start = time.perf_counter()
    results, _ = await asyncio.gather(
        asyncio.gather(*(asyncio.to_thread(blocking_io, i) for i in range(3))),
        heartbeat(),
    )
    print(results, f"in {time.perf_counter() - start:.1f}s")  # ≈ 1.0s, not 3s

asyncio.run(main())
```

![Mermaid Diagram](https://mermaid.ink/img/pako:eNptkE1OwzAQRq8yjMTOlUjCKjt-VNEFGyIQi0po4kwSU8eu7KG0VD0HB-JiqElJi2Dp7z35Wd6i9hVjjg05kbkDABAjliGD0nq9MK4BTdZG-PqEJAKTbgetIuGpDx0JPA8LrU08LOfFz116MXPCYUUWksjau2ogkbUY7-DWBNbSNwbw6ktIINfBiAJKFFwoSOKRpSNLFVAtHHrrVMlGJRuV9Kj8pMW_SBuYql9h0mJWrKD8Nz3S9A_NTmh2oKiw49CRqTDforTc7T-74prerKAalicKhkrLce_U3smUOmM3mOOElkvLk7iJwp2Ca2vc4p500Z-n3omCORbceIbH2RwVPPjSi1dwx3bFYjQpuAqGrIJILk4iB1Oj6iOF-di_JblcrnG3U1g2N976gDmevbdGGHffuRuqMQ?type=png)

The heartbeat keeps ticking while all three jobs run, so the loop was never blocked.

### The same pattern with a real blocking client

Any sync library works the same way. Here it is with the standard library's HTTP client (swap in `requests.get` or a sync SDK, and nothing else changes):

```python
import asyncio
import time
import urllib.request

def fetch(url: str) -> int:
    with urllib.request.urlopen(url, timeout=10) as resp:  # blocking network call
        return len(resp.read())

async def main():
    urls = ["https://httpbin.org/delay/1"] * 3
    start = time.perf_counter()
    sizes = await asyncio.gather(*(asyncio.to_thread(fetch, u) for u in urls))
    print(sizes, f"in {time.perf_counter() - start:.1f}s")  # roughly 1s, not 3s

asyncio.run(main())
```

* * *

## The FastAPI trap

FastAPI runs a plain `def` endpoint in an external threadpool, but an `async def` endpoint runs directly on the event loop. So the classic mistake is marking a handler `async def` and then calling a sync library inside it.

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqF0m1r2zAQB_Cvcru82ZjD4jQ2jRiF7qGk0LGRbmMQlXG2zomoLLmSktRr892H88S6MvZS0vH73x_0gKVTjAIr49blgnyEq6m0AADTlzOJl7Z0tbZz8Hy35BAl3rwSQni-g37_DCYPEidklWEPIbaGJW6EEHc7YdLNPEqk0NoSFFfwGgrjytsOLMkYiY_wYyZxurQBnIW4YOAV2wjGueZt4d-cfVyxbw_psCYdg8QbIURB6mlKY0jbLqVTv84kXlCI518uwXe6jqAtEMSFZ1KNc2bLXznXQIjUBqg8846eO6f-3SC6nztkmzOcSfxsTbvd_Um5rV-7FQeI7pj8Z8IuozQUwgeuupJQaWNEryDOK5WE6N0ti97gJB9TmpTOOC96g9NhNRrvH_trreJCDJv7v7ADpZTKKz5SWTFMi_xADTkd5Nn_qILUHqtKyig7YuNxWqTFARtlAxrQU-zkGdY132unOVdUHrU0z7OT0bFlNuQ0f7YaJlizr0krFA8YF1x3n1dxRUsTMdndfCevqTAcupnK2XhBtTYtCuxT0xjuhzZErhN4Z7S9_UTl9fZ84WxMQOI1zx3Dt0uJCUxd4aJLYMJmxVGXlMC512QSCGRDP7DXFSbbkGv9q9slHTX3uNkkWMzfd1VQ4Iv1QkfGzW-D5yJI?type=png)

```python
# Bad: blocks the loop for every other request
@app.get("/report")
async def report():
    return legacy_client.fetch_report()  # sync SDK call

# Fix A: plain def, FastAPI offloads the whole handler
@app.get("/report")
def report():
    return legacy_client.fetch_report()

# Fix B: stay async, offload only the blocking call
@app.get("/report")
async def report():
    rows = await db.fetch_rows()  # async-native call
    return await asyncio.to_thread(legacy_client.fetch_report, rows)
```

Pick **B** when the handler also awaits other things and only one call is blocking.

* * *

## When should you use it?

![Mermaid Diagram](https://mermaid.ink/img/pako:eNqF09tO20AQBuBXmS4XbaU15OA4YFVUEEqhBzVqSnuBK7S2x_Eqm12zO05iQt698gGqlIveWLZ3_P0zI3nLEpMiC1mmzDrJhSX4cRFpAIDZdhuxX7mg1w5iZZKF1PN3sT06rUxpAVeoCZQxxfuI7XZhGN53n4HnnT5G7EyDcJVOPC1IrhCUjK2wFeBGOnIN9CYnKja8rSvmbyP2CGe3EftUOgKxFpJAUsR-h2E4Nybd98-7luD66FurWbwv0ZHjkEmFjkPNwuzis2vk89uINUnSHJK5o9yiSFu9u9_zJ1BvBigXBBYVCocOKEf4eP2l6164XMmYw0Nz1eWyqNqkfekKxaqCorToTSvKjYbJ9AbWxi7q4sltxKbWJOjc1Bj1YYNJScY2ESspmhUf2lLfSX2H3WHbdWFNEuk2K1HCuQvM4L4eXoUHaZoGGXJH1iwwPBjFg34c8MQoY8ODAfZ7wag79NYypTwcFJt_qHrnnXYcYCaSZ60fBKOh_6T1RgPsB__T2h133jhNh9lfrzcenRyPnr3jQeaf7HvDF149fadlaSzG_rN2IoZ-f_Ck-cO-3xu_6I5xtkS7FDJl4ZZRjsv6L0gxE6Uixts3P4WVIlbo6prMaLoUS6kqFjJPFIVCz1WOcMnhXEm9-CqSWfN8aTRxiNgM5wbh5jpiHL6b2JDhcIVqhSQTweHMSqE4OKGd59DKjPEmZCYf6l76frFhux1n8XxSj8JC9mqdS0K2-wNuaTxG?type=png)

**Rule of thumb:** threads help when the work is _waiting_ (I/O) or runs in C without the GIL. On a standard build, pure-Python number crunching in a thread won't speed up, because only one thread runs Python bytecode at a time, and it competes with your event loop for that lock.

**Free-threaded Python:** the free-threaded build (no GIL) became officially supported in Python 3.14 ([PEP 779](https://peps.python.org/pep-0779/)), but it is still opt-in, not the default. On those builds, threads can run Python code in parallel. Benchmark `to_thread` against processes for your own CPU-heavy workload before choosing.

* * *

## Gotchas

| Gotcha | What to do |
| --- | --- |
| Pool is finite. The default is min(32, cpu_count + 4) workers (os.process_cpu_count() on Python 3.13+). | Cap concurrency with an asyncio.Semaphore, or pass your own executor to loop.run_in_executor. |
| The default executor is shared. to_thread uses the same pool asyncio uses for loop.getaddrinfo() (DNS lookups), so a flood of slow jobs can delay unrelated network calls. | Give heavy or slow jobs a dedicated ThreadPoolExecutor with loop.run_in_executor(my_pool, fn). |
| Cancellation doesn't kill the thread. Cancelling the awaiting task stops the await, but the thread runs to completion. | Give blocking calls their own timeouts (requests.get(..., timeout=10)). |
| Thread safety is on you. Shared mutable state needs locks. | Prefer returning values over mutating globals. |
| Don't call asyncio APIs from the worker thread. | Use asyncio.run_coroutine_threadsafe(coro, loop) to talk back to the loop. |

* * *

## Takeaways

1.  **Never block the loop.** One sync call can stall every request, in plain asyncio and in FastAPI.
    
2.  **Wrap blocking I/O with** `await asyncio.to_thread(fn, *args)`**.** It's the simplest fix and the loop stays responsive.
    
3.  **Pair it with** `asyncio.gather` to run blocking jobs concurrently.
    
4.  **Know the limits:** the pool is finite and shared, cancellation doesn't stop the thread, and on standard builds the GIL means no CPU speedup. For heavy CPU work, use processes.
    

_Requires Python 3.9+._

---

*Published via [ZyVOP](https://zyvop.com/asyncio-to-thread-stop-freezing-your-event-loop-pfbpf?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
