Retry With Exponential Backoff Jitter

Retry operations with exponential backoff and jitter in Go for transient error handling.

GoResilience

Code

snippet
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
}