Lesson 6 of 9 · 22m
Mixing asyncio with Threads, Processes, and Legacy Blocking Code
When to use asyncio.to_thread, when to use ProcessPoolExecutor, how loop.run_in_executor really works, and how to cross the sync-async boundary safely.
You will not greenfield your way out of blocking Python. Legacy database drivers, PDF generators, image processing, cryptographic verification, and vendor SDKs all show up in real services. The correct question is not 'is this pure async?' It is 'which execution model owns this work, and how do we keep it from stalling the event loop?'
asyncio.to_thread is the default escape hatch
import asyncio
async def render_pdf(report_id):
data = await load_report(report_id)
pdf_bytes = await asyncio.to_thread(build_pdf_with_blocking_sdk, data)
return pdf_bytesto_thread() runs the callable in a worker thread and returns an awaitable. The event loop remains responsive while the blocking SDK occupies one thread. This is appropriate for I/O-bound or moderately CPU-bound calls that release the GIL, and occasionally for Python CPU work if latency matters more than throughput.
Threads do not create infinite capacity. Python's default executor is finite, and every queued job is memory plus latency. Put explicit concurrency limits around expensive operations.
CPU-bound Python needs processes
from concurrent.futures import ProcessPoolExecutor
pool = ProcessPoolExecutor(max_workers=4)
async def resize_image(payload):
loop = asyncio.get_running_loop()
return await loop.run_in_executor(pool, resize_blocking, payload)Pure Python number crunching in threads still fights over the GIL. Processes have separate interpreters and real parallelism, but payloads cross process boundaries by pickle. Large arrays, non-pickleable objects, and chatty APIs make process pools painful. If the workload is large, isolate it as a worker service or use native libraries that release the GIL.
Calling async code from sync code is a boundary crossing
Do not casually call asyncio.run() inside a thread or inside a running event loop:
# bad inside a service request path
result = asyncio.run(fetch_remote()) # creates a whole second loopEach loop owns its tasks, clients, and synchronization primitives. Objects created on one loop generally cannot be awaited or used on another. Design explicit boundaries: a synchronous CLI can use asyncio.run() once; a sync library callback should push work onto a thread-safe queue or schedule with loop.call_soon_threadsafe().
def sync_callback(message):
loop.call_soon_threadsafe(queue.put_nowait, message)This is safe because call_soon_threadsafe is designed for cross-thread scheduling. Directly mutating asyncio objects from other threads is not.
subprocesses are already async-aware
proc = await asyncio.create_subprocess_exec(
'ffmpeg', '-i', src, '-f', 'mp4', dst,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)Use create_subprocess_exec rather than shell strings unless you truly need shell expansion. Beware communicate() buffering large output; stream it or redirect to files for long-running tools.
Field notes
asyncio.to_threadrequires Python 3.9+; older code may userun_in_executordirectly.- Do not share database connections, SQLite objects, or file handles across threads unless their documentation explicitly allows it.
- A blocking call with no timeout is still a blocking call in a thread. Add deadlines at the SDK or socket level where possible.
- Process pools need clean shutdown. During deploys, stop submitting before terminating or you will abandon work in unpredictable states.
Was this lesson helpful?