A flexible Python decorator for retrying functions upon failure with support for exponential backoff, jitter, and configurable retry policies.
- Retry functions automatically when exceptions occur.
- Configurable number of retries or infinite retries.
- Adjustable initial delay and exponential backoff.
- Optional maximum delay to cap wait times.
- Support for random jitter to prevent retry storms (thundering herd problem).
- Specify which exception types trigger retries.
Install via pip:
pip install refire
# or
uv add refireOr clone the repository:
git clone https://github.com/maxscheijen/refire.git
cd refire
pip install .
# or
uv syncimport random
from refire import refire
@refire(tries=5, delay=2, backoff=2, jitter=(0, 1))
def flaky_function():
if random.random() < 0.7:
raise ValueError("Unlucky!")
return "Success!"
result = flaky_function()
print(result) # "Success!" after several retriesclass CustomError(Exception):
pass
@refire(exceptions=CustomError, tries=3, delay=1)
def risky_function():
raise CustomError("Oops!")
risky_function()Retries are by default logged at WARNING level:
Caught ValueError: Unlucky!. Retrying in 2.00s (remaining=4)
This project uses uv. To set up a local development environment:
# Clone the repository
git clone https://github.com/maxscheijen/refire.git
cd refire
# Install dependencies (using uv)
uv sync --extra dev
# Or using pip
pip install -e ".[dev]"This project uses pytest:
pytest