Write your own retry decorator with exponential backoff and jitter.
AdvancedHands-onPython for DevOps
Answer
import functools
import random
import time
def retry(times=5, base=0.5, exceptions=(Exception,)):
def deco(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except exceptions as e:
if attempt == times:
raise
sleep = base * 2 ** (attempt - 1) + random.uniform(0, base)
print(f"{fn.__name__} failed ({e}); retry {attempt} in {sleep:.1f}s")
time.sleep(sleep)
return wrapper
return deco
@retry(times=4, exceptions=(ConnectionError, TimeoutError))
def fetch():
...
Key trick → Jitter stops many clients from retrying in lockstep and hammering a recovering service. Only retry specific, transient exceptions.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateParse a YAML file and print every container image in a multi-document Kubernetes manifest.IntermediateRun a shell command from Python, capture output, and fail properly on error.Intermediate