DevPill 10 - Fault tolerance: adding retries to your Go code
dev.to·3d·
Discuss: DEV
🛡️Error Handling
Preview
Report Post

Adding retries to your API is a must to make your system more resilient. You can add them in database operations, communication with external apis and every other operation that might depend on a response of a third party.

Here’s an example of a retry implementation for database transient errors:

1. First, let’s code the retry function

The function receives the number of attempts, delay (interval between attempts) and the function which represents the operation you want to do.

func Retry(attempts int, delay time.Duration, fn func() error) error {
err := fn()
if err == nil {
return nil
}

if !IsTransientError(err) {
// log.Println("--- retry not needed")
return err
}

if attempts--; attempts > 0 {
time.Sleep(delay)
// log.Println("--- trying again...")
return Retry(attemp...

Similar Posts

Loading similar posts...