Created
December 4, 2024 10:15
-
-
Save ludndev/22df6b7f61682a0a9d078d5121aaf7c3 to your computer and use it in GitHub Desktop.
Exponential Backoff with Golden Ration
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
import time | |
import random | |
# golden Ratio constant | |
phi = 1.6180339887 | |
def exponential_backoff_with_phi(max_retries=5, base_delay=1): | |
""" | |
Retries an operation with exponential backoff using the golden ratio (phi). | |
:param max_retries: Maximum number of retries. | |
:param base_delay: The initial delay in seconds (usually 1 second). | |
""" | |
retries = 0 | |
while retries < max_retries: | |
delay = base_delay * (phi ** retries) # exponential growth by golden ratio | |
# add jitter (randomness) to avoid retries being sync | |
jitter = random.uniform(0.5, 1.5) | |
delay *= jitter | |
# display delay and retry attempt | |
print(f"Retry {retries + 1}/{max_retries}, waiting for {delay:.2f} seconds...") | |
# wait before retrying | |
time.sleep(delay) | |
retries += 1 | |
print("Maximum retries reached.") | |
def main(): | |
# simulate retry logic | |
exponential_backoff_with_phi(max_retries=5, base_delay=1) | |
if __name__ == "__main__": | |
try: | |
main() | |
except KeyboardInterrupt: | |
print("Stopping program ...") | |
except Exception e: | |
print(f"Something went wrong. {e}") | |
finally: | |
quit() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment