Skip to content

Commit 2cf05e9

Browse files
committed
feat: exponential backoff for clients
Signed-off-by: Wenli Wan <[email protected]>
1 parent 9ae475a commit 2cf05e9

File tree

3 files changed

+147
-1
lines changed

3 files changed

+147
-1
lines changed

async_producer_test.go

+64
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,70 @@ func TestAsyncProducerMultipleRetriesWithBackoffFunc(t *testing.T) {
638638
}
639639
}
640640

641+
func TestAsyncProducerWithExponentialBackoffDurations(t *testing.T) {
642+
Logger = log.New(os.Stdout, "[sarama] ", log.LstdFlags)
643+
var backoffDurations []time.Duration
644+
var mu sync.Mutex
645+
646+
topic := "my_topic"
647+
maxBackoff := 2 * time.Second
648+
config := NewTestConfig()
649+
650+
innerBackoffFunc := NewExponentialBackoff(100*time.Millisecond, maxBackoff)
651+
backoffFunc := func(retries, maxRetries int) time.Duration {
652+
duration := innerBackoffFunc(retries, maxRetries)
653+
mu.Lock()
654+
backoffDurations = append(backoffDurations, duration)
655+
mu.Unlock()
656+
return duration
657+
}
658+
659+
config.Producer.Flush.Messages = 5
660+
config.Producer.Return.Successes = true
661+
config.Producer.Retry.Max = 3
662+
config.Producer.Retry.BackoffFunc = backoffFunc
663+
664+
broker := NewMockBroker(t, 1)
665+
666+
metadataResponse := new(MetadataResponse)
667+
metadataResponse.AddBroker(broker.Addr(), broker.BrokerID())
668+
metadataResponse.AddTopicPartition(topic, 0, broker.BrokerID(), nil, nil, nil, ErrNoError)
669+
broker.Returns(metadataResponse)
670+
671+
producer, err := NewAsyncProducer([]string{broker.Addr()}, config)
672+
if err != nil {
673+
t.Fatal(err)
674+
}
675+
676+
failResponse := new(ProduceResponse)
677+
failResponse.AddTopicPartition(topic, 0, ErrNotLeaderForPartition)
678+
successResponse := new(ProduceResponse)
679+
successResponse.AddTopicPartition(topic, 0, ErrNoError)
680+
681+
broker.Returns(failResponse)
682+
broker.Returns(metadataResponse)
683+
broker.Returns(failResponse)
684+
broker.Returns(metadataResponse)
685+
broker.Returns(successResponse)
686+
687+
for i := 0; i < 5; i++ {
688+
producer.Input() <- &ProducerMessage{Topic: topic, Value: StringEncoder("test")}
689+
}
690+
691+
expectResults(t, producer, 5, 0)
692+
closeProducer(t, producer)
693+
broker.Close()
694+
695+
for i := 1; i < len(backoffDurations); i++ {
696+
if backoffDurations[i] < backoffDurations[i-1] {
697+
t.Errorf("expected backoff[%d] >= backoff[%d], got %v < %v", i, i-1, backoffDurations[i], backoffDurations[i-1])
698+
}
699+
if backoffDurations[i] > maxBackoff {
700+
t.Errorf("backoff exceeded max: %v", backoffDurations[i])
701+
}
702+
}
703+
}
704+
641705
// https://github.com/IBM/sarama/issues/2129
642706
func TestAsyncProducerMultipleRetriesWithConcurrentRequests(t *testing.T) {
643707
// Logger = log.New(os.Stdout, "[sarama] ", log.LstdFlags)

utils.go

+33
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ package sarama
33
import (
44
"bufio"
55
"fmt"
6+
"math/rand"
67
"net"
78
"regexp"
9+
"time"
810
)
911

1012
type none struct{}
@@ -344,3 +346,34 @@ func (v KafkaVersion) String() string {
344346

345347
return fmt.Sprintf("%d.%d.%d", v.version[0], v.version[1], v.version[2])
346348
}
349+
350+
// NewExponentialBackoff returns a function that implements an exponential backoff strategy with jitter.
351+
// It follows KIP-580, implementing the formula:
352+
// MIN(retry.backoff.max.ms, (retry.backoff.ms * 2**(failures - 1)) * random(0.8, 1.2))
353+
// This ensures retries start with `backoff` and exponentially increase until `maxBackoff`, with added jitter.
354+
//
355+
// Example usage:
356+
//
357+
// backoffFunc := sarama.NewExponentialBackoff(config.Producer.Retry.Backoff, 2*time.Second)
358+
// config.Producer.Retry.BackoffFunc = backoffFunc
359+
func NewExponentialBackoff(backoff time.Duration, maxBackoff time.Duration) func(retries, maxRetries int) time.Duration {
360+
backoff = max(backoff, 0)
361+
maxBackoff = max(maxBackoff, 0)
362+
363+
if backoff > maxBackoff {
364+
Logger.Println("Warning: backoff is greater than maxBackoff, using maxBackoff instead.")
365+
backoff = maxBackoff
366+
}
367+
368+
return func(retries, maxRetries int) time.Duration {
369+
if retries <= 0 {
370+
return backoff
371+
}
372+
373+
calculatedBackoff := backoff * time.Duration(1<<(retries-1))
374+
jitter := 0.8 + 0.4*rand.Float64()
375+
calculatedBackoff = time.Duration(float64(calculatedBackoff) * jitter)
376+
377+
return min(calculatedBackoff, maxBackoff)
378+
}
379+
}

utils_test.go

+50-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33
package sarama
44

5-
import "testing"
5+
import (
6+
"sync"
7+
"testing"
8+
"time"
9+
)
610

711
func TestVersionCompare(t *testing.T) {
812
if V0_8_2_0.IsAtLeast(V0_8_2_1) {
@@ -95,3 +99,48 @@ func TestVersionParsing(t *testing.T) {
9599
}
96100
}
97101
}
102+
103+
func TestExponentialBackoffCorrectness(t *testing.T) {
104+
testCases := []struct {
105+
backoff time.Duration
106+
maxBackoff time.Duration
107+
retries int
108+
maxRetries int
109+
minBackoff time.Duration
110+
maxBackoffExpected time.Duration
111+
}{
112+
{100 * time.Millisecond, 2 * time.Second, 0, 5, 100 * time.Millisecond, 100 * time.Millisecond},
113+
{100 * time.Millisecond, 2 * time.Second, 1, 5, 80 * time.Millisecond, 120 * time.Millisecond},
114+
{100 * time.Millisecond, 2 * time.Second, 3, 5, 320 * time.Millisecond, 480 * time.Millisecond},
115+
{100 * time.Millisecond, 2 * time.Second, 5, 5, 1280 * time.Millisecond, 1920 * time.Millisecond},
116+
{-100 * time.Millisecond, 2 * time.Second, 3, 5, 0, 480 * time.Millisecond},
117+
{100 * time.Millisecond, -2 * time.Second, 3, 5, 0, 0},
118+
{-100 * time.Millisecond, -2 * time.Second, 3, 5, 0, 0},
119+
{0 * time.Millisecond, 2 * time.Second, 3, 5, 0, 480 * time.Millisecond},
120+
{100 * time.Millisecond, 0 * time.Second, 3, 5, 0, 0},
121+
{0 * time.Millisecond, 0 * time.Second, 3, 5, 0, 0},
122+
}
123+
124+
for _, tc := range testCases {
125+
backoffFunc := NewExponentialBackoff(tc.backoff, tc.maxBackoff)
126+
backoff := backoffFunc(tc.retries, tc.maxRetries)
127+
if backoff < tc.minBackoff || backoff > tc.maxBackoffExpected {
128+
t.Errorf("backoff(%d, %d): expected between %v and %v, got %v", tc.retries, tc.maxRetries, tc.minBackoff, tc.maxBackoffExpected, backoff)
129+
}
130+
}
131+
}
132+
133+
func TestExponentialBackoffRaceDetection(t *testing.T) {
134+
backoffFunc := NewExponentialBackoff(100*time.Millisecond, 2*time.Second)
135+
var wg sync.WaitGroup
136+
concurrency := 1000
137+
138+
wg.Add(concurrency)
139+
for i := 0; i < concurrency; i++ {
140+
go func(i int) {
141+
defer wg.Done()
142+
_ = backoffFunc(i%10, 5)
143+
}(i)
144+
}
145+
wg.Wait()
146+
}

0 commit comments

Comments
 (0)