pythonbeginner

Tenacity Retry with Backoff

Add robust retry logic with exponential backoff, jitter, and conditional retry using the tenacity library.

python
from tenacity import (
    retry,
    stop_after_attempt,
    wait_exponential,
    retry_if_exception_type,
    before_sleep_log,
)
import logging

logger = logging.getLogger(__name__)

@retry(
    stop=stop_after_attempt(5),
    wait=wait_exponential(multiplier=1, min=1, max=30),
    retry=retry_if_exception_type((ConnectionError, TimeoutError)),
    before_sleep=before_sleep_log(logger, logging.WARNING),
    reraise=True,
)
async def call_external_api(url: str) -> dict:
    import httpx
    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.get(url)
        response.raise_for_status()
        return response.json()

# Usage:
# result = await call_external_api("https://api.example.com/data")

Use Cases

  • Flaky API calls
  • Network retry logic
  • Database reconnection

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.