pythonbeginner
Tenacity Retry with Backoff
Add robust retry logic with exponential backoff, jitter, and conditional retry using the tenacity library.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
Retry Decorator with Exponential Backoff
Generic retry decorator with configurable attempts, exponential backoff, and exception filtering.
Best for: Network request resilience
#decorator#retry
typescriptintermediate
Retry with Exponential Backoff
Retry failed async operations with exponential backoff, jitter, and configurable retry conditions.
Best for: API call resilience
#nodejs#retry
pythonintermediate
Retry Logic for Data Pipelines
Configurable retry decorator with exponential backoff and jitter for resilient data pipeline tasks.
Best for: Resilient API calls in data pipelines
#retry#resilience
pythonintermediate
Tenacity Retry for Pipeline Resilience
Add exponential backoff retries to flaky data pipeline steps using Tenacity.
Best for: resilient API calls
#tenacity#retry