Retries, Backoff and Circuit Breakers in Python with tenacity and pybreaker

Every call from one service to another can fail or hang. Handled badly, a slow dependency ties up threads and connections in its callers until they fail too. Two patterns address this from opposite directions: retries recover from brief, transient failures, and circuit breakers stop calling a dependency that's clearly down, so callers fail fast instead of piling up.
This guide implements both in Python with tenacity and pybreaker. It covers which errors are worth retrying, why backoff needs jitter, and how to combine the two patterns without them working against each other.
Understanding the Problem: Cascading Failures
Imagine a scenario common in many microservice architectures: Service A calls Service B, and Service B calls Service C. If Service C experiences a temporary outage or becomes excessively slow, Service B will start queuing requests, eventually exhausting its own resources and becoming unresponsive. This, in turn, causes Service A to slow down or fail, potentially leading to its own resource exhaustion. Suddenly, a problem in one isolated service has brought down a significant portion of your application. This is a cascading failure.
Timeouts are the foundation: without one, a call to a hung service can wait forever. But timeouts alone don't stop callers from sending more requests to a struggling service, and naive retries make it worse by multiplying the load exactly when the dependency can least handle it.
The Solution: The Circuit Breaker Pattern
The Circuit Breaker pattern is inspired by electrical circuit breakers, which trip and open a circuit when an overload or short circuit is detected, preventing further damage. In software, a circuit breaker wraps a function call (e.g., an HTTP request to another service) and monitors for failures.
What is a Circuit Breaker?
A circuit breaker has three main states:
- Closed: The normal operating state. Requests pass through to the target service. If failures occur above a certain threshold, the circuit trips and moves to the Open state.
- Open: No requests are allowed to pass through to the target service. Instead, a fast-fail error is returned immediately to the caller. After a configured
timeoutperiod, the circuit moves to the Half-Open state. - Half-Open: A limited number of test requests are allowed to pass through. If these requests succeed, the circuit moves back to the Closed state. If they fail, it immediately returns to the Open state, resetting the timeout.
How a Circuit Breaker Works
By preventing requests from hammering an unresponsive service, the circuit breaker gives the failing service time to recover, reduces resource consumption on the calling service (no more waiting for dead services), and provides immediate feedback to the caller that the dependency is unavailable.
Enhancing Resilience with the Retry Pattern
While circuit breakers prevent calls to services that are known to be failing, the Retry pattern helps overcome transient failures. These are often temporary network glitches, brief service restarts, or short-lived resource contention. Instead of immediately failing, the caller attempts the operation again, often after a short delay.
Why Retries?
The key benefits of retries include:
- Handling transient issues: Many errors are temporary and resolve quickly.
- Improved user experience: Operations might succeed without the user needing to manually retry.
- Exponential backoff with jitter: the delay grows with each attempt (1 s, 2 s, 4 s, ...), and jitter adds randomness to it. Without jitter, every client that failed at the same moment retries at the same moment, producing synchronized load spikes on the recovering service.
When to Use (and Not Use) Retries
Retry only errors that might succeed on a second attempt: connection errors, timeouts, HTTP 502/503/504, and 429 (respecting Retry-After). Don't retry 4xx client errors such as 400, 401, 404 or 422. The same request will fail the same way.
⚠️ Common mistake: Retrying non-idempotent operations. An operation is idempotent if applying it multiple times produces the same result as applying it once. For example,
GETrequests are idempotent. Sending aPOSTrequest to create a new resource is typically not; retrying it might create duplicate resources. RetryPOSTrequests only when the API supports an idempotency key, a client-generated ID sent with the request so the server can recognize and ignore duplicates.
Implementing Circuit Breakers and Retries in Python
For Python, we have excellent libraries that abstract away the complexity of these patterns. We'll use tenacity for retries and pybreaker for circuit breakers. Let's set up a simple scenario where a client service calls a (potentially) failing API.
1. Setting Up the Environment
First, install the necessary libraries:
pip install Flask tenacity pybreaker requestsNext, let's create a dummy 'backend' microservice using Flask that will sometimes fail. Save this as backend_service.py:
# backend_service.py
from flask import Flask, jsonify
import random
import time
app = Flask(__name__)
request_count = 0
@app.route('/data')
def get_data():
global request_count
request_count += 1
print(f"Backend received request #{request_count}")
# Simulate transient failures: the first few requests fail 60% of the time
if request_count < 5 and random.random() < 0.6:
print("Backend: Simulating failure...")
return jsonify({"message": "Internal Server Error"}), 500
# Simulate slow responses sometimes
if request_count % 7 == 0:
print("Backend: Simulating slow response...")
time.sleep(2) # 2-second delay
print("Backend: Success!")
return jsonify({"message": "Data from backend", "request_id": request_count}), 200
if __name__ == '__main__':
print("Starting backend service on http://127.0.0.1:5000")
app.run(port=5000)Run this service in a separate terminal:
python backend_service.py2. Step-by-Step: Implementing a Retry Mechanism
Now, a client that retries with tenacity. The key part is the retry= predicate, which decides which failures are retryable. Save this as client_with_retry.py:
# client_with_retry.py
import requests
from tenacity import (
retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_random_exponential,
)
RETRYABLE_STATUS = {429, 502, 503, 504}
def is_retryable(exc: BaseException) -> bool:
if isinstance(exc, (requests.ConnectionError, requests.Timeout)):
return True
if isinstance(exc, requests.HTTPError) and exc.response is not None:
return exc.response.status_code in RETRYABLE_STATUS or exc.response.status_code == 500
return False
@retry(
retry=retry_if_exception(is_retryable),
wait=wait_random_exponential(multiplier=0.5, max=8), # exponential backoff with full jitter
stop=stop_after_attempt(4) | stop_after_delay(15), # whichever comes first
reraise=True, # raise the last real error, not RetryError
)
def call_backend():
response = requests.get("http://127.0.0.1:5000/data", timeout=(1, 3)) # (connect, read)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
for _ in range(10):
try:
print(call_backend())
except requests.RequestException as e:
print(f"Gave up: {e}")Run python client_with_retry.py. Failed calls are retried after short, randomized delays, and most requests succeed once the backend's simulated failures stop. The 500 status is retried here because the demo backend uses it for transient errors. In a real system, whether to retry a 500 depends on the dependency, since many 500s are bugs that will fail again.
stop_after_delay caps the total time spent retrying. The caller has its own timeout, and retries that outlast it waste work nobody is waiting for.
3. Step-by-Step: Implementing a Circuit Breaker
Now, let's integrate a circuit breaker using pybreaker. Save this as client_with_circuit_breaker.py:
# client_with_circuit_breaker.py
import requests
from pybreaker import CircuitBreaker, CircuitBreakerError
import time
# Configure the circuit breaker
# fail_max: consecutive failures before the circuit opens
# reset_timeout: seconds to stay open before allowing a trial call (half-open)
# exclude: exceptions that should NOT count as failures, e.g. 4xx client errors
def is_client_error(exc):
return (isinstance(exc, requests.HTTPError) and exc.response is not None
and 400 <= exc.response.status_code < 500)
service_breaker = CircuitBreaker(fail_max=3, reset_timeout=5, exclude=[is_client_error])
@service_breaker
def call_backend_with_breaker():
print("Attempting to call backend (via Circuit Breaker)...")
try:
response = requests.get('http://127.0.0.1:5000/data', timeout=1)
response.raise_for_status()
print(f"Successful response: {response.json()}")
return response.json()
except requests.exceptions.RequestException as e:
print(f"Call failed: {e}")
raise # Re-raise to let the circuit breaker log the failure
if __name__ == '__main__':
print("\n--- Client with Circuit Breaker ---")
for i in range(20):
try:
call_backend_with_breaker()
except CircuitBreakerError:
print(f"Circuit is OPEN for request {i+1}! Fast-failing.")
except Exception as e:
print(f"Operation ultimately failed: {e}")
time.sleep(1)
print(f"Current breaker state: {service_breaker.current_state}")
print("\n")Run python client_with_circuit_breaker.py. After three consecutive failures the circuit opens, and calls fail immediately with CircuitBreakerError without touching the network. Five seconds later, one trial call goes through: if it succeeds the circuit closes, and if it fails it opens again.
Two practical notes:
- Breaker state is per process. With 8 Gunicorn workers on 4 hosts, you have 32 independent breakers, each needing its own
fail_maxfailures to open. pybreaker can share state through Redis (CircuitRedisStorage) if that matters. - Excluding 4xx errors matters. A burst of 404s for missing records says nothing about the dependency's health, so it shouldn't open the circuit.
4. Combining Patterns for Maximum Effect
The order of the decorators decides how they interact:
- Breaker outside, retry inside (below): one logical call, including all its retries, counts as a single success or failure for the breaker. When the circuit opens, the retry logic doesn't run at all.
- Retry outside, breaker inside: each attempt counts separately, so the circuit opens faster. You must also stop retrying on
CircuitBreakerError, or the retry loop just collects fast failures until it runs out of attempts.
The first arrangement is easier to reason about and is used here.
# client_combined.py
import requests
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_random_exponential
from pybreaker import CircuitBreaker, CircuitBreakerError
import time
from client_with_retry import is_retryable
# Configure the circuit breaker (applied to the entire retry mechanism)
service_breaker_combined = CircuitBreaker(fail_max=3, reset_timeout=5)
@service_breaker_combined
@retry(
retry=retry_if_exception(is_retryable), # same predicate as before: no 4xx retries
wait=wait_random_exponential(multiplier=0.5, max=4),
stop=stop_after_attempt(3),
reraise=True,
)
def call_backend_combined():
print("Attempting to call backend (via Circuit Breaker + Retry)...")
try:
response = requests.get('http://127.0.0.1:5000/data', timeout=1)
response.raise_for_status()
print(f"Successful response: {response.json()}")
return response.json()
except requests.exceptions.RequestException as e:
print(f"Call failed: {e}")
raise # Re-raise to trigger tenacity retry or circuit breaker failure count
if __name__ == '__main__':
print("\n--- Client with Combined Circuit Breaker and Retry ---")
for i in range(20):
try:
call_backend_combined()
except CircuitBreakerError:
print(f"Circuit is OPEN for request {i+1}! Fast-failing.")
except Exception as e:
print(f"Operation ultimately failed after all retries and breaker: {e}")
time.sleep(1)
print(f"Current breaker state: {service_breaker_combined.current_state}")
print("\n")Transient blips are absorbed by the retries. A sustained outage fails three logical calls in a row, opens the circuit, and from then on callers get an immediate error they can handle, for example by serving cached data or a degraded response, instead of waiting on timeouts.
💡 Tip: Budget retries across the whole call chain. If service A retries 3 times and each attempt calls B, which also retries 3 times on C, one user request can produce 9 calls to C. Retry at one layer (usually closest to the user) or keep per-layer attempts low.
Summary
- Always set timeouts on outbound calls. Retries and circuit breakers both depend on calls failing in bounded time.
- Retry only transient errors, with exponential backoff and jitter, a small attempt count and a total time cap.
- Exclude client errors from the breaker's failure count, and remember that breaker state is per process unless you share it.
- Only retry idempotent operations, or use idempotency keys for writes.
