Skip to content

Instantly share code, notes, and snippets.

@msanders
Created October 30, 2017 22:49
Show Gist options
  • Save msanders/a9fa381ef9eade94bb81c5707f649bcc to your computer and use it in GitHub Desktop.
Save msanders/a9fa381ef9eade94bb81c5707f649bcc to your computer and use it in GitHub Desktop.
Exponential Backoff And Jitter
extension CountableClosedRange {
var randomElement: Element {
let distance = self.distance(from: startIndex, to: endIndex)
let offset = arc4random_uniform(UInt32(distance))
return self[index(startIndex, offsetBy: Bound.Stride(offset))]
}
}
enum Random {
enum Backoff {
// From https://www.awsarchitectureblog.com/2015/03/backoff.html
static func fullJitter(cap: Int, attempt: Int) -> Int {
precondition(cap >= 0)
precondition(attempt >= 0)
return (0...Int(min(Double(cap), pow(2, Double(attempt))))).randomElement
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment