Skip to content

Commit

Permalink
swap: add exponential backoff and jitter mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
YusukeShimizu committed Jun 27, 2024
1 parent 6c6c802 commit c4e9145
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions swap/fsm.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package swap
import (
"errors"
"fmt"
"math"
"math/rand"
"sync"
"time"

Expand All @@ -26,6 +28,11 @@ const (

// NoOp represents a no-op event.
NoOp EventType = "NoOp"

// exponentialBackoffBase is the base value for the exponential backoff as milliseconds
exponentialBackoffBase int = 1000
// exponentialBackoffCap is the maximum value for the exponential backoff as milliseconds
exponentialBackoffCap int = 20000
)

// StateType represents an extensible state type in the state machine.
Expand Down Expand Up @@ -243,6 +250,7 @@ func (s *SwapStateMachine) SendEvent(event EventType, eventCtx EventContext) (bo
return false, nil
case Event_OnRetry:
s.retries++
s.exponentialBackoffAndJitter()
if s.retries > 20 {
s.retries = 0
return false, nil
Expand All @@ -257,6 +265,17 @@ func (s *SwapStateMachine) SendEvent(event EventType, eventCtx EventContext) (bo
}
}

// exponentialBackoffAndJitter is function to wait for
// exponential backoff and jitter.
func (s *SwapStateMachine) exponentialBackoffAndJitter() {
temp := exponentialBackoffBase * int(math.Pow(2, float64(s.retries)))
if temp > exponentialBackoffCap {
temp = exponentialBackoffCap
}
sleep := rand.Intn(temp)
time.Sleep(time.Duration(sleep) * time.Millisecond)
}

// Recover tries to continue from the current state, by doing the associated Action
func (s *SwapStateMachine) Recover() (bool, error) {
log.Infof("[Swap:%s]: Recovering from state %s", s.SwapId.String(), s.Current)
Expand Down

0 comments on commit c4e9145

Please sign in to comment.