retryWithExponentialBackoff

suspend fun <R> retryWithExponentialBackoff(retries: Long = 3, base: Duration = 200.milliseconds, factor: Double = 2.0, block: suspend () -> R): R(source)

Executes a suspend operation with retry capabilities using exponential backoff and jitter.

This is the primary retry function for most use cases. It uses exponential backoff strategy with automatic jitter (10%) to prevent thundering herd problems.

Retry Behavior:

  • Total attempts = initial attempt + retries

  • Delay grows exponentially: base * factor^attempt

  • Jitter (±10%) randomizes delays to avoid synchronized retries

  • All exceptions are retried (except CancellationException)

Return

The result of the successful execution

Parameters

retries

The maximum number of retry attempts after the initial attempt (defaults to 3)

base

The base duration for exponential backoff (defaults to 200 milliseconds)

factor

The exponential factor (defaults to 2.0)

block

The suspend operation to execute

Type Parameters

R

The return type of the suspend operation

Throws

if all retry attempts fail

Example usage:

val user = retryWithExponentialBackoff(retries = 5) {
userService.fetchUser("user123")
}