Timeouts and combining
Use Timeout to tell its own deadline apart from the caller's cancellation, and nest a retry, a breaker, and a timeout.
Limit how long a call may take
Timeout is a duration type, used as resil.Timeout(2*time.Second).Get(ctx, op). It gives the operation a context that ends after the duration. The difference from context.WithTimeout is the error: when its own deadline fires, the error matches ErrTimeout and still matches context.DeadlineExceeded. When the caller cancels, the error is returned unchanged.
slow := func(ctx context.Context) error {
select {
case <-time.After(time.Second):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
err := resil.Timeout(10*time.Millisecond).Do(context.Background(), slow)
fmt.Println(errors.Is(err, resil.ErrTimeout))trueTimeout never abandons a running operation. It cancels the context and waits for the operation to return, so it starts no goroutines and leaks none. The trade-off is that an operation that ignores its context cannot be interrupted.
Nest the building blocks
The three nest as closures, so the order is visible at the call site. The usual order is 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 by the breaker;
- once the breaker opens it returns
ErrOpen, which a retry does not retry by default, so it stops at once; - a request the caller cancelled is neither retried nor counted by the breaker.
In the example, the service hangs on the first call, returns a 502 on the second, and answers on the third.
breaker, err := resil.NewBreaker(resil.BreakerConfig{
FailureRate: 0.5, // open when half the calls fail...
Window: time.Minute, // ...over the last minute...
MinRequests: 20, // ...once there are 20 of them
Cooldown: 10 * time.Second, // then probe again after 10s
})
if err != nil {
panic(err)
}
retry := resil.Retry{
Attempts: 4,
Delay: 20 * time.Millisecond,
OnRetry: func(attempt int, err error, _ time.Duration) {
fmt.Printf("attempt %d: %v (timeout: %v)\n", attempt, err, errors.Is(err, resil.ErrTimeout))
},
}
timeout := resil.Timeout(100 * time.Millisecond)
quote, err := retry.Get(context.Background(), func(ctx context.Context) (Quote, error) {
return breaker.Get(ctx, func(ctx context.Context) (Quote, error) {
return timeout.Get(ctx, fetchQuote)
})
})
fmt.Printf("quote=%+v err=%v breaker=%s\n", quote, err, breaker.State())Test code that waits
resil times and waits through the standard time package. Inside a testing/synctest bubble, retry backoff and breaker cooldowns finish instantly, so tests do not wait in real time.