Retry with exponential backoff
A function that retries a failed operation after 100, 200, 400… ms, with a cap and an error filter. The sleep function is injected, so tests never wait a millisecond.
An external API sometimes answers 503, but works again a moment later. Instead of giving up immediately we retry – waiting twice as long each time so we do not hammer an overloaded service. The sleep function is injected, so tests check the delays without really waiting.
Task
retry calls operation(attempt) (attempt numbers start at 1):
- success → return the operation's result,
- error → if retries are left and the error is retryable, sleep for
delayand try again, - the delay before the
k-th retry ismin(maxDelay, baseDelay · 2^(k−1))– i.e.base,2·base,4·base… up to the cap, - there are at most
retries + 1attempts in total; after the last failed attempt the function throws the last error (the same object, not wrapped), shouldRetry(error)returning false stops retrying immediately (no sleep) and throws that error; noshouldRetry= retry every error.
| Language | Signature |
|---|---|
| JS/TS | await retry(operation, { retries, baseDelayMs, maxDelayMs = Infinity, shouldRetry?, sleep? }) – operation may return a value or a Promise, sleep(ms) returns a Promise (defaults to setTimeout) |
| Python | retry(operation, retries, base_delay, max_delay=inf, should_retry=None, sleep=time.sleep) |
| C# | Solution.Retry<T>(Func<int, T> operation, int retries, int baseDelayMs, int maxDelayMs, Action<int> sleep, Func<Exception, bool> shouldRetry = null) |
| Java | Solution.retry(IntFunction<T> operation, int retries, long baseDelayMs, long maxDelayMs, LongConsumer sleep, Predicate<RuntimeException> shouldRetry) – shouldRetry may be null |
| Go | Retry(operation func(attempt int) error, retries int, baseDelay, maxDelay time.Duration, sleep func(time.Duration), shouldRetry func(error) bool) error – nil means success |
Example
retries = 3, baseDelay = 100, maxDelay = 300, the operation succeeds on the fourth attempt:
| Attempt | Result | Then |
|---|---|---|
| 1 | error | sleep(100) |
| 2 | error | sleep(200) |
| 3 | error | sleep(300) – the cap instead of 400 |
| 4 | success | return the result |
Constraints
0 ≤ retries ≤ 100,1 ≤ baseDelay ≤ maxDelay ≤ 10⁹(C#/Java/Go).- The delay must not overflow or turn negative, even with 100 retries.
Expected complexity
O(retries) time besides the operation and the sleeping, O(1) memory.
Topics: Circuit Breaker