Sub topic 10
Setting timeouts
What you need first
This chapter assumes you can write coroutines and tasks, and that you know how cancellation works: task.cancel() raises CancelledError inside the task at its current await. The examples use Python 3.11 or later.
Why timeouts matter
An await on a network call or a queue can wait forever. A peer may never answer, a connection may hang half-open, or a producer may stop sending. Without a limit, one stuck coroutine can hold a task, a semaphore slot, or a connection indefinitely. A timeout turns "wait forever" into a bounded wait followed by an error you can handle.
asyncio has no special timer facility for this. A timeout is built from cancellation. When the time limit passes, the event loop cancels the waiting task. The timeout machinery then converts the resulting CancelledError into a TimeoutError.
asyncio.timeout
asyncio.timeout(delay) is an async context manager. It limits everything awaited inside its block.
import asyncio
async def slow():
await asyncio.sleep(5)
async def main():
try:
async with asyncio.timeout(0.5):
await slow()
except TimeoutError:
print("timed out")
asyncio.run(main())The program prints timed out after about half a second. Four things happen:
- The block starts and the loop schedules a callback for 0.5 seconds later.
- The callback fires and cancels the task that is running the block.
CancelledErroris raised at the currentawaitinsideslow(). It propagates up and finishes the task's work in the block.- On exit, the context manager sees that the cancellation came from its own deadline and raises
TimeoutErrorinstead.
Since Python 3.11, asyncio.TimeoutError is just another name for the built-in TimeoutError. In new code, write except TimeoutError.
wait_for
asyncio.wait_for(awaitable, timeout) applies a timeout to a single awaitable and returns its result.
import asyncio
async def fetch():
await asyncio.sleep(1)
return "data"
async def main():
try:
result = await asyncio.wait_for(fetch(), timeout=0.2)
except TimeoutError:
result = None
print(result)
asyncio.run(main())This prints None. If the awaitable is a bare coroutine, wait_for cancels it on timeout and waits for the cancellation to finish before raising. If it takes the cleanup a long time, the TimeoutError is delayed by that long.
Use wait_for when you limit one call and want its value in a single expression. Use timeout() when one limit covers several steps, or when you want to inspect or change the deadline.
| Feature | `asyncio.timeout` | `asyncio.wait_for` |
|---|---|---|
| Form | Async context manager | Awaited function call |
| Covers | Every `await` in the block | One awaitable |
| Deadline can be changed | Yes, with `reschedule` | No |
| Can tell if it expired | Yes, with `expired()` | Only through the exception |
| Available since | Python 3.11 | Python 3.4 |
Absolute deadlines and rescheduling
A relative timeout restarts each time you create it. If a function makes three calls in sequence and each uses timeout(1), the function can take three seconds. To bound the whole operation, compute one deadline using the loop's clock and use asyncio.timeout_at.
import asyncio
async def step(name, duration):
await asyncio.sleep(duration)
print("finished", name)
async def main():
loop = asyncio.get_running_loop()
deadline = loop.time() + 1.0
try:
async with asyncio.timeout_at(deadline):
await step("one", 0.4)
await step("two", 0.4)
await step("three", 0.4)
except TimeoutError:
print("deadline passed")
asyncio.run(main())Steps one and two finish. Step three is cut off at the one-second mark, and the program prints deadline passed. The deadline is a value from loop.time(), which is a monotonic clock. It is not a wall-clock time and it is not comparable to time.time().
The object returned by async with lets you move the deadline while the block runs. It also reports whether the deadline was what ended the block.
import asyncio
async def main():
loop = asyncio.get_running_loop()
try:
async with asyncio.timeout(1) as cm:
await asyncio.sleep(0.5)
cm.reschedule(loop.time() + 2)
await asyncio.sleep(1.5)
print("finished")
except TimeoutError:
print("timed out")
print("expired:", cm.expired())
asyncio.run(main())At 0.5 seconds the deadline moves to 2.5 seconds, so the 2.0 seconds of total work fits. The program prints finished and expired: False. You can also call cm.reschedule(None) to remove the deadline, and asyncio.timeout(None) creates a block with no deadline to begin with. That is handy for code where the limit is optional.
Telling your timeout apart from others
TimeoutError is a normal exception, and other code raises it too. A socket library may raise it for its own limit, for example. Catching TimeoutError around a block cannot tell you whose timeout fired. Check cm.expired() when it matters:
import asyncio
async def main():
try:
async with asyncio.timeout(1) as cm:
raise TimeoutError("raised by inner code")
except TimeoutError:
print("our deadline expired:", cm.expired())
asyncio.run(main())This prints our deadline expired: False, because the exception came from inside the block and not from the timer.
Cleanup and swallowed cancellation
Because a timeout is a cancellation, code inside the block can run finally blocks and except CancelledError handlers. Cleanup is normal and expected:
import asyncio
async def worker():
try:
await asyncio.sleep(10)
finally:
print("releasing resources")
async def main():
try:
async with asyncio.timeout(0.2):
await worker()
except TimeoutError:
print("timed out")
asyncio.run(main())The output is releasing resources, then timed out.
Timeouts and TaskGroup
A timeout around a TaskGroup bounds the whole group. When the deadline passes, the host task is cancelled. The group cancels its remaining child tasks, waits for them, and the outer timeout converts the result into TimeoutError. Put timeout on the outside, as in the TaskGroup chapter's example:
import asyncio
async def fetch(n, delay):
await asyncio.sleep(delay)
return n * 2
async def main():
try:
async with asyncio.timeout(1):
async with asyncio.TaskGroup() as tg:
fast = tg.create_task(fetch(1, 0.2))
slow = tg.create_task(fetch(2, 3))
except TimeoutError:
print("group timed out")
print("fast finished:", fast.done() and not fast.cancelled())
print("slow cancelled:", slow.cancelled())
asyncio.run(main())To limit one child instead, put the timeout inside the child coroutine. Remember that a TimeoutError raised inside a child and not caught there counts as a task failure. The group then cancels its siblings and raises an ExceptionGroup, which you handle with except*.
Letting work survive a timeout
Sometimes the caller should stop waiting, but the work should continue, such as a write that must complete. asyncio.shield protects the inner task from the cancellation that wait_for sends.
import asyncio
async def job():
await asyncio.sleep(0.5)
return "finished"
async def main():
task = asyncio.create_task(job())
try:
await asyncio.wait_for(asyncio.shield(task), timeout=0.2)
except TimeoutError:
print("still running:", not task.done())
print(await task)
asyncio.run(main())The output is still running: True, then finished. You now own the task. Keep a reference to it and await it later, or it may be lost and its exceptions never seen.
asyncio.wait(tasks, timeout=...) behaves differently from both tools above. When the time passes, it returns (done, pending) sets and does not cancel anything and does not raise. You decide what to do with the pending tasks.
Choosing a timeout value
- Set timeouts at the boundary of an external call, such as an HTTP request, a database query, or a queue read.
- Prefer a deadline for a multi-step operation, and a relative timeout for a single call.
- A timeout does not interrupt blocking code. If a coroutine calls
time.sleep()or a CPU-heavy function, the loop cannot run the cancellation callback until that call returns. Move blocking work toasyncio.to_thread. Even then, the thread keeps running after a timeout. Only the wait for it is cancelled. - Log the timeout with the operation's name. A bare
TimeoutErrorgives you no hint where it came from.
Exercise
Write a coroutine first_ok(coros_factories, per_call, total) that tries each zero-argument coroutine factory in order. Each attempt gets at most per_call seconds, and the whole function must give up after total seconds. It should return the first successful result, or None if none succeed in time. Which tools do you use, and why is a shared deadline better than only using per_call?
Show answer
Use one outer asyncio.timeout(total) (or timeout_at with a deadline computed from loop.time()) and, inside it, a loop that wraps each attempt in asyncio.timeout(per_call). For example: try: async with asyncio.timeout(total): for make in coros_factories: try: async with asyncio.timeout(per_call): return await make() except TimeoutError: continue except TimeoutError: pass, then return None. The outer block's TimeoutError is caught by the outer except, and a per-call TimeoutError is caught by the inner one and moves on to the next factory. Using only per_call would let the total time grow to per_call times the number of factories. The shared deadline bounds the whole operation. Note that the inner timeout never extends the outer one, because nested timeouts expire at whichever deadline comes first.
Exercise
A coroutine inside async with asyncio.timeout(1): contains try: await asyncio.sleep(5) except asyncio.CancelledError: print("ignored") and then continues to await asyncio.sleep(1) and returns normally. What does the caller see, and how should the code be fixed?
Show answer
The block does not end with a clean TimeoutError at one second. The coroutine swallows the cancellation, then runs the second sleep and returns, so the timeout fails to stop the work. The fix is to re-raise after cleanup: except asyncio.CancelledError: print("cleaning up"); raise. Then the cancellation reaches the async with block, which raises TimeoutError to the caller.