Python Python Free

Python: Retry with Exponential Backoff Decorator for API Calls

A Python decorator that retries a failing API call with exponential backoff — wait longer after each failure, then give up cleanly.

28 lines · Updated Nov 26, 2026

Preview of Python: Retry with Exponential Backoff Decorator for API Calls
python-retry-exponential-backoff-decorator.py
import time
import functools


def retry(tries=3, delay=2, backoff=2, exceptions=(Exception,)):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            wait = delay
            for attempt in range(tries):
                try:
                    return func(*args, **kwargs)
                except exceptions as error:
                    if attempt == tries - 1:
                        raise
                    print(f"Attempt {attempt + 1} failed: {error}. "
                          f"Retrying in {wait}s...")
                    time.sleep(wait)
                    wait *= backoff
        return wrapper
    return decorator


@retry(tries=3, delay=2)
def fetch_data(url):
    response = requests.get(url, timeout=10)
    response.raise_for_status()
    return response.json()

About this snippet

External APIs fail more often than you expect: rate limits, timeouts, a server restarting for two seconds. A script that gives up on the first error breaks for no good reason; a script that retries immediately in a tight loop makes things worse. This snippet is a reusable Python decorator that retries a function with exponential backoff — waiting a little longer after each failure — so temporary problems fix themselves.

How it works

  1. You wrap any function with the decorator, for example a function that calls an API.
  2. If the function raises one of the listed exceptions, the decorator waits and tries again.
  3. The wait doubles each time (for example 1s, 2s, 4s, 8s), often with a little random "jitter" so many clients do not retry at the same instant.
  4. After the maximum number of attempts, the last error is raised so you still know something is wrong.

How to use it

  • Decorate network calls: @retry(...) above def fetch_prices():.
  • Retry only temporary errors — timeouts, connection errors, HTTP 429 and 5xx responses.
  • Do not retry 400, 401, 403 or 404: those will fail every time.

Choosing settings

  • Interactive tools: 3 attempts, short delays.
  • Background jobs and scheduled scripts: 5–6 attempts with a maximum delay of around a minute.
  • If the API sends a Retry-After header, respect it.

Common problems

  • Duplicate actions: retrying a request that creates something (a payment, an order) can create it twice. Use idempotency keys where the API supports them.

FAQ

Is there a library for this? Yes — tenacity is popular. This snippet is useful when you want zero dependencies and to understand the logic.

Related: Telegram bot message · 10 Python automation projects

How to install

Save the decorator in a helpers module and import it wherever you call an API. Pass tries, delay and exceptions to suit the API — retry only on transient errors like timeouts, not on 400 errors.

Share this snippet

See all
Chat with us