Registry / http-networking / backoff

backoff

JSON →
library2.3.1pypypi✓ verified 47d ago

python-backoff is a Python library providing function decorators for configurable backoff and retry strategies. It allows you to wrap functions to automatically retry their execution until a specified condition is met, such as handling transient failures from unreliable network resources or external APIs. The library supports both synchronous and asynchronous (asyncio) code, offering various wait generators like exponential, fibonacci, and constant backoff. It is actively maintained, with recent releases in late 2025, and the current version is 2.3.1.

http-networkingobservabilitytesting
pip install backoff
Install & Compatibility
Where this runs
tested against v2.2.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
4/5 runs
4/5 runs
py 3.11
4/5 runs
4/5 runs
py 3.12
4/5 runs
4/5 runs
py 3.13
4/5 runs
4/5 runs
py 3.9
4/5 runs
4/5 runs
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

on_exception
from backoff import on_exception
from backoff import on_exception, expo, full_jitter, fatal_exception
expo
from backoff import expo
full_jitter
from backoff import full_jitter

This quickstart demonstrates how to use the `@backoff.on_exception` decorator to automatically retry a function that might fail intermittently. It configures exponential backoff with jitter, sets a maximum number of tries and total elapsed time, and includes `on_backoff` and `on_giveup` handlers for logging retry attempts. The example simulates a flaky API that raises exceptions for the first few calls, eventually succeeding or giving up.

import backoff import random import time # Simulate a flaky external API call CALL_COUNT = 0 MAX_FAILURES = 3 @backoff.on_exception(backoff.expo, # Exponential backoff strategy (ValueError, IOError), # Retry on these exceptions max_tries=5, # Max attempts max_time=30, # Max total time in seconds jitter=backoff.full_jitter, # Add randomness to delays on_backoff=lambda details: print(f"Backing off {details['wait']:.2f}s for {details['target'].__name__} after {details['tries']} tries, due to {details['exception'].__class__.__name__}"), on_giveup=lambda details: print(f"Giving up on {details['target'].__name__} after {details['tries']} tries, last exception {details['exception'].__class__.__name__}")) def call_flaky_api(): global CALL_COUNT CALL_COUNT += 1 print(f"Attempt {CALL_COUNT}: Calling flaky API...") if CALL_COUNT <= MAX_FAILURES: if random.random() < 0.8: # 80% chance to raise ValueError initially raise ValueError("API returned invalid data") else: raise IOError("Network connection lost") # Simulate another failure print(f"Attempt {CALL_COUNT}: API call successful!") return "Data from API" try: result = call_flaky_api() print(f"Final result: {result}") except (ValueError, IOError) as e: print(f"Operation failed after multiple retries: {e}") # Reset call count for a new demonstration CALL_COUNT = 0 print("\n--- Demonstrating with higher success chance after initial failures ---") MAX_FAILURES = 1 # Will likely succeed on the 2nd attempt try: result = call_flaky_api() print(f"Final result: {result}") except (ValueError, IOError) as e: print(f"Operation failed after multiple retries: {e}")
Debug
Known issues
breakingPython 3.7 support was dropped in `backoff` version 2.3.0. Users on Python 3.7 attempting to upgrade to 2.3.0 or later will encounter compatibility issues.
fix
Upgrade your Python environment to 3.8 or newer before upgrading `backoff`.
affects: >=2.3.0
breakingIn `backoff` v2.3.1, the `target` key in the `details` dictionary passed to event handlers (like `on_backoff`, `on_giveup`) changed its type from a string representation to an actual function reference.
fix
If your event handlers inspect `details['target']` and expect a string, update your logic to handle a function object instead. For example, use `details['target'].__name__` to get the function name.
affects: 2.3.1
gotchaThe `@backoff.on_exception` decorator requires the decorated function to raise the specified exception (or a subclass) to trigger a retry. If the function catches the exception internally with a bare `except:` clause and does not re-raise it, `backoff` will not detect the failure and will not retry.
fix
Ensure that the exceptions you want `backoff` to handle are propagated out of the decorated function. Avoid broad `except:` clauses, or explicitly `raise` the exception after handling it internally if retries are still desired.
affects: all
gotchaWhen using `@backoff.on_exception`, it is crucial to provide both a wait generator (e.g., `backoff.expo`, `backoff.constant`) and at least one exception type to retry on. Failing to provide these parameters makes the decorator ineffective.
fix
Always specify the wait strategy and the exceptions. Example: `@backoff.on_exception(backoff.expo, SomeError, max_tries=5)`.
affects: all
Upgrade
Version history
2.2.1latest on PyPI
Audit
Dependencies

No dependency data recorded yet.

Agent activity
100 hits · last 30 days
node
8
seranking-bot
4
mj12bot
3
ahrefsbot
3
bytedance
2
amazonbot
1
googlebot
1
Resources