Stamina: Production-Grade Retries

25.2.0 · active · verified Fri Apr 10

Stamina is a Python library that provides production-grade retries made easy, acting as an opinionated wrapper around Tenacity. It ensures resilient systems by handling transient failures with sensible defaults like exponential backoff with jitter, configurable exception handling, and automatic async support. It releases regularly, typically every few months, and is designed to minimize potential for misuse.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using the `@stamina.retry` decorator with `httpx` to handle transient HTTP errors. It configures retries for `httpx.HTTPStatusError` but includes a custom check to only retry on 5xx status codes, explicitly not retrying on 4xx client errors, and limits attempts and total timeout.

import httpx
import stamina
import os

@stamina.retry(on=httpx.HTTPStatusError, attempts=3, timeout=5)
def fetch_url_with_retry(url: str) -> str:
    try:
        response = httpx.get(url, timeout=1)
        response.raise_for_status() # Raises HTTPStatusError for 4xx/5xx responses
        return f"Successfully fetched: {response.status_code}"
    except httpx.HTTPStatusError as e:
        # Example: only retry on 5xx errors
        if e.response.status_code >= 500:
            print(f"Retrying on {e.response.status_code} for {url}...")
            raise
        else:
            print(f"Not retrying on {e.response.status_code} for {url}.")
            raise
    except httpx.RequestError as e:
        print(f"Request error for {url}: {e}, retrying...")
        raise

# Example usage:
try:
    # This URL will fail with 500 and retry
    print(fetch_url_with_retry("https://httpbin.org/status/500"))
except (httpx.HTTPStatusError, httpx.RequestError) as e:
    print(f"Final failure after retries for 500: {e}")

try:
    # This URL will fail with 404 and not retry (due to the if e.response.status_code >= 500 check)
    print(fetch_url_with_retry("https://httpbin.org/status/404"))
except (httpx.HTTPStatusError, httpx.RequestError) as e:
    print(f"Final failure for 404 (not retried): {e}")

try:
    # This URL will succeed
    print(fetch_url_with_retry("https://httpbin.org/status/200"))
except (httpx.HTTPStatusError, httpx.RequestError) as e:
    print(f"Unexpected failure for 200: {e}")

view raw JSON →