IC Improve Code Recipes

Recipe 13.2 · Python

Timeouts, Retries and Circuit Breakers

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

The partner API is usually fast, but a few times a day it takes 40 seconds or returns a 503. Your pages hang for the full 100-second default timeout. When it goes down completely, every request waits, threads pile up, and your own site falls over with it.

The way it's often written

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

This retries a 400 Bad Request that will never succeed, sleeps a thread for 15 seconds per request, and keeps calling a server that is already down. Multiply it by a few hundred concurrent users and the retry loop is the outage.

Requirements: Python 3.12+. Install: pip install httpx

Python Blocking retry-everything loop (p281_r13_2_blocking_retry_loop_before.py)
"""Blocking retry-everything loop

Source: ImproveCode, Chapter 13, Recipe 13.2 "Timeouts, Retries and Circuit Breakers"
Section: The way it's often written
Book page: 281  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
HttpClient.GetStringAsync(...).Result -> synchronous httpx.Client; Thread.Sleep -> time.sleep.
"""

from __future__ import annotations

import time

import httpx


# Not to copy: retries everything, blocks threads, hammers a dead server
def get_with_retries(client: httpx.Client, url: str) -> str:
    for attempt in range(1, 4):
        try:
            response = client.get(url)
            response.raise_for_status()
            return response.text
        except Exception:
            time.sleep(5)
    raise Exception("Service unavailable")

The improved recipe

Microsoft.Extensions.Http.Resilience adds a standard pipeline to any HttpClient registered with the factory. It is built on Polly, and its defaults are sensible. Tune the numbers to your partner.

For a service where a repeated call could do harm, such as a payment or a shipment booking, build a pipeline with a timeout and a circuit breaker but no retry:

Requirements: Python 3.12+. Install: pip install httpx

Python Standard resilience handler: timeouts, jittered retries and a circuit breaker (p282_r13_2_standard_resilience_handler.py)
"""Standard resilience handler: timeouts, jittered retries and a circuit breaker

Source: ImproveCode, Chapter 13, Recipe 13.2 "Timeouts, Retries and Circuit Breakers"
Section: The improved recipe
Book page: 282  -- original C# listing
Converted from C# to Python.
Microsoft.Extensions.Http.Resilience / Polly -> a custom httpx.AsyncBaseTransport that
applies total and per-attempt timeouts (asyncio.timeout), exponential jittered retries of
transient failures for safe methods only, and a failure-ratio circuit breaker.
"""

from __future__ import annotations

import asyncio
import random
import time
from collections import deque
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Any

import httpx

from p279_r13_1_register_customer_api_client import (
    CustomerApiClientBuilder,
    add_customer_api,
)

UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE", "CONNECT"})


@dataclass
class RetryOptions:
    max_retry_attempts: int = 3
    delay: timedelta = timedelta(seconds=2)
    exponential_backoff: bool = True
    use_jitter: bool = True
    disabled_methods: frozenset[str] = frozenset()

    def disable_for_unsafe_http_methods(self) -> None:
        self.disabled_methods = UNSAFE_METHODS


@dataclass
class CircuitBreakerOptions:
    sampling_duration: timedelta = timedelta(seconds=30)
    failure_ratio: float = 0.1
    minimum_throughput: int = 100
    break_duration: timedelta = timedelta(seconds=5)


@dataclass
class StandardResilienceOptions:
    total_request_timeout: timedelta = timedelta(seconds=30)
    attempt_timeout: timedelta = timedelta(seconds=10)
    retry: RetryOptions = field(default_factory=RetryOptions)
    circuit_breaker: CircuitBreakerOptions = field(
        default_factory=CircuitBreakerOptions)


class BrokenCircuitError(Exception):
    """Raised without calling the server while the circuit is open."""


class CircuitBreaker:
    """Opens when the failure ratio over the sampling window is too high."""

    def __init__(self, options: CircuitBreakerOptions) -> None:
        self._options = options
        self._outcomes: deque[tuple[float, bool]] = deque()
        self._open_until = 0.0
        self._half_open = False

    def before_call(self) -> None:
        now = time.monotonic()
        if now < self._open_until:
            raise BrokenCircuitError("The circuit is open.")
        if self._open_until:
            # Break duration is over: let one trial call through.
            self._open_until = 0.0
            self._half_open = True

    def record(self, success: bool) -> None:
        now = time.monotonic()
        if self._half_open:
            self._half_open = False
            if not success:
                self._open(now)
            return

        self._outcomes.append((now, success))
        window_start = now - self._options.sampling_duration.total_seconds()
        while self._outcomes and self._outcomes[0][0] < window_start:
            self._outcomes.popleft()

        total = len(self._outcomes)
        failures = sum(1 for _, ok in self._outcomes if not ok)
        if (total >= self._options.minimum_throughput
                and failures / total >= self._options.failure_ratio):
            self._open(now)

    def _open(self, now: float) -> None:
        self._open_until = now + self._options.break_duration.total_seconds()
        self._outcomes.clear()


def is_transient(status_code: int) -> bool:
    return status_code in (408, 429) or status_code >= 500


class ResilientTransport(httpx.AsyncBaseTransport):
    def __init__(
            self,
            options: StandardResilienceOptions,
            inner: httpx.AsyncBaseTransport | None = None) -> None:
        self._options = options
        self._inner = inner or httpx.AsyncHTTPTransport()
        self._breaker = CircuitBreaker(options.circuit_breaker)

    async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
        o = self._options
        # Whole operation, including all retries.
        async with asyncio.timeout(o.total_request_timeout.total_seconds()):
            attempt = 0
            while True:
                self._breaker.before_call()
                response: httpx.Response | None = None
                error: Exception | None = None
                try:
                    # Each individual attempt.
                    async with asyncio.timeout(o.attempt_timeout.total_seconds()):
                        response = await self._inner.handle_async_request(request)
                        await response.aread()
                except (httpx.TransportError, TimeoutError) as ex:
                    error = ex
                    self._breaker.record(False)
                else:
                    transient = is_transient(response.status_code)
                    self._breaker.record(not transient)
                    if not transient:
                        return response

                if (attempt >= o.retry.max_retry_attempts
                        or request.method in o.retry.disabled_methods):
                    if response is not None:
                        return response
                    assert error is not None
                    raise error

                if response is not None:
                    await response.aclose()
                await asyncio.sleep(self._delay(attempt))
                attempt += 1

    def _delay(self, attempt: int) -> float:
        base = self._options.retry.delay.total_seconds()
        delay = base * 2 ** attempt if self._options.retry.exponential_backoff else base
        if self._options.retry.use_jitter:
            delay *= random.uniform(0.5, 1.5)
        return delay

    async def aclose(self) -> None:
        await self._inner.aclose()


def add_resilient_customer_api(
        configuration: Mapping[str, Any] | None = None) -> CustomerApiClientBuilder:
    builder = add_customer_api(configuration)

    options = StandardResilienceOptions()
    # Whole operation, including all retries.
    options.total_request_timeout = timedelta(seconds=20)

    # Each individual attempt.
    options.attempt_timeout = timedelta(seconds=5)

    options.retry.max_retry_attempts = 3
    options.retry.delay = timedelta(milliseconds=500)
    options.retry.exponential_backoff = True
    options.retry.use_jitter = True
    options.retry.disable_for_unsafe_http_methods()

    options.circuit_breaker.sampling_duration = timedelta(seconds=30)
    options.circuit_breaker.failure_ratio = 0.5
    options.circuit_breaker.minimum_throughput = 20
    options.circuit_breaker.break_duration = timedelta(seconds=15)

    builder.transport = ResilientTransport(options)
    return builder

Requirements: Python 3.12+. Install: pip install httpx

Python Timeout plus circuit breaker, with no retries (p282_r13_2_timeout_and_breaker_only.py)
"""Timeout plus circuit breaker, with no retries

Source: ImproveCode, Chapter 13, Recipe 13.2 "Timeouts, Retries and Circuit Breakers"
Section: The improved recipe
Book page: 282-283  -- original C# listing
Converted from C# to Python.
AddResilienceHandler pipeline -> an httpx.AsyncBaseTransport that wraps each call in
asyncio.timeout and the failure-ratio CircuitBreaker from the standard-handler module.
"""

from __future__ import annotations

