Sub topic 10
Deadlines with asyncio.timeout
This chapter assumes Python 3.11 or newer and that you can write coroutines with async/await. It also assumes you know try/finally, async with, and how Task.cancel() raises CancelledError (covered in the cancellation chapters). asyncio.timeout builds directly on that mechanism.
What asyncio.timeout does
asyncio.timeout(delay) is an async context manager. It sets a deadline for everything awaited inside its block. If the block is still running when the deadline passes, the code inside is cancelled and TimeoutError is raised.
import asyncio
async def main():
try:
async with asyncio.timeout(0.5):
await asyncio.sleep(2)
except TimeoutError:
print("timed out")
asyncio.run(main())The try sits outside the async with. The exception is raised when the block exits, not at the line that was interrupted. Any code after the slow await inside the block never runs.
How it works internally
When you enter the block, the context manager asks the event loop to run a callback at the deadline. When the callback fires, it calls cancel() on the task that entered the block. That task receives CancelledError at its current await. On the way out of the block, the context manager checks whether the cancellation came from its own deadline. If so, it replaces CancelledError with TimeoutError. Cancellations that came from somewhere else pass through unchanged. It tells them apart by counting requests with Task.cancelling() and Task.uncancel(), which a later chapter covers.
Cleanup inside the block
Because the interruption is a normal cancellation, finally blocks and context managers inside the timeout still run. Resources are released before TimeoutError reaches your handler.
import asyncio
async def main():
try:
async with asyncio.timeout(0.2):
try:
await asyncio.sleep(5)
finally:
print("cleanup ran")
except TimeoutError:
print("timed out")
asyncio.run(main())This prints cleanup ran first, then timed out.
Inspecting and moving the deadline
async with asyncio.timeout(...) as cm gives you a Timeout object. It has three useful members:
cm.when()returns the current deadline as a loop-clock value, orNoneif no deadline is set.cm.reschedule(when)changes the deadline. PassingNoneremoves it.cm.expired()reports whether the deadline fired. It is still readable after the block.
import asyncio
async def main():
loop = asyncio.get_running_loop()
try:
async with asyncio.timeout(1.0) as cm:
print("deadline set:", cm.when() is not None)
cm.reschedule(loop.time() + 0.2)
await asyncio.sleep(0.5)
except TimeoutError:
print("expired:", cm.expired())
asyncio.run(main())The deadline is shortened from 1.0 s to 0.2 s, so the sleep is interrupted and the program prints deadline set: True and then expired: True.
asyncio.timeout(None) starts with no deadline. You can call reschedule later, for example to push the deadline out each time a message arrives from a peer, which gives an idle timeout instead of a total timeout.
Relative and absolute deadlines
| Function | Argument | Typical use |
|---|---|---|
| `asyncio.timeout(delay)` | Seconds from now, or `None` | A budget for one block |
| `asyncio.timeout_at(when)` | Absolute time on the loop clock | One deadline shared by several steps or functions |
The loop clock is loop.time(), a monotonic clock. It is not time.time(). Passing a wall-clock value to timeout_at gives a deadline far in the future.
timeout_at suits request handling: compute deadline = loop.time() + 2.0 once, pass deadline down the call chain, and let each layer open asyncio.timeout_at(deadline). Every layer then respects the same total budget, however much time earlier steps used.
One budget for several steps
A single timeout around several awaits limits the total time, not each await. Anything you want to keep must live outside the block, because the exception skips the rest of the block.
import asyncio
async def step(n):
await asyncio.sleep(0.2)
return n
async def main():
results = []
try:
async with asyncio.timeout(0.5):
for n in range(5):
results.append(await step(n))
except TimeoutError:
print("partial results:", results)
asyncio.run(main())Steps 0 and 1 finish at 0.2 s and 0.4 s. Step 2 would finish at 0.6 s, so the deadline cancels it. The output is partial results: [0, 1].
Nested timeouts
Each timeout block tracks its own deadline. The earliest deadline fires first, and each block raises TimeoutError only for its own expiry.
import asyncio
async def main():
try:
async with asyncio.timeout(2):
try:
async with asyncio.timeout(0.1):
await asyncio.sleep(1)
except TimeoutError:
print("inner timed out, continuing")
await asyncio.sleep(0.1)
print("outer still fine")
except TimeoutError:
print("outer timed out")
asyncio.run(main())The inner TimeoutError is caught by the inner handler. The outer block's 2-second budget is unaffected, so the program prints inner timed out, continuing and then outer still fine.
If the outer deadline were the one to pass, the inner block would let that cancellation through, and TimeoutError would come from the outer block. This works because each manager only claims cancellations it requested.
Common errors
Swallowing CancelledError
If code inside the block catches CancelledError and does not re-raise it, the timeout cannot convert it. The deadline fires, but the block exits normally and no TimeoutError appears.
import asyncio
async def main():
async with asyncio.timeout(0.1) as cm:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
print("swallowed")
print("no TimeoutError, expired =", cm.expired())
asyncio.run(main())The program continues after the block as if nothing went wrong. Catch CancelledError only to clean up, and re-raise it.
Blocking code ignores the deadline
Cancellation is delivered at an await. A call such as time.sleep(3), or a long CPU-bound loop with no await, never returns control to the event loop. The deadline callback cannot run until that code finishes. The timeout then fires late, at the next await. Move blocking work to a thread with asyncio.to_thread, and keep in mind that the thread itself cannot be cancelled.
Catching the exception in the wrong place
Putting try/except TimeoutError inside the async with block catches nothing from that block. The TimeoutError is raised by the context manager on exit, so the handler must wrap the async with.
Mistaking a different TimeoutError
From Python 3.11, asyncio.TimeoutError is an alias of the built-in TimeoutError. A TimeoutError raised by a socket or other library inside your block is the same type. Do not assume any TimeoutError came from your deadline. When it matters, check cm.expired().
Exercise
A coroutine runs async with asyncio.timeout(1): around await asyncio.sleep(3). Where must the except TimeoutError clause go for it to catch the exception, and does code placed after the sleep inside the block run?
Show answer
The except TimeoutError must wrap the whole async with statement, because the context manager raises TimeoutError when the block exits. Code after the sleep inside the block does not run, since sleep is cancelled at the deadline. finally blocks inside the block still run.
Exercise
You have a request handler that calls three services in sequence and must finish within 2 seconds in total. Which approach gives the correct total limit: three separate asyncio.timeout(2) blocks, or one asyncio.timeout(2) around all three calls? How would you pass the same limit into a helper function in another module?
Show answer
One asyncio.timeout(2) around all three calls gives a 2-second total, because separate blocks would each allow 2 seconds, for up to 6 seconds in all. To share the limit with a helper, compute deadline = loop.time() + 2 once and have each layer use asyncio.timeout_at(deadline).