# Python retry libraries

Python retry libraries run a failed operation again after a delay until it succeeds or reaches a stop condition. A retry policy pairs conditions such as an exception type, a returned value, or an attempt limit with a wait between attempts. These libraries let apps and AI agents recover from network errors and brief outages in the services they call.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Tenacity](#tenacity) | 429.7M | 8.8K | Oct 2026 | Apache-2.0 |
| [backoff](#backoff) | 152.5M | 2.7K | Oct 2022 | MIT |
| [retry](#retry) | 26.0M | Not on GitHub | May 2016 | Apache-2.0 |
| [retrying](#retrying) | 25.3M | Not on GitHub | Aug 2025 | Apache-2.0 |
| [stamina](#stamina) | 5.8M | 1.5K | Nov 2026 | MIT |
| [retry2](#retrytwo) | 2.1M | Not on GitHub | Jan 2023 | Apache-2.0 |

Downloads: pypi, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Tenacity](#tenacity) has the most monthly downloads in this comparison, at 429.7M.

## Capabilities

| Library | Async callable retries | Return-value retry predicate |
| --- | --- | --- |
| [Tenacity](#tenacity) | Yes | Yes |
| [backoff](#backoff) | Yes | Yes |
| [retry](#retry) | No | No |
| [retrying](#retrying) | No | Yes |
| [stamina](#stamina) | Yes | No |
| [retry2](#retrytwo) | No | No |

## Libraries

### Tenacity

[GitHub](https://github.com/jd/tenacity) · [pypi](https://pypi.org/project/tenacity)

Provides configurable retry decorators and code-block retry loops.

- Downloads / mo: 429.7M
- Stars: 8.8K
- Last release: 9.2.1
- License: Apache-2.0
- Capabilities: [From the Tenacity docs](https://github.com/jd/tenacity)

**Strengths**

- **Combines retry conditions.** Retry selected exceptions or returned results with configurable stop and wait policies.
- **Retries individual code blocks.** Use a retry iterator and context manager around the failing block.

**Watch out for**

- **Defaults retry forever without waiting.** Set both a stop condition and a wait policy.
- **Exhaustion wraps the last error.** Set reraise to expose the original exception directly.

```sh
python -m pip install tenacity==9.2.1
```

**langchain-ai/langchain-community** (285 stars)

[langchain-ai/langchain-community](https://github.com/langchain-ai/langchain-community) 

```python
def _create_retry_decorator() -> Callable[[Any], Any]:
    """Returns a tenacity retry decorator."""

    multiplier = 1
    min_seconds = 1
    max_seconds = 4
    max_retries = 6

    return retry(
        reraise=True,
        stop=stop_after_attempt(max_retries),
        wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds),
        before_sleep=before_sleep_log(logger, logging.WARNING),
    )

```

[libs/community/langchain_community/embeddings/minimax.py](https://github.com/langchain-ai/langchain-community/blob/f425a3ed1933173fb3694b81359d1519c4f82d36/libs/community/langchain_community/embeddings/minimax.py#L20-L33) · [More projects using Tenacity →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20tenacity%20for%20retry%20behavior&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from tenacity import retry, stop_after_attempt

@retry(stop=stop_after_attempt(3))
def greet():
    return "Hello"

print(greet())

```

From [index.rst](https://api.github.com/repos/jd/tenacity/readme)

### backoff

[GitHub](https://github.com/litl/backoff) · [pypi](https://pypi.org/project/backoff)

Decorates synchronous functions and asyncio coroutines with exception or return-value retries.

- Downloads / mo: 152.5M
- Stars: 2.7K
- Last release: 2.2.1
- License: MIT
- Capabilities: [From the backoff docs](https://github.com/litl/backoff)

**Strengths**

- **Retries exceptions or returned values.** Choose on_exception or on_predicate for the operation’s failure signal.
- **Offers retry event handlers.** Attach handlers for successful calls, retries, and give-up events.

**Watch out for**

- **Repository is archived.** Account for the archived upstream when choosing a new dependency.
- **Suppressed errors return None.** Disabling raise_on_giveup returns None when retries are exhausted.

```sh
python -m pip install backoff==2.2.1
```

**langfuse/langfuse-python** (516 stars)

[langfuse/langfuse-python](https://github.com/langfuse/langfuse-python) 

```python
def _request_with_backoff(
    self, func: Callable[P, T], *args: P.args, **kwargs: P.kwargs
) -> T:
    def _should_give_up(e: Exception) -> bool:
        if isinstance(e, ApiError):
            return (
                e.status_code is not None
                and 400 <= e.status_code < 500
                and e.status_code != 429
            )
        if isinstance(e, httpx.HTTPStatusError):
            return (
                e.response is not None
                and e.response.status_code < 500
                and e.response.status_code != 429
            )
        return False

    @backoff.on_exception(
        backoff.expo,
        Exception,
        max_tries=self._max_retries,
        giveup=_should_give_up,
        logger=None,
    )
    def execute_task_with_backoff() -> T:
        return func(*args, **kwargs)

    return execute_task_with_backoff()

```

[langfuse/_task_manager/media_manager.py](https://github.com/langfuse/langfuse-python/blob/077448c7a4ae8708f29e1434177bf9f3c667119b/langfuse/_task_manager/media_manager.py#L512-L540) · [More projects using backoff →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20backoff%20for%20retry%20behavior&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import backoff

@backoff.on_exception(backoff.expo, OSError, max_tries=3)
def greet():
    return "Hello"

print(greet())

```

From [README.rst](https://api.github.com/repos/litl/backoff/readme)

### retry

[GitHub](https://github.com/invl/retry) · [pypi](https://pypi.org/project/retry)

Retries a function through a decorator.

- Downloads / mo: 26.0M
- Last release: 0.9.2
- License: Apache-2.0
- Capabilities: [From the retry docs](https://github.com/invl/retry)

```sh
python -m pip install retry==0.9.2
```

**openatx/uiautomator2** (8.5K stars)

[openatx/uiautomator2](https://github.com/openatx/uiautomator2) 

```python
@retry(HierarchyEmptyError, tries=3, delay=1)
def _do_dump_hierarchy(self, compressed=False, max_depth=None) -> str:
    if max_depth is None:
        max_depth = 50
    content = self.jsonrpc.dumpWindowHierarchy(compressed, max_depth)
    if content == "":
        raise HierarchyEmptyError("dump hierarchy is empty")

    # '<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\' ?>\r\n<hierarchy rotation="0" />'
    if '<hierarchy rotation="0" />' in content:
        logger.debug("dump empty, call clear_traversed_text and retry")
        # self.clear_traversed_text()
        raise HierarchyEmptyError("dump hierarchy is empty with no children")
    return content
```

[uiautomator2/__init__.py](https://github.com/openatx/uiautomator2/blob/314e7eb4a9937ba98d0c53b35d1269f15555e427/uiautomator2/__init__.py#L292-L305) · [More projects using retry →](https://dashboard.exa.ai/playground/search?q=retry%20GitHub%20projects)

**Quickstart**

```python
from retry import retry

@retry(OSError, tries=3, delay=1)
def greet():
    return "Hello"

print(greet())

```

From [README.rst](https://api.github.com/repos/invl/retry/readme)

### retrying

[GitHub](https://github.com/groodt/retrying) · [pypi](https://pypi.org/project/retrying)

Retries function calls.

- Downloads / mo: 25.3M
- Last release: 1.4.2
- License: Apache-2.0
- Capabilities: [From the retrying docs](https://github.com/groodt/retrying)

```sh
python -m pip install retrying==1.4.2
```

**openstack/ironic** (575 stars)

[openstack/ironic](https://github.com/openstack/ironic) 

```python
@retrying.retry(
    stop_max_attempt_number=CONF.agent.neutron_agent_max_attempts,
    retry_on_exception=lambda e: isinstance(e, exception.NetworkError),
    wait_fixed=CONF.agent.neutron_agent_status_retry_interval * 1000
)
def wait_for_port_status(client, port_id, status):
    """Wait for port status to be the desired status

    :param client: A Neutron client object.
    :param port_id: Neutron port_id
    :param status: Port's target status, can be ACTIVE, DOWN ... etc.
    :returns: boolean indicates that the port status matches the
        required value passed by param status.
    :raises: InvalidParameterValue if the port does not exist.
    :raises: exception.NetworkError if port status didn't match
        the required status after max retry attempts.
    """
    LOG.debug('Validating Port %(port_id)s status is %(status)s',
              {'port_id': port_id, 'status': status})
    port = _get_port_by_uuid(client, port_id)
    LOG.debug('Port %(port_id)s status is: %(status)s',
              {'port_id': port_id, 'status': port.status})
    if port.status == status:
        return True
    raise exception.NetworkError(
        'Port %(port_id)s failed to reach status %(status)s' % {
            'port_id': port_id, 'status': status})
```

[ironic/common/neutron.py](https://github.com/openstack/ironic/blob/71ebba5cf354e3c22991764899d0669dd4be04e6/ironic/common/neutron.py#L907-L933) · [More projects using retrying →](https://dashboard.exa.ai/playground/search?q=retrying%20GitHub%20projects)

**Quickstart**

```python
from retrying import retry

@retry(stop_max_attempt_number=3, wait_fixed=100)
def greet():
    return "Hello"

print(greet())

```

From [README.md](https://api.github.com/repos/groodt/retrying/readme)

### stamina

[GitHub](https://github.com/hynek/stamina) · [pypi](https://pypi.org/project/stamina)

Wraps Tenacity with bounded retry defaults, jitter, and instrumentation.

- Downloads / mo: 5.8M
- Stars: 1.5K
- Last release: 26.2.0
- License: MIT
- Capabilities: [From the stamina docs](https://github.com/hynek/stamina)

**Strengths**

- **Bounds retries by default.** Configure attempt and total-time limits alongside exponential backoff and jitter.
- **Supports asyncio and Trio.** Use the same retry functions with synchronous and asynchronous operations.

**Watch out for**

- **Generator retries restart from beginning.** Make repeated yielded work safe before retrying a generator.
- **Custom delays override backoff settings.** An on-hook delay replaces the normal exponential backoff calculation.

```sh
python -m pip install stamina==26.2.0
```

**earthobservations/wetterdienst** (457 stars)

[earthobservations/wetterdienst](https://github.com/earthobservations/wetterdienst) 

```python
@stamina.retry(on=Exception, attempts=3)
def list_remote_files_fsspec(
    url: str, settings: Settings, cache_expiry: CacheExpiry = CacheExpiry.FILEINDEX
) -> list[str]:
    """Create a listing of all files of a given path on the server.

    The default ttl with ``CacheExpiry.FILEINDEX`` is "5 minutes".

    Args:
        url: The URL to list files from.
        settings: The settings to use for the listing.
        cache_expiry: The cache expiration time.

    Returns:
        A list of all files on the server

    """
    use_cache = not (settings.cache_disable or cache_expiry is CacheExpiry.NO_CACHE)
    fs = HTTPFileSystem(
        use_listings_cache=use_cache,
        listings_expiry_time=not settings.cache_disable and cache_expiry.value,
        listings_cache_location=settings.cache_dir,
        client_kwargs=settings.fsspec_client_kwargs,
        use_certifi=settings.use_certifi,
    )
    return fs.find(url)
```

[src/wetterdienst/util/network.py](https://github.com/earthobservations/wetterdienst/blob/7971d23ffd8a9d09550e8b6473aad39dc31f77ec/src/wetterdienst/util/network.py#L358-L383) · [More projects using stamina →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20stamina%20for%20retry%20behavior&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import stamina

@stamina.retry(on=OSError, attempts=3)
def greet():
    return "Hello"

print(greet())

```

From [tutorial.md](https://api.github.com/repos/hynek/stamina/readme)

### retry2

[GitHub](https://github.com/eSAMTrade/retry) · [pypi](https://pypi.org/project/retry2)

Retries a function through a decorator.

- Downloads / mo: 2.1M
- Last release: 0.9.5
- License: Apache-2.0
- Capabilities: [From the retry2 docs](https://github.com/eSAMTrade/retry)

```sh
python -m pip install retry2==0.9.5
```

**openatx/uiautomator2** (8.5K stars)

[openatx/uiautomator2](https://github.com/openatx/uiautomator2) 

```python
@retry(HierarchyEmptyError, tries=3, delay=1)
def _do_dump_hierarchy(self, compressed=False, max_depth=None, root_in_active: Optional[bool] = None) -> str:
    if max_depth is None:
        max_depth = 50
    if root_in_active is None:
        content = self.jsonrpc.dumpWindowHierarchy(compressed, max_depth)
    else:
        content = self.jsonrpc.dumpWindowHierarchy(compressed, max_depth, root_in_active)
    if content == "":
        raise HierarchyEmptyError("dump hierarchy is empty")

    # '<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\' ?>\r\n<hierarchy rotation="0" />'
    if '<hierarchy rotation="0" />' in content:
        logger.debug("dump empty, call clear_traversed_text and retry")
        # self.clear_traversed_text()
        raise HierarchyEmptyError("dump hierarchy is empty with no children")
    return content
```

[uiautomator2/__init__.py](https://github.com/openatx/uiautomator2/blob/96f581d3b95efdf16105b767a5d5401c73f7ec0e/uiautomator2/__init__.py#L131-L147) · [More projects using retry2 →](https://dashboard.exa.ai/playground/search?q=retry2%20GitHub%20projects)

**Quickstart**

```python
from retry import retry

@retry(OSError, tries=3, delay=1)
def greet():
    return "Hello"

print(greet())

```

From [README.rst](https://api.github.com/repos/eSAMTrade/retry/readme)

## FAQ

### Which Python retry library should I use?

[Tenacity](#tenacity) suits code that combines retry conditions or retries individual code blocks. [stamina](#stamina) suits services that want bounded retries with jitter by default. [backoff](#backoff) suits existing code built on its decorators, although its repository is archived.

### What is Tenacity?

[Tenacity](#tenacity) is a retry library with configurable decorators and code-block retry loops. By default it retries exceptions forever without waiting. A stop policy bounds the number of attempts.

### Which Python retry libraries support async functions?

[Tenacity](#tenacity) and [backoff](#backoff) both retry asyncio coroutines. [stamina](#stamina) supports asyncio and Trio with the same API.

### What does stamina add to Tenacity?

[stamina](#stamina) wraps Tenacity with bounded retry defaults, jitter, and instrumentation.

### Does stamina resume a generator after its last yielded item?

No. A retried generator restarts from the beginning.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python retry libraries Tenacity backoff stamina urllib3 code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
