Skip to content

Commit ff2dc5f

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

File tree

3 files changed

+154
-2
lines changed

3 files changed

+154
-2
lines changed

async_producer_test.go

+63-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ package sarama
44

55
import (
66
"errors"
7-
"github.com/stretchr/testify/assert"
87
"log"
98
"math"
109
"os"
@@ -18,6 +17,7 @@ import (
1817

1918
"github.com/fortytw2/leaktest"
2019
"github.com/rcrowley/go-metrics"
20+
"github.com/stretchr/testify/assert"
2121
"github.com/stretchr/testify/require"
2222
)
2323

@@ -638,6 +638,68 @@ 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(defaultRetryBackoff, 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+
assert.Greater(t, backoffDurations[0], time.Duration(0),
695+
"Expected first backoff duration to be greater than 0")
696+
for i := 1; i < len(backoffDurations); i++ {
697+
assert.Greater(t, backoffDurations[i], time.Duration(0))
698+
assert.GreaterOrEqual(t, backoffDurations[i], backoffDurations[i-1])
699+
assert.LessOrEqual(t, backoffDurations[i], maxBackoff)
700+
}
701+
}
702+
641703
// https://github.com/IBM/sarama/issues/2129
642704
func TestAsyncProducerMultipleRetriesWithConcurrentRequests(t *testing.T) {
643705
// Logger = log.New(os.Stdout, "[sarama] ", log.LstdFlags)

utils.go

+43
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,15 @@ package sarama
33
import (
44
"bufio"
55
"fmt"
6+
"math/rand"
67
"net"
78
"regexp"
9+
"time"
10+
)
11+
12+
const (
13+
defaultRetryBackoff = 100 * time.Millisecond
14+
defaultRetryMaxBackoff = 1000 * time.Millisecond
815
)
916

1017
type none struct{}
@@ -344,3 +351,39 @@ func (v KafkaVersion) String() string {
344351

345352
return fmt.Sprintf("%d.%d.%d", v.version[0], v.version[1], v.version[2])
346353
}
354+
355+
// NewExponentialBackoff returns a function that implements an exponential backoff strategy with jitter.
356+
// It follows KIP-580, implementing the formula:
357+
// MIN(retry.backoff.max.ms, (retry.backoff.ms * 2**(failures - 1)) * random(0.8, 1.2))
358+
// This ensures retries start with `backoff` and exponentially increase until `maxBackoff`, with added jitter.
359+
// The behavior when `failures = 0` is not explicitly defined in KIP-580 and is left to implementation discretion.
360+
//
361+
// Example usage:
362+
//
363+
// backoffFunc := sarama.NewExponentialBackoff(config.Producer.Retry.Backoff, 2*time.Second)
364+
// config.Producer.Retry.BackoffFunc = backoffFunc
365+
func NewExponentialBackoff(backoff time.Duration, maxBackoff time.Duration) func(retries, maxRetries int) time.Duration {
366+
if backoff <= 0 {
367+
backoff = defaultRetryBackoff
368+
}
369+
if maxBackoff <= 0 {
370+
maxBackoff = defaultRetryMaxBackoff
371+
}
372+
373+
if backoff > maxBackoff {
374+
Logger.Println("Warning: backoff is greater than maxBackoff, using maxBackoff instead.")
375+
backoff = maxBackoff
376+
}
377+
378+
return func(retries, maxRetries int) time.Duration {
379+
if retries <= 0 {
380+
return backoff
381+
}
382+
383+
calculatedBackoff := backoff * time.Duration(1<<(retries-1))
384+
jitter := 0.8 + 0.4*rand.Float64()
385+
calculatedBackoff = time.Duration(float64(calculatedBackoff) * jitter)
386+
387+
return min(calculatedBackoff, maxBackoff)
388+
}
389+
}

utils_test.go

+48-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22

33
package sarama
44

5-
import "testing"
5+
import (
6+
"testing"
7+
"time"
8+
)
69

710
func TestVersionCompare(t *testing.T) {
811
if V0_8_2_0.IsAtLeast(V0_8_2_1) {
@@ -95,3 +98,47 @@ func TestVersionParsing(t *testing.T) {
9598
}
9699
}
97100
}
101+
102+
func TestExponentialBackoffValidCases(t *testing.T) {
103+
testCases := []struct {
104+
retries int
105+
maxRetries int
106+
minBackoff time.Duration
107+
maxBackoffExpected time.Duration
108+
}{
109+
{1, 5, 80 * time.Millisecond, 120 * time.Millisecond},
110+
{3, 5, 320 * time.Millisecond, 480 * time.Millisecond},
111+
{5, 5, 1280 * time.Millisecond, 1920 * time.Millisecond},
112+
}
113+
114+
for _, tc := range testCases {
115+
backoffFunc := NewExponentialBackoff(100*time.Millisecond, 2*time.Second)
116+
backoff := backoffFunc(tc.retries, tc.maxRetries)
117+
if backoff < tc.minBackoff || backoff > tc.maxBackoffExpected {
118+
t.Errorf("backoff(%d, %d): expected between %v and %v, got %v", tc.retries, tc.maxRetries, tc.minBackoff, tc.maxBackoffExpected, backoff)
119+
}
120+
}
121+
}
122+
123+
func TestExponentialBackoffDefaults(t *testing.T) {
124+
testCases := []struct {
125+
backoff time.Duration
126+
maxBackoff time.Duration
127+
}{
128+
{-100 * time.Millisecond, 2 * time.Second},
129+
{100 * time.Millisecond, -2 * time.Second},
130+
{-100 * time.Millisecond, -2 * time.Second},
131+
{0 * time.Millisecond, 2 * time.Second},
132+
{100 * time.Millisecond, 0 * time.Second},
133+
{0 * time.Millisecond, 0 * time.Second},
134+
}
135+
136+
for _, tc := range testCases {
137+
backoffFunc := NewExponentialBackoff(tc.backoff, tc.maxBackoff)
138+
backoff := backoffFunc(2, 5)
139+
if backoff < defaultRetryBackoff || backoff > defaultRetryMaxBackoff {
140+
t.Errorf("backoff(%v, %v): expected between %v and %v, got %v",
141+
tc.backoff, tc.maxBackoff, defaultRetryBackoff, defaultRetryMaxBackoff, backoff)
142+
}
143+
}
144+
}

0 commit comments

Comments
 (0)