Skip to content

Commit db94232

Browse files
committed
fix: use a sync pool for strategy randomness, which offers slightly better perf under load
1 parent 4b5508d commit db94232

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

internal/strategies/flexible_rollout.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ func (s flexibleRolloutStrategy) Name() string {
3131
func (s flexibleRolloutStrategy) resolveStickiness(st stickiness, ctx context.Context) string {
3232
switch st {
3333
case defaultStickiness:
34-
return coalesce(ctx.UserId, ctx.SessionId, s.random.string())
34+
return coalesce(ctx.UserId, ctx.SessionId, randomString())
3535
case randomStickiness:
36-
return s.random.string()
36+
return randomString()
3737
default:
3838
return ctx.Field(string(st))
3939
}

internal/strategies/helpers.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,18 @@ func newRng() *rng {
102102
seed := time.Now().UnixNano() + int64(os.Getpid())
103103
return &rng{random: rand.New(rand.NewSource(seed))}
104104
}
105+
106+
var rngPool = sync.Pool{
107+
New: func() any {
108+
seed := time.Now().UnixNano() + int64(os.Getpid())
109+
return rand.New(rand.NewSource(seed))
110+
},
111+
}
112+
113+
func randomString() string {
114+
r := rngPool.Get().(*rand.Rand)
115+
n := r.Intn(10000) + 1
116+
rngPool.Put(r)
117+
118+
return strconv.Itoa(n)
119+
}

0 commit comments

Comments
 (0)