Skip to content

Commit e39f515

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

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
@@ -89,3 +89,18 @@ func (r *rng) string() string {
8989
func newRng() *rng {
9090
return &rng{random: rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), uint64(os.Getpid())))}
9191
}
92+
93+
var rngPool = sync.Pool{
94+
New: func() any {
95+
seed := time.Now().UnixNano() + int64(os.Getpid())
96+
return rand.New(rand.NewSource(seed))
97+
},
98+
}
99+
100+
func randomString() string {
101+
r := rngPool.Get().(*rand.Rand)
102+
n := r.Intn(10000) + 1
103+
rngPool.Put(r)
104+
105+
return strconv.Itoa(n)
106+
}

0 commit comments

Comments
 (0)