IC Improve Code Recipes

Recipe 5.6 · Python

Retry with Backoff (and Polly)

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Some failures are transient: a deadlock victim, a dropped connection, a 503 from an overloaded API, a timeout during a failover. Trying again a moment later usually works. Without a retry, a nightly job fails for a two-second network blip. With a naive retry loop, a hundred clients hammer a recovering server in lockstep and keep it down.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Fixed-delay retry loop that retries everything and blocks a thread (p116_r5_6_fixed_delay_retry_loop_before.py)
"""Fixed-delay retry loop that retries everything and blocks a thread

Source: ImproveCode, Chapter 5, Recipe 5.6 "Retry with Backoff (and Polly)"
Section: The way it's often written
Book page: 116  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
time.sleep replaces Thread.Sleep; the final exception discards the original (from None).
"""

from __future__ import annotations

import time
from typing import Any, Callable


def call_with_retry(call_service: Callable[[], Any]) -> Any:
    # Not this: fixed delay, retries everything, blocks a thread,
    # and throws away the original exception.
    for i in range(5):
        try:
            return call_service()
        except Exception:
            time.sleep(1)
    raise Exception("Service failed after 5 tries") from None

The improved recipe

A small asynchronous helper with exponential backoff, jitter, a transient-error test and logging. When you need more (timeouts, circuit breakers, rate limiting), use Polly (Polly.Core).

The same policy with Polly, plus an overall timeout per attempt:

Usage:

Requirements: Python 3.12+. Install: pip install httpx pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.

Python Async retry helper with exponential backoff, jitter and transient-error check (p116_r5_6_exponential_backoff_retry_helper.py)
"""Async retry helper with exponential backoff, jitter and transient-error check

Source: ImproveCode, Chapter 5, Recipe 5.6 "Retry with Backoff (and Polly)"
Section: The improved recipe
Book page: 116-117  -- original C# listing
Converted from C# to Python.
asyncio.sleep replaces Task.Delay; httpx exceptions replace HttpRequestException
(TransportError = no status code, HTTPStatusError carries one); pyodbc OperationalError
stands in for DbException.IsTransient. Cancellation is asyncio.CancelledError, never retried.
"""

from __future__ import annotations

import asyncio
import logging
import random
from typing import Awaitable, Callable

import httpx
import pyodbc


class Retry:
    @staticmethod
    async def execute[T](
        operation: Callable[[], Awaitable[T]],
        is_transient: Callable[[Exception], bool],
        max_attempts: int = 3,
        base_delay: float | None = None,
        logger: logging.Logger | None = None,
    ) -> T:
        if operation is None:
            raise ValueError("operation must not be None")
        if is_transient is None:
            raise ValueError("is_transient must not be None")
        if max_attempts < 1:
            raise ValueError("max_attempts must be at least 1")

        first = base_delay if base_delay is not None else 0.2  # seconds

        attempt = 1
        while True:
            try:
                return await operation()
            except Exception as ex:
                if not (attempt < max_attempts and is_transient(ex)):
                    raise
                delay = Retry._backoff(first, attempt)
                if logger is not None:
                    logger.warning(
                        "Transient failure, attempt %s of %s; retrying in %s ms",
                        attempt, max_attempts, int(delay * 1000), exc_info=ex)
                await asyncio.sleep(delay)
            attempt += 1

    # 200 ms, 400 ms, 800 ms ... plus up to 100% jitter, max 30 s.
    @staticmethod
    def _backoff(first: float, attempt: int) -> float:
        s = first * 2 ** (attempt - 1)
        s += random.random() * s
        return min(s, 30.0)


class TransientErrors:
    _TRANSIENT_STATUS = {408, 429, 502, 503, 504}

    @staticmethod
    def is_transient(ex: Exception) -> bool:
        match ex:
            case TimeoutError():
                return True
            case httpx.HTTPStatusError():
                return ex.response.status_code in TransientErrors._TRANSIENT_STATUS
            case httpx.TransportError():  # network, no status code
                return True
            case pyodbc.OperationalError():
                return True
            case _:
                return False

Requirements: Python 3.12+. Install: pip install httpx tenacity

Python Resilience pipeline: exponential retry with jitter plus an overall timeout (p117_r5_6_tenacity_retry_with_timeout.py)
"""Resilience pipeline: exponential retry with jitter plus an overall timeout

Source: ImproveCode, Chapter 5, Recipe 5.6 "Retry with Backoff (and Polly)"
Section: The improved recipe
Book page: 117-118  -- original C# listing
Converted from C# to Python.
tenacity replaces Polly (AsyncRetrying with wait_random_exponential and a before_sleep
log hook); asyncio.timeout replaces AddTimeout. TransientErrors.is_transient is from
p116_r5_6_exponential_backoff_retry_helper.py and is passed in.
"""

from __future__ import annotations

import asyncio
import logging
from typing import Awaitable, Callable

import httpx
from tenacity import (
    AsyncRetrying,
    RetryCallState,
    retry_if_exception,
    stop_after_attempt,
    wait_random_exponential,
)


