Skip to content

Commit d8df714

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

File tree

3 files changed

+146
-1
lines changed

3 files changed

+146
-1
lines changed

async_producer_test.go

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

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