Kotlin retry loop with capped exponential backoff
Kotlin
import kotlin.random.Random
fun <T> retry(
attempts: Int = 5,
baseMs: Long = 100,
maxMs: Long = 5_000,
block: () -> T,
): T {
var delayMs = baseMs
repeat(attempts - 1) {
try {
return block()
} catch (e: Exception) {
// full jitter avoids synchronized retries
val cap = minOf(delayMs, maxMs)
Thread.sleep(Random.nextLong(cap / 2, cap + 1))
delayMs = minOf(delayMs * 2, maxMs)
}
}
return block()
}