Python asyncio Recipes/Retry an async operation

Retry with simple exponential backoff.

Section: Retries and Resilience

Retry an async operation

python
python
import asyncio

attempts = 0

async def flaky():
    global attempts
    attempts += 1
    if attempts < 3:
        raise RuntimeError("temporary failure")
    return "ok"

async def with_retry():
    delay = 0.2
    for _ in range(5):
        try:
            return await flaky()
        except RuntimeError:
            await asyncio.sleep(delay)
            delay *= 2
    raise RuntimeError("exhausted retries")

print(asyncio.run(with_retry()))
Explanation

Keep retries bounded and cancellation-aware in production systems.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Retries and Resilience
Cancel cleanly on shutdown
Maintain and cancel outstanding tasks at shutdown time.
OpenIn sheetpythonsame section
Bound a worker pool with Semaphore
Throttle async work to a safe level.
Inspect running tasks
List currently active tasks in the running loop.
Process input in batches
Break large workloads into fixed-size async chunks.
Enable asyncio debug mode
Turn on extra diagnostics while developing.