-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use exponential backoff for Transaction#execute
- Loading branch information
Showing
2 changed files
with
61 additions
and
45 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import Foundation | ||
|
||
enum Backoff { | ||
static let receiptInitialDelay: UInt32 = 1 | ||
static let receiptRetryDelay: TimeInterval = 0.5 | ||
|
||
static func getDelayUs(startTime: Date, attempt: UInt8) -> UInt32? { | ||
// exponential backoff algorithm: | ||
// next delay is some constant * rand(0, 2 ** attempt - 1) | ||
let delay = Backoff.receiptRetryDelay | ||
* Double.random(in: 0..<Double((1 << attempt))) | ||
|
||
// if the next delay will put us past the valid duration we should stop trying | ||
let validDuration: TimeInterval = 2 * 60 | ||
let expireInstant = startTime.addingTimeInterval(validDuration) | ||
if Date(timeIntervalSinceNow: delay).compare(expireInstant) == .orderedDescending { | ||
return nil | ||
} | ||
|
||
// converting from seconds to microseconds | ||
return UInt32(delay * 1000000) | ||
} | ||
} |
This file contains 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