Bound retries with backoff and jitter
Bound retries with backoff and jitter
Retry only failures classified as transient, and only when repeating the operation is safe. Exponential backoff grows the waiting interval; jitter spreads retries across clients. A cap, maximum attempts and overall deadline prevent unbounded work. Retrying at every service layer multiplies load.
package main
import ( "context" "errors" "fmt")
func retry(ctx context.Context, call func() error, wait func(context.Context, int) error) error { var err error for i := 0; i < 3; i++ { if e := ctx.Err(); e != nil { return e } err = call() if err == nil { return nil } if !errors.Is(err, transient) || i == 2 { return err } if e := wait(ctx, i); e != nil { return e } } return err}
var transient = errors.New("temporary")
func main() { n := 0 err := retry(context.Background(), func() error { n++ if n < 3 { return transient } return nil }, func(_ context.Context, i int) error { fmt.Println("wait", i); return nil }) fmt.Println(n, err)}The injected wait records the attempt index rather than sleeping. The operation has an explicit transient error category. A real wait must respect context, and the remote call itself must also accept the deadline; the sample call is immediate.
Expected output:
wait 0wait 13 <nil>Calculate a bounded random delay
package main
import ( "fmt" prand "math/rand")
func capDelay(attempt int) int { n := 100 for i := 0; i < attempt && n < 800; i++ { n *= 2 } return n}func main() { r := prand.New(prand.NewSource(42)) for _, a := range []int{0, 1, 10} { cap := capDelay(a) delay := r.Intn(cap + 1) fmt.Println(cap, delay >= 0 && delay <= cap) }}Full jitter selects a delay from zero to the capped interval in milliseconds here. A fixed seed is for reproducible teaching, not identical seeds across service replicas. A cancelable timer can wait using select on timer.C and ctx.Done. Do not retry validation errors, authorization failures or an ambiguous non-idempotent write automatically.
Expected output:
100 true200 true800 trueTry it locally
For a safe immediate read, attempt at most twice. Stop on success or a permanent error. Simulate a permanent error and print the attempt count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed services 02: Bound retries with backoff and jitter
Check the lesson objective before moving on.
Why add jitter?
Which failure should normally stop retrying?