Skip to content

Instantly share code, notes, and snippets.

@rajrao
Created October 27, 2023 18:43
Show Gist options
  • Save rajrao/647b299bd4b20974c110d2a336c9d522 to your computer and use it in GitHub Desktop.
Save rajrao/647b299bd4b20974c110d2a336c9d522 to your computer and use it in GitHub Desktop.
def get_backoff_w_jitter(attempt: int, max_backoff: int = 20) -> int:
"""returns the wait time for a backoff for attempt # attempt
algorithm: truncated binary exponential backoff with jitter
src: https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html
Arguments:
attempt -- the attempt # for calculating the backoff. a number >= 0
Returns:
the backoff amount (usually used as seconds to sleep)
"""
import random
b = random.random()
r = 2
backoff_seconds = min(b*(r**attempt), max_backoff)
return backoff_seconds
for a in range(0, 4):
backoff_seconds = get_backoff_w_jitter(a)
print(f"attempt: {a}: sleep: {backoff_seconds}")
@rajrao
Copy link
Author

rajrao commented Oct 31, 2023

What the sleep times look like over 10 attempts (5 runs).

You can see that in the beginning the sleep times are small, approaching the max value of 30 with more attempts and jitter causing variabilty even at higher order runs:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment