@@ -60,13 +60,16 @@ import javax.inject.Inject
6060import javax.inject.Singleton
6161import kotlin.math.min
6262import kotlin.math.pow
63+ import kotlin.random.Random
6364import kotlin.time.Duration
6465import kotlin.time.Duration.Companion.minutes
6566import kotlin.time.Duration.Companion.seconds
6667
6768private const val SYNC_TIMEOUT_MS = 10_000L
6869private const val MAX_RETRY_ATTEMPTS = 5
6970private const val INITIAL_RETRY_DELAY_MS = 1000L
71+ private const val MAX_DELAY_MS = 30_000L
72+ private const val JITTER_PERCENTAGE = 0.25
7073
7174@Singleton
7275@Suppress(" LongParameterList" , " LargeClass" , " TooManyFunctions" )
@@ -204,7 +207,7 @@ class LightningRepo @Inject constructor(
204207 context = TAG
205208 )
206209
207- val retryDelay = calculateRetryDelay (retryAttempt)
210+ val retryDelay = calculateRetryDelayWithJitter (retryAttempt)
208211 delay(retryDelay)
209212
210213 return @withContext start(
@@ -271,7 +274,7 @@ class LightningRepo @Inject constructor(
271274
272275 _lightningState .update { it.copy(nodeLifecycleState = initialLifecycleState) }
273276
274- val retryDelay = calculateRetryDelay (retryAttempt)
277+ val retryDelay = calculateRetryDelayWithJitter (retryAttempt)
275278 delay(retryDelay)
276279
277280 return @withContext start(
@@ -313,14 +316,14 @@ class LightningRepo @Inject constructor(
313316 /* *
314317 * Calculates retry delay with exponential backoff and jitter
315318 */
316- private fun calculateRetryDelay (retryAttempt : Int ): Long {
319+ private fun calculateRetryDelayWithJitter (retryAttempt : Int ): Long {
317320 val baseDelay = INITIAL_RETRY_DELAY_MS
318321 val exponentialDelay = baseDelay * 2.0 .pow(retryAttempt.toDouble()).toLong()
319- val maxDelay = 30_000L // 30 seconds max
320- val delayWithCap = min(exponentialDelay, maxDelay)
322+ val delayWithCap = min(exponentialDelay, MAX_DELAY_MS )
323+
324+ val maxJitter = (delayWithCap * JITTER_PERCENTAGE ).toLong()
325+ val jitter = Random .nextLong(- maxJitter, maxJitter + 1 )
321326
322- // Add jitter (±25% of the delay)
323- val jitter = (delayWithCap * 0.25 * (Math .random() - 0.5 )).toLong()
324327 return delayWithCap + jitter
325328 }
326329
0 commit comments