Created
October 30, 2017 22:49
-
-
Save msanders/a9fa381ef9eade94bb81c5707f649bcc to your computer and use it in GitHub Desktop.
Exponential Backoff And Jitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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