L2 · Working engineerAdvanced L2~10 min · 4 tests#84

Retry Decorator With Max Attempts

Write a Python @retry decorator that re-runs a failing function up to N times, logs each attempt and re-raises after the last. Tested with a flaky function.

The problem

Write a decorator factory retry(max_attempts):

  • call the function; if it raises, print Attempt <k> -> Failed and try again
  • on success print Attempt <k> -> Success and return the result
  • after max_attempts failures, re-raise the last exception

A function that fails twice and then succeeds should print:

Attempt 1 -> Failed
Attempt 2 -> Failed
Attempt 3 -> Success

Examples

  1. Example 1

    Input

    captured(run_retry, retry, 2, 3)

    Expected output

    'Attempt 1 -> Failed\nAttempt 2 -> Failed\nAttempt 3 -> Success\n'
  2. Example 2

    Input

    run_retry(retry, 1, 3)

    Expected output

    'ok'

+ 2 hidden tests on Submit — re-raises after the last attempt.

Edge cases to ask about

  • Success on first try
  • All attempts fail
  • Exception type preserved
How the tests call your code

These helpers run before your code. The test inputs above call them.

def flaky(fail_times, value="ok"):
    state = {"calls": 0}
    def call():
        state["calls"] += 1
        if state["calls"] <= fail_times:
            raise ConnectionError("temporary failure")
        return value
    return call

def run_retry(retry, fail_times, max_attempts):
    fn = retry(max_attempts)(flaky(fail_times))
    return fn()

def exhausted(retry):
    fn = retry(3)(flaky(5))
    out = captured(lambda: raises(fn))
    return out, raises(retry(3)(flaky(5)))

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · retry
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Loop inside the wrapperO(k)O(1)Production versions add exponential backoff with jitter.
    Walkthrough of the optimal approach (try it yourself first)

    Loop over attempts. try the call; except Exception prints the failure and, on the last attempt, re-raises with a bare raise (keeping the original traceback). The else branch runs only on success.

    In production: catch only retryable exceptions (ConnectionError, timeouts — never KeyboardInterrupt), and sleep with exponential backoff and jitter between attempts so a thousand clients do not retry in lockstep. Libraries like tenacity do this.

    Complexity: O(k) time, O(1) space. At most k = max_attempts calls of the wrapped function.

    Reveal the reference solution
    import functools
    
    def retry(max_attempts):
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                for attempt in range(1, max_attempts + 1):
                    try:
                        result = func(*args, **kwargs)
                    except Exception:
                        print(f"Attempt {attempt} -> Failed")
                        if attempt == max_attempts:
                            raise
                    else:
                        print(f"Attempt {attempt} -> Success")
                        return result
            return wrapper
        return decorator

    Follow-ups interviewers ask

    • Add exponential backoff with jitter.
    • Retry only on specific exception types.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Retry Decorator With Max Attempts in Python?

    The optimal solution runs in O(k) time and O(1) auxiliary space. At most k = max_attempts calls of the wrapped function.

    What follow-up questions do interviewers ask about Retry Decorator With Max Attempts?

    Add exponential backoff with jitter. Retry only on specific exception types.