Exponential backoff with jitter लागू करें
आप एक फ्लेकी थर्ड-पार्टी पेमेंट्स API के साथ इंटीग्रेट कर रहे हैं जो कभी-कभी ट्रांज़िएंट एरर लौटाती है. जब सर्विस पहले से जूझ रही हो, तब उसे बार-बार हिट करने से बचने के लिए, आप exponential backoff with full jitter वाला retry स्ट्रैटेजी लागू करेंगे, जिसमें प्रयासों के बीच इंतज़ार बढ़ेगा और रैंडमनेस जुड़ जाएगी ताकि क्लाइंट्स का "thundering herd" एक ही पल में दोबारा प्रयास न करे.
एक flaky_call(payload) फंक्शन उपलब्ध है: यह पहली 3 invocations पर TransientError के साथ फेल होता है, और 4th पर succeed करता है. time, random, और TransientError पहले से लोड हैं.
यह अभ्यास पाठ्यक्रम का हिस्सा है
AWS पर एप्लिकेशन डेवलप करना
अभ्यास निर्देश
tryब्लॉक के अंदर,payloadके साथflaky_callको कॉल करें और उसी का परिणाम रिटर्न करें.- इस प्रयास के लिए
baseऔर मौजूदाattemptकाउंट का उपयोग करके exponential cap निकालें. - full jitter लागू करने के लिए
random.uniform()से0औरcapके बीच एक रैंडम wait चुनें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
def retry_with_backoff(payload, max_attempts=5, base=0.2):
last_error = None
for attempt in range(max_attempts):
try:
# Try the call
return ____(payload)
except TransientError as err:
last_error = err
# Cap grows exponentially with each attempt
cap = ____ * (2 ** attempt)
# Pick a random wait between 0 and cap (full jitter)
wait = random.____(0, cap)
time.sleep(wait)
# All attempts failed; surface the last error
raise last_error
result = retry_with_backoff({"order_id": 42})
print(result)