Created
November 21, 2025 15:07
-
-
Save opentechnologist/75d24241ddc67525d204bb670283a45a to your computer and use it in GitHub Desktop.
a simple exponential back-off implementation in python
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
| from time import sleep | |
| import random | |
| from exponential_backoff import ExponentialBackoff | |
| def demo(iterations=1000): | |
| backoff = ExponentialBackoff(initial=3, maximum=10) # sleeps between 3 to 10 seconds | |
| def get_next_item(): | |
| rand = random.random() | |
| return int(rand * 1e8) if rand > 0.8 else None # returns None 80% of the time. | |
| def handle(item): | |
| # Put business processing logic here. | |
| print('Item found: [%d]' % item) | |
| sleep(5) | |
| for i in range(iterations): | |
| item = get_next_item() | |
| if item is None: | |
| print('No item found: sleeping {%f} seconds' % backoff.seconds()) | |
| backoff.sleep() | |
| else: | |
| handle(item) | |
| backoff.reset() | |
| if __name__ == '__main__': | |
| demo() |
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
| from time import sleep | |
| class ExponentialBackoff(object): | |
| def __init__(self, initial=15, maximum=180, factor=1.3333): | |
| self.initial = float(initial) | |
| self.maximum = float(maximum) | |
| self.factor = float(factor) | |
| self.current = float(initial) | |
| def reset(self): | |
| self.current = self.initial | |
| def seconds(self): | |
| return self.current | |
| def sleep(self): | |
| sleep(self.current) | |
| self.current *= self.factor | |
| if self.current > self.maximum: | |
| self.current = self.maximum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment