luminyra

Quickstart

Run a retry with backoff and Stop, then combine a retry, a breaker, and a timeout.

Run the retry example

Use Go 1.27 or later. Install resil, save the complete example as main.go, and run go run .. From the resil source directory, run go run ./examples/retry.

go get github.com/luminyra/resil
Complete retry example
// Command retry calls a flaky service with exponential backoff, logs every
// retry, and gives up at once on an error that retrying cannot fix.
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/luminyra/resil"
)

var errNotFound = errors.New("order not found")

// fetchOrder fails twice with a temporary error, then succeeds. It returns
// errNotFound, marked with resil.Stop, for unknown orders.
func fetchOrder(calls *int) func(ctx context.Context, id int) (string, error) {
	return func(ctx context.Context, id int) (string, error) {
		*calls++
		if id != 42 {
			return "", resil.Stop(errNotFound)
		}
		if *calls < 3 {
			return "", errors.New("503 service unavailable")
		}
		return "order 42: 3 items", nil
	}
}

func main() {
	ctx := context.Background()

	retry := resil.Retry{
		Attempts: 5,
		Delay:    50 * time.Millisecond,
		MaxDelay: time.Second,
		Jitter:   0.2,
		OnRetry: func(attempt int, err error, wait time.Duration) {
			fmt.Printf("attempt %d failed (%v), retrying in about %s\n", attempt, err, wait.Round(10*time.Millisecond))
		},
	}

	for _, id := range []int{42, 7} {
		calls := 0
		fetch := fetchOrder(&calls)
		order, err := retry.Get(ctx, func(ctx context.Context) (string, error) {
			return fetch(ctx, id)
		})
		fmt.Printf("order %d: %q, err=%v, calls=%d\n", id, order, err, calls)
	}
}
View on GitHub

Order 42 fails twice with a 503 and succeeds on the third attempt. Order 7 returns "not found" wrapped with Stop, so it is called only once.

Watch the retries

Retry is a plain struct, and every field is optional. In the test below, the operation fails twice and then succeeds, so Retry.Do returns nil.

resil/example_test.go
attempt := 0
err := resil.Retry{Attempts: 4, Delay: time.Millisecond}.Do(context.Background(), func(context.Context) error {
	attempt++
	fmt.Println("attempt", attempt)
	if attempt < 3 {
		return errors.New("unavailable")
	}
	return nil
})
fmt.Println(err)
Expected output
attempt 1
attempt 2
attempt 3
<nil>
View on GitHub

Combine the building blocks

Nest a retry around a breaker around a timeout. Each attempt goes through the breaker and gets its own deadline. An attempt that times out is retried and counted as a failure, and retrying stops as soon as the breaker opens.

resil/example_test.go
breaker, err := resil.NewBreaker(resil.BreakerConfig{Failures: 3, Cooldown: 10 * time.Second})
if err != nil {
	panic(err)
}
retry := resil.Retry{Attempts: 3, Delay: time.Millisecond}

calls := 0
fetch := func(ctx context.Context) (string, error) {
	calls++
	if calls < 3 {
		return "", errors.New("connection reset")
	}
	return "alice", nil
}

name, err := retry.Get(context.Background(), func(ctx context.Context) (string, error) {
	return breaker.Get(ctx, func(ctx context.Context) (string, error) {
		return resil.Timeout(time.Second).Get(ctx, fetch)
	})
})
fmt.Println(name, err, calls)
Expected output
alice <nil> 3
View on GitHub

Continue with retries and backoff to see how waits are computed and which errors are not retried.

On this page