Threads vs processes vs asyncio: how do you choose?
IntermediateConceptConcurrency: threads, processes & asyncio
Answer
- Threads (
ThreadPoolExecutor): I/O bound, sync libraries (boto3, requests, paramiko), tens to a few hundred concurrent tasks. - Processes (
ProcessPoolExecutor,multiprocessing): CPU bound; each process has its own interpreter and GIL. Higher memory and startup cost; arguments and results must be picklable. - asyncio: thousands of concurrent I/O tasks with async libraries (httpx, aiohttp, asyncssh), single thread, cooperative scheduling. Every library in the path must be async.
Our default for ops tooling is threads, because boto3 is synchronous.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerWhat is a race condition, and how do you prevent one in threaded code?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedWhat are coroutines, `async def` and `await`?IntermediateHow do you run many async tasks concurrently with a limit?Intermediate