From e757f6670802b42aa55383abda7dc5a36f6fd912 Mon Sep 17 00:00:00 2001 From: Ajay Subramanya Date: Mon, 8 Apr 2024 21:49:14 -0500 Subject: [PATCH] added jitter to retry after --- Sources/KlaviyoSwift/APIRequestErrorHandling.swift | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Sources/KlaviyoSwift/APIRequestErrorHandling.swift b/Sources/KlaviyoSwift/APIRequestErrorHandling.swift index f055e050..8a465c64 100644 --- a/Sources/KlaviyoSwift/APIRequestErrorHandling.swift +++ b/Sources/KlaviyoSwift/APIRequestErrorHandling.swift @@ -33,10 +33,9 @@ enum InvalidField: Equatable { } } -private func getDelaySeconds(for count: Int) -> Int { - let delay = Int(pow(2.0, Double(count))) +private func addJitter(to value: Int) -> Int { let jitter = environment.randomInt() - return min(delay + jitter, ErrorHandlingConstants.maxBackoff) + return value + jitter } private func parseError(_ data: Data) -> [InvalidField]? { @@ -112,7 +111,9 @@ func handleRequestError( case let .retryWithBackoff(requestCount, totalCount, _): requestRetryCount = requestCount + 1 totalRetryCount = totalCount + 1 - nextBackoff = retryAfter ?? getDelaySeconds(for: totalRetryCount) + let exponentialBackOff = Int(pow(2.0, Double(totalRetryCount))) + + nextBackoff = addJitter(to: retryAfter ?? exponentialBackOff) } return .requestFailed( request, .retryWithBackoff(