Skip to main content

Write a function that calls a model API and retries with exponential backoff when the call fails with a rate-limit or server error. For example, with 4 tries and a 1 second base, it waits about 1, 2 and 4 seconds between tries and then raises the last error.

Coding rounds · Intermediate 2

Short answer

Loop over a fixed number of attempts. Call the API inside try and return on success. Catch only retryable errors, such as timeouts, 429 and 5xx. On the last attempt re-raise. Otherwise sleep base * 2 ** attempt, capped, plus random jitter. The cost is bounded: at most max_tries calls and a known worst-case wait.

Deeper answer

First clarify what is safe to retry. Timeouts, HTTP 429 and 5xx errors are worth retrying. A 400 or 401 will fail again, so raise it at once. Ask whether the call is idempotent, because retrying a request that creates something can create it twice.

The structure is for attempt in range(max_tries), with the call in a try block that returns the result. In the except block for retryable errors, re-raise when attempt == max_tries - 1. Otherwise compute delay = min(cap, base * 2 ** attempt) and call time.sleep(delay + random.uniform(0, 1)). The jitter stops many clients from retrying at the same moment. If the response has a Retry-After header, use that value instead.

With base 1 and four tries the waits are about 1, 2 and 4 seconds. Test three cases with a fake call and a fake sleep: success on the third try, failure on every try, and a non-retryable error that must be raised after one call. Say that in production you would log each retry and may use a library such as tenacity.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Python for production

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.