class ResiliencePipeline:
    def __init__(self, logger: logging.Logger,
                 is_transient: Callable[[Exception], bool]) -> None:
        self._logger = logger
        self._is_transient = is_transient

    def _should_handle(self, ex: BaseException) -> bool:
        if isinstance(ex, TimeoutError):
            return True
        return isinstance(ex, httpx.HTTPError) and self._is_transient(ex)

    def _on_retry(self, state: RetryCallState) -> None:
        delay = state.next_action.sleep if state.next_action else 0.0
        self._logger.warning(
            "Retry %s in %s ms", state.attempt_number, int(delay * 1000),
            exc_info=state.outcome.exception() if state.outcome else None)

    async def execute[T](self, operation: Callable[[], Awaitable[T]]) -> T:
        async with asyncio.timeout(10):  # AddTimeout(TimeSpan.FromSeconds(10))
            async for attempt in AsyncRetrying(
                retry=retry_if_exception(self._should_handle),
                stop=stop_after_attempt(3 + 1),  # MaxRetryAttempts = 3
                wait=wait_random_exponential(multiplier=0.2, max=30),
                before_sleep=self._on_retry,
                reraise=True,
            ):
                with attempt:
                    return await operation()
        raise AssertionError("unreachable")


def create_default(logger: logging.Logger,
                   is_transient: Callable[[Exception], bool]) -> ResiliencePipeline:
    return ResiliencePipeline(logger, is_transient)

Requirements: Python 3.12+. Install: pip install httpx

Python Calling an HTTP API through the retry helper and the resilience pipeline (p118_r5_6_retry_and_pipeline_usage.py)
"""Calling an HTTP API through the retry helper and the resilience pipeline

Source: ImproveCode, Chapter 5, Recipe 5.6 "Retry with Backoff (and Polly)"
Section: The improved recipe
Book page: 118  -- original C# listing
Converted from C# to Python.
httpx.AsyncClient replaces HttpClient.GetStringAsync; Retry, TransientErrors and the
pipeline come from p116_r5_6_exponential_backoff_retry_helper.py and
p117_r5_6_tenacity_retry_with_timeout.py.
"""

from __future__ import annotations

import logging
from typing import Any

import httpx


async def fetch_rates(
    http: httpx.AsyncClient, retry: Any, transient_errors: Any,
    pipeline: Any, logger: logging.Logger, url: str,
) -> tuple[str, str]:
    async def get_rates() -> str:
        response = await http.get("https://api.example.com/rates")
        response.raise_for_status()
        return response.text

    json_text = await retry.execute(
        get_rates,
        transient_errors.is_transient,
        max_attempts=4,
        logger=logger)

    async def get_url() -> str:
        response = await http.get(url)
        response.raise_for_status()
        return response.text

    again = await pipeline.execute(get_url)
    return json_text, again

How it works

Each failed attempt waits twice as long as the one before, so a struggling server gets more room with every round. Jitter adds a random amount on top so that many clients that failed at the same moment don't all retry at the same moment. The cap keeps a misconfigured attempt count from producing hour-long waits.

The exception filter is the important part. The catch only runs when another attempt is allowed and the error is transient. On the last attempt, or for a non-transient error such as a 400 or a NullReferenceException, the filter returns false, the exception propagates untouched and the caller sees the real failure with its original stack trace. There is no "failed after 5 tries" wrapper that hides the cause.

TransientErrors is the policy for what deserves a retry. Timeouts, network failures with no HTTP status, and the standard "try again later" status codes do. A 400, 401 or 404 never succeeds on retry. DbException.IsTransient (added in .NET 6) lets ADO.NET providers that support it flag deadlocks and failover errors; check whether your provider sets it, and if not, test for its specific error numbers (for SQL Server, 1205 for a deadlock victim and the Azure SQL transient codes such as 40613).

Polly does the same with a declarative pipeline and adds strategies you shouldn't hand-roll: timeouts, circuit breakers that stop calling a service that is clearly down, hedging and rate limiting. Build the pipeline once and reuse it; it is thread-safe.

Variations and pitfalls

  • Only retry operations that are safe to repeat. A GET is; a POST that charges a card is not, unless the API supports an idempotency key. A database write inside a transaction that rolled back is safe to retry as a whole unit.
  • Keep total retry time well inside the caller's own timeout. Three retries of a 30-second call inside a 30-second HTTP request is a timeout with extra steps.
  • Retry at one layer only. If the HTTP client, the service and the job runner each retry three times, one failure becomes 27 calls.
  • For HttpClient, prefer Microsoft.Extensions.Http.Resilience and its AddStandardResilienceHandler(), which wires a Polly pipeline into IHttpClientFactory (Chapter 13).
  • Microsoft.Data.SqlClient also has built-in connection retry (ConnectRetryCount in the connection string) for the connection itself, not for commands.
  • Never use Thread.Sleep in a retry loop on a server. Task.Delay frees the thread while waiting and honors cancellation.