Files
mtusi2026lab5/internal/worker/backoff.go
T
2026-11-10 16:21:46 +03:00

46 lines
1.0 KiB
Go

package worker
import (
"crypto/sha256"
"encoding/binary"
"strconv"
"time"
)
// RetryDelay returns exponential backoff with deterministic per-job jitter in
// [0.5, 1.5). Determinism makes retries reproducible while still avoiding a
// synchronized retry wave across different jobs.
func RetryDelay(jobID string, nextAttempt int, base, maximum time.Duration) time.Duration {
if base <= 0 {
base = time.Millisecond
}
if maximum < base {
maximum = base
}
exponent := nextAttempt - 2
if exponent < 0 {
exponent = 0
}
delay := base
for index := 0; index < exponent && delay < maximum; index++ {
if delay > maximum/2 {
delay = maximum
break
}
delay *= 2
}
if delay > maximum {
delay = maximum
}
sum := sha256.Sum256([]byte(jobID + ":" + strconv.Itoa(nextAttempt)))
fraction := float64(binary.BigEndian.Uint64(sum[:8])) / float64(^uint64(0))
jittered := time.Duration(float64(delay) * (0.5 + fraction))
if jittered > maximum {
return maximum
}
if jittered < time.Millisecond {
return time.Millisecond
}
return jittered
}