Retry With Exponential Backoff Jitter
Retry operations with exponential backoff and jitter in Go for transient error handling.
Code
package main
import ("context";"math/rand";"time";"fmt")
func retryWithBackoff(ctx context.Context, maxAttempts int, fn func() error) error {
var lastErr error
for attempt := 0; attempt < maxAttempts; attempt++ {
if err := fn(); err != nil {
lastErr = err
delay := time.Duration(1<<attempt) * time.Millisecond * time.Duration(rand.Intn(100))
select {
case <-ctx.Done(): return ctx.Err()
case <-time.After(delay):
}
} else { return nil }
}
return lastErr
}Report a problem with this exampleOpens a pre-filled issue on GitHub.