typestar

Retry with backoff in Python

Exponential backoff is the polite way to retry flaky calls.

import time

def retry(fn, attempts=3, delay=0.5):
    for attempt in range(attempts):
        try:
            return fn()
        except Exception:
            if attempt == attempts - 1:
                raise
            time.sleep(delay * (2 ** attempt))

How it works

  1. Calls the function and returns on success.
  2. On failure, time.sleep waits, doubling the delay each attempt.
  3. The final failure re-raises the original exception.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
186
Tokens
54
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 31 seconds.

Type this snippet

Step 5 of 5 in Decorators & closures, step 9 of 53 in Pythonic Python.

← Previous Next →

Retry with backoff in other languages