Implement retry with exponential backoff in Go by looping until success or max attempts, doubling the wait time on each failure.
package main
import (
"fmt"
"math/rand"
"time"
)
func RetryWithBackoff(maxAttempts int, fn func() error) error {
baseDelay := 100 * time.Millisecond
maxDelay := 10 * time.Second
for i := 0; i < maxAttempts; i++ {
if err := fn(); err == nil {
return nil
}
if i == maxAttempts-1 {
return err
}
// Exponential backoff: 2^i * baseDelay
backoff := time.Duration(1<<uint(i)) * baseDelay
if backoff > maxDelay {
backoff = maxDelay
}
// Add jitter (±10%)
jitter := time.Duration((0.1*rand.Float64()-0.05) * float64(backoff))
time.Sleep(backoff + jitter)
}
return fmt.Errorf("max retries exceeded")
}