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
}Inside the snippet
Retry With Exponential Backoff Jitter is built around the function retryWithBackoff.
Repetition is confined to for attempt := 0; attempt < maxAttempts; attempt++ — the rest of the file is straight-line. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.
Caveats
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
The primary signature is func retryWithBackoff(ctx context.Context, maxAttempts int, fn func() error) error
Core lines
case <-ctx.Done(): return ctx.Err()
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- As returned `error` values, checked at its call site — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `retryWithBackoff` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.