How do you add timeouts to async operations?
IntermediateConceptConcurrency: threads, processes & asyncio
Answer
try:
async with asyncio.timeout(10): # 3.11+
data = await fetch_all()
except TimeoutError:
log.error("fetch_all exceeded 10s")
result = await asyncio.wait_for(fetch_one(), timeout=3) # older API
A timeout cancels the inner task by raising CancelledError inside it, so cleanup code in finally blocks runs. Also set client-level timeouts (httpx/aiohttp) so individual requests cannot hang.
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?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateWhat 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`?Intermediate