Backoff implements exponential backoff algorithm in Go.
This is simple example.
w.Wait
blocks until next period that are:
- 1±0.5s
- 2±1s
- 4±2s
- 8±4s
It increases exponentially forever.
import (
"context"
"log"
"github.com/lufia/backoff"
)
func main() {
var w backoff.Backoff
for {
if err := w.Wait(context.Background()); err != nil {
log.Fatalln(err)
}
}
}
Next example has limits for increase.
w.Wait
blocks like above example but it is limited by Initial
, Peak
, and Limit
.
Therefore periods are:
- 0.5±0.25s
- 1±0.5s
- 2±1s
- 2±1s
- 2±1s
w.Wait
ends up with an error.
import (
"context"
"log"
"time"
"github.com/lufia/backoff"
)
func main() {
w := backoff.Backoff{
Initial: 500 * time.Millisecond,
Peak: 2 * time.Second,
Limit: 5,
}
for {
if err := w.Wait(context.Background()); err != nil {
log.Fatalln(err)
}
}
}