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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help