Asyncio Retry Utility

6.3.1 · active · verified Fri Apr 17

aioretry is an asyncio utility for Python 3.7+ that provides flexible retry mechanisms for asynchronous operations. It supports various retry policies, including fixed delay, exponential backoff, and custom strategies, handling transient failures in async code gracefully. The current version is 6.3.1, and it maintains an 'active' release cadence with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using the `@retry` decorator with a custom asynchronous retry policy. The `flaky_async_call` function simulates transient failures, and `my_retry_policy` specifies when to give up and how long to delay between attempts.

import asyncio
from aioretry import retry, RetryInfo, RetryPolicyStrategy

fail_count = 0

async def my_retry_policy(info: RetryInfo) -> RetryPolicyStrategy:
    """Retry up to 3 times, with increasing delay."""
    # (should_give_up, delay_in_seconds)
    return info.fails >= 3, info.fails * 0.5

@retry(policy=my_retry_policy)
async def flaky_async_call():
    global fail_count
    fail_count += 1
    print(f"Attempt {fail_count}: Making a flaky call...")
    if fail_count < 3: # Succeed on the 3rd attempt
        raise ConnectionError("Simulated network issue")
    print(f"Attempt {fail_count}: Call succeeded!")
    return "Data Fetched"

async def main():
    print("Starting main program...")
    try:
        result = await flaky_async_call()
        print(f"Final Result: {result}")
    except Exception as e:
        print(f"Operation failed after retries: {e}")
    print("Program finished.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →