← All Exercises

Retry with Exponential Backoff and Cap

intermediatejavascript~15min

Background

Transient network and service failures are usually retried with exponential backoff. Capping the delay prevents runaway waits, and injecting sleep keeps tests fast and deterministic.

Problem

Implement retry(task, options) where options provide retries, baseDelay, maxDelay, and a sleep function. The first attempt runs immediately; after failure i, wait min(maxDelay, baseDelay * 2^i) before the next attempt. When retries are exhausted, rethrow the last error. Do not delay after the final failed attempt.

Input

A JSON object with failures, retries, baseDelay, maxDelay, and optional error message.

Output

One line with attempts, the comma-separated delays, and either result:ok or error:<message>.

Sample tests

Sample 1

Input: {"failures":2,"retries":3,"baseDelay":100,"maxDelay":250,"error":"ETEMP"}
Expected: attempts:3 delays:100,200 result:ok

Sample 2

Input: {"failures":5,"retries":2,"baseDelay":100,"maxDelay":250,"error":"ETEMP"}
Expected: attempts:3 delays:100,200 error:ETEMP

Sample 3

Input: {"failures":3,"retries":4,"baseDelay":100,"maxDelay":250}
Expected: attempts:4 delays:100,200,250 result:ok

Your solution

Learning objective

Learn bounded retries, exponential backoff with a delay cap, and testable async error handling through dependency injection.