Polski

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.

easy · typescript · javascript · python · csharp · java · go · 10 XP

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 delay and try again,
  • the delay before the k-th retry is min(maxDelay, baseDelay · 2^(k−1)) – i.e. base, 2·base, 4·base… up to the cap,
  • there are at most retries + 1 attempts 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; no shouldRetry = retry every error.
LanguageSignature
JS/TSawait retry(operation, { retries, baseDelayMs, maxDelayMs = Infinity, shouldRetry?, sleep? }) – operation may return a value or a Promise, sleep(ms) returns a Promise (defaults to setTimeout)
Pythonretry(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)
JavaSolution.retry(IntFunction<T> operation, int retries, long baseDelayMs, long maxDelayMs, LongConsumer sleep, Predicate<RuntimeException> shouldRetry) – shouldRetry may be null
GoRetry(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:

AttemptResultThen
1errorsleep(100)
2errorsleep(200)
3errorsleep(300) – the cap instead of 400
4successreturn 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