Skip to content

Commit

Permalink
adds a jitter to backoff
Browse files Browse the repository at this point in the history
  • Loading branch information
yhassanzadeh13 committed May 9, 2022
1 parent a9f4edf commit a77d435
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions backoff.go
Expand Up @@ -2,18 +2,20 @@ package pubsub

import (
"context"
"math/rand"
"sync"
"time"

"github.com/libp2p/go-libp2p-core/peer"
)

const (
MinBackoffDelay = 100 * time.Millisecond
MaxBackoffDelay = 10 * time.Second
MinBackoffDelay = 100 * time.Millisecond
MaxBackoffDelay = 10 * time.Second
TimeToLive = 10 * time.Minute
BackoffCleanupInterval = 1 * time.Minute
BackoffMultiplier = 2
MaxBackoffJitterCoff = 1000
)

type backoffHistory struct {
Expand All @@ -36,6 +38,7 @@ func newBackoff(ctx context.Context, sizeThreshold int, cleanupInterval time.Dur
info: make(map[peer.ID]*backoffHistory),
}

rand.Seed(time.Now().UnixNano()) // used for jitter
go b.cleanupLoop(ctx)

return b
Expand All @@ -54,7 +57,8 @@ func (b *backoff) updateAndGet(id peer.ID) time.Duration {
} else if h.duration < MinBackoffDelay {
h.duration = MinBackoffDelay
} else if h.duration < MaxBackoffDelay {
h.duration = time.Duration(BackoffMultiplier * h.duration)
jitter := rand.Intn(MaxBackoffJitterCoff)
h.duration = (BackoffMultiplier * h.duration) + time.Duration(jitter) * time.Millisecond
if h.duration > MaxBackoffDelay || h.duration < 0 {
h.duration = MaxBackoffDelay
}
Expand Down

0 comments on commit a77d435

Please sign in to comment.