Skip to content

Instantly share code, notes, and snippets.

@ludndev
Created December 4, 2024 10:15
Show Gist options
  • Save ludndev/22df6b7f61682a0a9d078d5121aaf7c3 to your computer and use it in GitHub Desktop.
Save ludndev/22df6b7f61682a0a9d078d5121aaf7c3 to your computer and use it in GitHub Desktop.
Exponential Backoff with Golden Ration
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