Retry with Exponential Backoff

Difficulty: Easy · Topics: Design, Error Handling, Async

Difficulty: Easy  |  Tags: Design, Error Handling, Async

Description

Implement a retry mechanism that executes a given function and, upon failure, retries with exponential backoff.

Implement:

retryWithBackoff(fn, maxRetries, baseDelayMs) → Result | Error

Backoff formula: Delay after attempt n = baseDelay * 2^n + random jitter

Examples

Example 1 — Succeeds on 3rd try:

Input:
  fn = httpCall (fails first 2 times, succeeds 3rd)
  maxRetries = 5
  baseDelay = 100ms

Execution:
  Attempt 1: FAIL → wait 100ms
  Attempt 2: FAIL → wait 200ms
  Attempt 3: SUCCESS → return result

Output: result from httpCall

Example 2 — All retries exhausted:

Input:
  fn = alwaysFails
  maxRetries = 3
  baseDelay = 50ms

Execution:
  Attempt 1: FAIL → wait 50ms
  Attempt 2: FAIL → wait 100ms
  Attempt 3: FAIL → wait 200ms
  Attempt 4: FAIL → no more retries

Output: Error — "Max retries (3) exceeded"

Constraints

Follow-up

---

## Easy Problems

Practice this problem

Related problems