Tags: #go #backoff #retry #resilience
package main
import (
"context"
"errors"
"fmt"
"math"
"time"
)
func main() {
if err := doSomething(); err != nil {
fmt.Println("there was an error:", err)
}
}
func doSomething() error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
var (
// initialBackoff is the initial backoff used for exponential backoff
initialBackoff = 100 * time.Millisecond
// is the maximum value to use for exponential backoff
maxBackoff = 500 * time.Millisecond
// maxRetries is the number of retries
maxRetries = 3
)
for attempt := range maxRetries {
// exponential backoff
backoff := time.Duration(math.Pow(2, float64(attempt+1))) * initialBackoff
if backoff > maxBackoff {
backoff = maxBackoff
}
fmt.Println(backoff)
select {
case <-ctx.Done():
return errors.New("whoops: timeout")
case <-time.After(backoff):
// continue
}
}
return errors.New("unable to perform the task, max retries exceeded")
}
// Alternative implementation
func (s *service) CreateVersion(ctx context.Context, customerID, configID string, cloneVersion *int, comment string) (*ConfigVersion, error) {
const maxRetries = 3
for attempt := 0; attempt < maxRetries; attempt++ {
version, err := s.createVersionAttempt(ctx, customerID, configID, cloneVersion, comment)
if err == nil {
return version, nil
}
// Retry only on duplicate errors (race condition)
if !errors.Is(err, errorsx.ErrDuplicate) {
return nil, err
}
// Exponential backoff: 10ms, 20ms, 40ms
backoff := time.Duration(10 * (1 << attempt)) * time.Millisecond
time.Sleep(backoff)
}
return nil, fmt.Errorf("failed to create version after %d attempts: %w", maxRetries, errorsx.ErrDuplicate)
}