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
0 <= maxRetries <= 101 <= baseDelayMs <= 10000- Jitter: random value between 0 and
baseDelay * 0.1. - Total attempts =
maxRetries + 1(initial + retries).
Follow-up
- Add support for retrying only on specific exception types.
- Add a max total timeout across all retries.
- Support circuit breaker pattern integration.
---
## Easy Problems