tenacity
Retry any Python function with exponential backoff, jitter, and custom stop conditions — three decorator lines replace 30 lines of retry logic.
External APIs fail. Network calls time out. Databases hiccup. Without retry logic, your application crashes on the first transient failure. Writing retry loops by hand is repetitive, error-prone, and hard to configure correctly.
tenacity decorates your function with retry behavior. You declare when to stop (max attempts, timeout), how to wait between attempts (fixed, exponential, random), and what to retry on (exception types, return values). The decorator handles the loop, logging, and re-raising.
Retry an API call with exponential backoff
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import httpx
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=1, max=10),
retry=retry_if_exception_type(httpx.HTTPError),
)
def fetch_data(url: str) -> dict:
response = httpx.get(url, timeout=5)
response.raise_for_status()
return response.json()
# Will retry up to 3 times with 1s, 2s, 4s delays
data = fetch_data('https://api.example.com/data')Use it when
Any I/O that can fail transiently: HTTP calls, database queries, queue operations, cloud API calls, file system operations on network drives.
Skip it when
Don't retry non-idempotent operations (POST that creates resources) without careful thought. Don't retry errors that won't resolve with time (auth failures, 400 Bad Request).
Ready to explore the full API?
See every class, function, and relationship in an interactive graph.