import asyncio
from datetime import timedelta

import httpx

from p279_r13_1_register_customer_api_client import CustomerApiClientBuilder
from p282_r13_2_standard_resilience_handler import (
    CircuitBreaker,
    CircuitBreakerOptions,
    is_transient,
)


class TimeoutBreakerTransport(httpx.AsyncBaseTransport):
    """The "timeout-breaker" pipeline: one attempt, bounded, behind a breaker."""

    def __init__(
            self,
            timeout: timedelta,
            breaker: CircuitBreakerOptions,
            inner: httpx.AsyncBaseTransport | None = None) -> None:
        self._timeout = timeout
        self._breaker = CircuitBreaker(breaker)
        self._inner = inner or httpx.AsyncHTTPTransport()

    async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
        self._breaker.before_call()
        try:
            async with asyncio.timeout(self._timeout.total_seconds()):
                response = await self._inner.handle_async_request(request)
                await response.aread()
        except (httpx.TransportError, TimeoutError):
            self._breaker.record(False)
            raise
        self._breaker.record(not is_transient(response.status_code))
        return response

    async def aclose(self) -> None:
        await self._inner.aclose()


def add_timeout_and_breaker_only(
        builder: CustomerApiClientBuilder,
        timeout: timedelta) -> CustomerApiClientBuilder:
    builder.transport = TimeoutBreakerTransport(
        timeout,
        CircuitBreakerOptions(
            sampling_duration=timedelta(seconds=60),
            failure_ratio=0.5,
            minimum_throughput=10,
            break_duration=timedelta(seconds=30),
        ))
    return builder

How it works

The standard handler chains five strategies, from outside to inside: a rate limiter, the total request timeout, retry, the circuit breaker, and the per-attempt timeout. Each request passes through all five on the way out.

The two timeouts do different jobs. The attempt timeout cuts off one slow call so a retry can try again, perhaps on a healthier server behind the load balancer. The total timeout caps what the caller waits, retries included. HttpClient.Timeout from Recipe 13.1 still applies outside the pipeline, so keep it longer than the total timeout, or the client gives up before the pipeline does.

The retry strategy only retries what is worth retrying: network failures, timeouts, 408, 429 and 5xx responses. A 400 or 404 passes straight through. Exponential backoff with jitter spreads the retries out, so a thousand clients that failed at the same moment do not all retry at the same moment. A Retry-After header from the server is honored. DisableForUnsafeHttpMethods turns retries off for POST, PUT, PATCH and DELETE, because a request that timed out may still have succeeded on the server.

The circuit breaker watches the failure ratio over the sampling window. When at least MinimumThroughput calls have been made and half of them failed, it opens: for the next 15 seconds, calls fail immediately with a BrokenCircuitException instead of waiting. Your threads are freed, the struggling partner gets a break, and after the break duration a trial call decides whether to close the circuit again.

Variations and pitfalls

  • Package version. DisableForUnsafeHttpMethods is not in the earliest releases of the package. I compiled these listings against version 9.10.0. Pick the newest version whose dependencies match your target framework.
  • Sampling duration must be at least twice the attempt timeout. The options are validated at start-up, and an invalid combination throws. Change both together.
  • Apply defaults to every client. services.ConfigureHttpClientDefaults(b => b.AddStandardResilienceHandler()); gives every factory client the standard pipeline. Override it per client where needed.
  • Idempotency keys. If a partner supports an Idempotency-Key header, send a fresh GUID per logical operation and you can safely retry POST requests. Without it, don't.
  • Polly directly. For resilience around non-HTTP work, such as a database call or a file share, use the Polly.Core package and its ResiliencePipelineBuilder. Chapter 5 covers a simple retry with backoff for those cases.
  • Log the breaker. Configure options.CircuitBreaker.OnOpened to log a warning. An open circuit is the first sign of a partner outage, and you want to know before your users tell you.

On .NET Framework

Microsoft.Extensions.Http.Resilience targets modern .NET and .NET Standard 2.0, and with the factory it can run on .NET Framework 4.6.2 and later. In older code without the factory, use Polly v7's Policy.Handle<HttpRequestException>().WaitAndRetryAsync(...) and wrap each call in it.