go / backoff
I use a lookup table for retry backoff.
Pattern
The computed version:
delay := baseDelay
for attempt := range maxAttempts {
err := request(ctx)
if err == nil {
return nil
}
delay *= 2
delay = min(delay, maxDelay)
time.Sleep(delay)
}
The table version:
delays := []time.Duration{
1 * time.Second,
2 * time.Second,
4 * time.Second,
8 * time.Second,
16 * time.Second,
}
err := request(ctx)
for _, delay := range delays {
if err == nil {
return nil
}
if err := sleepWithJitter(ctx, delay); err != nil {
return err
}
err = request(ctx)
}
return err
Calling request before the loop avoids sleeping after the last failed
attempt. The sleep helper adds jitter and stops on context cancellation:
func sleepWithJitter(ctx context.Context, delay time.Duration) error {
// Full jitter spreads retries across concurrent callers.
wait := rand.N(delay)
t := time.NewTimer(wait)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
Fixed delays synchronize retries across workers after an outage or rate
limit. Jitter spreads those retries out, and ctx.Done() stops a wait
when the caller cancels.
The table version has fewer variables and keeps no state between iterations. A schedule change is one edit.
Example
A retry loop that backs off on 404s from an eventually-consistent API:
var retryDelays = []time.Duration{
1 * time.Second,
2 * time.Second,
4 * time.Second,
8 * time.Second,
16 * time.Second,
}
func fetchFiles(ctx context.Context, pr int) ([]File, error) {
var files []File
err := api.Get(ctx, &files, "pulls/%d/files", pr)
for _, delay := range retryDelays {
if !errors.Is(err, ErrNotFound) {
break
}
if sleepErr := sleepWithJitter(ctx, delay); sleepErr != nil {
return nil, sleepErr
}
err = api.Get(ctx, &files, "pulls/%d/files", pr)
}
return files, err
}
Limits
The computed version wins only when the delay sequence is unbounded or the program picks it at runtime.