-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add exponential backoff when doing updates
- Loading branch information
1 parent
734a8e9
commit 1d31f50
Showing
2 changed files
with
45 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"time" | ||
) | ||
|
||
// Operation is a function type that represents an operation that might fail and need a retry. | ||
type Operation func() error | ||
|
||
const ( | ||
maxRetries = 5 | ||
initialBackoff = 300 * time.Millisecond | ||
) | ||
|
||
// ExponentialBackoff retries the provided operation with an exponential backoff strategy. | ||
func ExponentialBackoff(operation Operation, maxRetries int, initialBackoff time.Duration) error { | ||
backoff := initialBackoff | ||
var err error | ||
for i := 0; i < maxRetries; i++ { | ||
err = operation() | ||
if err == nil { | ||
return nil // Success | ||
} | ||
|
||
if i < maxRetries-1 { | ||
// If not the last retry, wait for a bit | ||
time.Sleep(backoff) | ||
backoff *= 2 // Exponential increase | ||
} | ||
} | ||
|
||
return fmt.Errorf("operation failed after %d retries, returned error: %s", maxRetries, err) | ||
} |