Bound Cumulative Retry Time with Deadlines
Core idea
A retry policy needs a maximum attempt count, explicitly retryable failures, and a total time budget. asyncio.timeout_at uses the event loop monotonic clock and an absolute deadline; wrap the whole retry loop so attempts and delays share the budget. Retry only operations safe to repeat (or protected by idempotency). Do not catch cancellation as a retryable failure.
import asyncio
async def main(): attempts=0 async def fetch(): nonlocal attempts attempts+=1 if attempts==1: raise ConnectionError('temporary') return 'ready' async def retry(): for i in range(3): try: return await fetch() except ConnectionError: if i==2: raise await asyncio.sleep(0) print(await retry(), attempts)
asyncio.run(main())The first simulated failure is retried once. sleep(0) is a teaching yield, not production backoff.
Expected output:
ready 2Expire a shared absolute deadline
import asyncio
async def main(): deadline=asyncio.get_running_loop().time() try: async with asyncio.timeout_at(deadline): await asyncio.Event().wait() except TimeoutError: print('budget exhausted')
asyncio.run(main())An already due deadline cancels the suspended operation. A future deadline would use loop.time()+budget.
Expected output:
budget exhaustedCommon mistake
Resetting a full timeout on every retry can exceed the intended total budget. Do not retry validation errors or non-idempotent side effects blindly. Real backoff should be bounded and cancellation should propagate; deadlines cannot forcibly stop blocking code.
Practice
Wrap retry in timeout_at(loop.time()+budget). For a deterministic timeout test use an unset event and an already expired deadline; test the max-attempt policy separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async retry and deadlines
Check your understanding of async retry and deadlines.
What is printed?
import asyncio
async def main(): try: async with asyncio.timeout_at(asyncio.get_running_loop().time()): await asyncio.Event().wait() except TimeoutError: print('stop')
asyncio.run(main())What is printed?
import asyncio
async def main(): attempts=[] for i in range(3): attempts.append(i) if i==1: break print(len(attempts))
asyncio.run(main())Where should a total timeout be applied?
Which failure should a retry catch?