python-async-no-blocking-calls
Narrow trigger extracted from skills/python-conventions §4.4–§4.5, so a blocking call inside async
code routes here directly instead of only through the whole Python block.
When
Writing or reviewing an async def that calls a synchronous HTTP client, reads a file, sleeps, does
a DNS lookup, runs a subprocess, logs through a network handler, or runs any CPU-heavy work — anything not
itself await-able.
Steps
- Never mix blocking code into an
async function without isolating it. A blocking call delays every
other task and I/O operation on the loop by its whole duration, not just its caller.
- This is the failure mode described as "the whole service got slow while one report was
generating." One coroutine stalls every other request in the process, not only its own caller.
- The blocking call is usually not obvious. A synchronous HTTP client, a plain file read,
time.sleep,
subprocess.run, a direct socket.getaddrinfo, a log handler that writes to the network — none of these
look like I/O at the call site, but none of them yield to the event loop either.
- Pick the isolation by the kind of work.
- Blocking I/O:
asyncio.to_thread(func, ...) (Python 3.9+, copies the context variables) or
loop.run_in_executor(None, func, ...), which uses the loop's default thread pool.
- CPU-bound pure Python: a
ProcessPoolExecutor through run_in_executor. The function and its arguments
must be picklable and the entry point needs the if __name__ == "__main__": guard. A thread does not
give pure-Python code a real speedup because of the GIL; it helps mainly with I/O, or with extensions
that release the GIL.
- Subprocesses:
asyncio.create_subprocess_exec, and communicate() rather than wait() when output is
piped (wait() can deadlock once the pipe buffer fills).
- Files:
aiofiles or to_thread; the loop has no native file API, so both end up on a thread pool.
- A thread pool is a shared, finite resource. The default executor also runs the loop's own
getaddrinfo
and getnameinfo; when it is saturated, DNS lookups queue and higher layers report timeouts. Give heavy
blocking work its own executor, or size the default one on purpose.
- Find the culprits at run time. Debug mode (
PYTHONASYNCIODEBUG=1, asyncio.run(..., debug=True) or
Development Mode) logs any callback slower than loop.slow_callback_duration, 100 ms by default. Run it
in tests or staging, not as a production default.
- In a web framework, check what the framework already does. FastAPI runs a plain
def path operation
or dependency in a threadpool and does not do so for an async def one; a handler that must call a
blocking library and has no await should be def, not async def.
Output / checkpoint
Every synchronous or CPU-heavy operation reached from an async def is either replaced by its async
equivalent or explicitly isolated (to_thread, run_in_executor, a process pool) — nothing blocking runs
directly on the event loop's thread. A test or staging run in debug mode shows no slow-callback warning on the
changed path.
Guardrails
- A library labelled "async-compatible" is not proof — check whether its actual I/O call is
non-blocking, not just whether it exposes an
async def wrapper. Some async file libraries only run the
blocking call in a thread pool for you: fine, but then the pool size is your concern.
- Do not "fix" CPU-bound code by moving it to a thread and calling it done; see step 4.
- Hold a strong reference to a task you start with
create_task (a set with a done callback, or a
TaskGroup); the loop keeps only weak ones, and a dropped task can vanish before it finishes.
- The full
gather/concurrency-bound argument this section opens with lives in
skills/python-conventions §4 — read it before assuming asyncio.gather alone fixes a blocking
call.
Origin
Extracted from skills/python-conventions §4.4–§4.5 (2026-09-09), then checked on 2026-10-20 against the
Python asyncio documentation (facts only) and the FastAPI (MIT), AnyIO (MIT) and aiofiles (Apache-2.0)
documentation. Sources, licences and what stays unsourced are in
references/origin.md. 🟡: never run by us.
1---2name: python-async-no-blocking-calls3description: "Use when writing or reviewing an async function: never mix synchronous I/O or heavy CPU work in without isolating it (run_in_executor, to_thread, a process pool) — it blocks the whole event loop."4metadata:5 source: https://skillmd.com/skills/techmefr/python-async-no-blocking-calls6---78# python-async-no-blocking-calls910Narrow trigger extracted from `skills/python-conventions` §4.4–§4.5, so a blocking call inside async11code routes here directly instead of only through the whole Python block.1213## When14Writing or reviewing an `async def` that calls a synchronous HTTP client, reads a file, sleeps, does15a DNS lookup, runs a subprocess, logs through a network handler, or runs any CPU-heavy work — anything not16itself `await`-able.1718## Steps191. **Never mix blocking code into an `async` function without isolating it.** A blocking call delays every20 other task and I/O operation on the loop by its whole duration, not just its caller.212. **This is the failure mode described as "the whole service got slow while one report was22 generating."** One coroutine stalls every other request in the process, not only its own caller.233. **The blocking call is usually not obvious.** A synchronous HTTP client, a plain file read, `time.sleep`,24 `subprocess.run`, a direct `socket.getaddrinfo`, a log handler that writes to the network — none of these25 look like I/O at the call site, but none of them yield to the event loop either.264. **Pick the isolation by the kind of work.**27 - Blocking I/O: `asyncio.to_thread(func, ...)` (Python 3.9+, copies the context variables) or28 `loop.run_in_executor(None, func, ...)`, which uses the loop's default thread pool.29 - CPU-bound pure Python: a `ProcessPoolExecutor` through `run_in_executor`. The function and its arguments30 must be picklable and the entry point needs the `if __name__ == "__main__":` guard. A thread does not31 give pure-Python code a real speedup because of the GIL; it helps mainly with I/O, or with extensions32 that release the GIL.33 - Subprocesses: `asyncio.create_subprocess_exec`, and `communicate()` rather than `wait()` when output is34 piped (`wait()` can deadlock once the pipe buffer fills).35 - Files: `aiofiles` or `to_thread`; the loop has no native file API, so both end up on a thread pool.365. **A thread pool is a shared, finite resource.** The default executor also runs the loop's own `getaddrinfo`37 and `getnameinfo`; when it is saturated, DNS lookups queue and higher layers report timeouts. Give heavy38 blocking work its own executor, or size the default one on purpose.396. **Find the culprits at run time.** Debug mode (`PYTHONASYNCIODEBUG=1`, `asyncio.run(..., debug=True)` or40 Development Mode) logs any callback slower than `loop.slow_callback_duration`, 100 ms by default. Run it41 in tests or staging, not as a production default.427. **In a web framework, check what the framework already does.** FastAPI runs a plain `def` path operation43 or dependency in a threadpool and does not do so for an `async def` one; a handler that must call a44 blocking library and has no `await` should be `def`, not `async def`.4546## Output / checkpoint47Every synchronous or CPU-heavy operation reached from an `async def` is either replaced by its async48equivalent or explicitly isolated (`to_thread`, `run_in_executor`, a process pool) — nothing blocking runs49directly on the event loop's thread. A test or staging run in debug mode shows no slow-callback warning on the50changed path.5152## Guardrails53- A library labelled "async-compatible" is not proof — check whether its actual I/O call is54 non-blocking, not just whether it exposes an `async def` wrapper. Some async file libraries only run the55 blocking call in a thread pool for you: fine, but then the pool size is your concern.56- Do not "fix" CPU-bound code by moving it to a thread and calling it done; see step 4.57- Hold a strong reference to a task you start with `create_task` (a set with a done callback, or a58 `TaskGroup`); the loop keeps only weak ones, and a dropped task can vanish before it finishes.59- The full `gather`/concurrency-bound argument this section opens with lives in60 `skills/python-conventions` §4 — read it before assuming `asyncio.gather` alone fixes a blocking61 call.6263## Origin64Extracted from `skills/python-conventions` §4.4–§4.5 (2026-09-09), then checked on 2026-10-20 against the65Python asyncio documentation (facts only) and the FastAPI (MIT), AnyIO (MIT) and aiofiles (Apache-2.0)66documentation. Sources, licences and what stays unsourced are in67[`references/origin.md`](./references/origin.md). 🟡: never run by us.