Tenacity Retry Stop Wait Strategies

Compose retry behavior with Tenacity using stop conditions, adaptive wait strategies, custom retry predicates, and typed final errors.

PythonResilience

Code

pythonsnippet
49 lines
import random
from typing import Any

from tenacity import (
    RetryError,
    retry,
    stop_after_attempt,
    stop_after_delay,
    wait_random_exponential,
    before_sleep_log,
    retry_if_exception_type,
)
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class ThrottleError(Exception):
    pass


@retry(
    stop=(stop_after_attempt(6) | stop_after_delay(30)),
    wait=wait_random_exponential(multiplier=0.5, max=10),
    retry=retry_if_exception_type((ConnectionError, ThrottleError)),
    before_sleep=before_sleep_log(logger, logging.WARNING),
    reraise=True,
)
def fetch_ledger(page: int) -> list[dict[str, Any]]:
    roll = random.random()
    if roll < 0.35:
        raise ConnectionError('ledger node unreachable')
    if roll < 0.5:
        raise ThrottleError('quota exceeded for this window')
    return [{'page': page, 'rows': random.randint(1, 40)}]


def safe_fetch(page: int) -> list[dict[str, Any]]:
    try:
        return fetch_ledger(page)
    except RetryError:
        return []
    except (ConnectionError, ThrottleError):
        return []  # reraise=True 时最终以原始异常抛出


rows = safe_fetch(1)
print('ledger rows fetched:', len(rows))

What the code does

Tenacity Retry Stop Wait Strategies keeps everything in the class ThrottleError and the functions fetch_ledger and safe_fetch.

The import line is the dependency contract: Any, ( come from tenacity and nothing else. A guard precedes the ConnectionError and ThrottleError: bad state stops the flow there instead of continuing.

Returns a newly built value, leaving the inputs as they were.

Watch out for

  • Requires tenacity and logging as packages; the snippet will not run without them.
  • The guard roll < 0.35 short-circuits the flow with an early raise when its condition holds.

Using it

The main signature reads def fetch_ledger(page: int) -> list[dict[str, Any]]

The demo output is labeled (ledger rows fetched:), so every printed line maps back to its originating operation.

The surface worth importing is fetch_ledger; the helpers around it are private to the snippet.

Key statements

def fetch_ledger(page: int) -> list[dict[str, Any]]:
    roll = random.random()
    if roll < 0.35:
        raise ConnectionError('ledger node unreachable')
    if roll < 0.5:
        raise ThrottleError('quota exceeded for this window')
    return [{'page': page, 'rows': random.randint(1, 40)}]
def safe_fetch(page: int) -> list[dict[str, Any]]:
    try:
        return fetch_ledger(page)
    except RetryError:
        return []
    except (ConnectionError, ThrottleError):
        return []  # reraise=True 时最终以原始异常抛出

Interactive Tools for This Topic

FAQ

Does `fetch_ledger` modify its input?
No mutation happens — the function reads its input and returns a new value.
How are precondition violations signaled?
It throws `ConnectionError` and `ThrottleError` before any real work runs, via the guard `roll < 0.35` — handle it at the call site or let it propagate deliberately.
Which packages must be installed first?
Yes. The imports resolve to `tenacity` and `logging`, which the package manager must provide.