Retry with Exponential Backoff
Source: Custom
Topics: Generics, Context, time.Timer, Exponential backoff
Problem
Implement Do that retries a fallible function with exponential backoff and jitter.
Requirements:
- Attempt
fn up to cfg.MaxAttempts times.
- Return immediately on success (non-nil value, nil error).
- Between attempts, sleep for
BaseDelay << attempt (doubles each retry), capped at MaxDelay.
- Add random jitter of up to 10% of the computed delay to prevent thundering-herd retries.
- Stop early and return
ctx.Err() if the context is cancelled during a sleep.
Types:
type Config struct {
MaxAttempts int
BaseDelay time.Duration
MaxDelay time.Duration
}
func Do[T any](ctx context.Context, cfg Config, fn func() (T, error)) (T, error)
Key concepts
- Exponential backoff:
delay = BaseDelay << attempt — doubles on each retry.
- Cap:
min(delay, MaxDelay) prevents unbounded waits.
- Jitter:
delay += rand.N(delay/10 + 1) breaks synchronised retry storms.
- Context-aware sleep:
time.NewTimer + select on ctx.Done() — don't use time.Sleep directly.
Run
go test -v -bench=. -benchmem ./challenges/concurrency/retry/
Sign in to submit your solution.