Advertisement
Advanced Python, Exception Handling

How would you implement a retry-with-backoff decorator that catches specific transient exceptions and retries with increasing delays?

Short answer

Wrap the function call in a loop with a try/except catching only the SPECIFIC transient exception types you expect (like a network timeout), sleeping with an exponentially increasing delay between attempts, and re-raising the final exception if all attempts are exhausted.

Save Python mock interview
Advertisement
AModel answer
Wrap the function call in a loop with a try/except catching only the SPECIFIC transient exception types you expect (like a network timeout), sleeping with an exponentially increasing delay between attempts, and re-raising the final exception if all attempts are exhausted.
import time, functools

def retry(exceptions, times=3, delay=1):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(times):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    if attempt == times - 1:
                        raise
                    time.sleep(delay * (2 ** attempt))
            return wrapper
    return decorator

@retry((ConnectionError, TimeoutError), times=3)
def fetch_data():
    ...
Real-world example
Retrying a flaky network request up to three times with increasing delays before giving up and propagating the final failure.
Likely follow-ups
  • Why is it important to only catch SPECIFIC transient exception types here, rather than a bare 'except Exception'?
Related topics