Bird
0
0

You want to implement exponential backoff retry for a REST API call in Python. Which approach correctly applies this?

hard📝 Application Q8 of 15
Rest API - Webhooks and Events

You want to implement exponential backoff retry for a REST API call in Python. Which approach correctly applies this?

import time

for i in range(4):
    response = requests.get('https://api.example.com')
    if response.status_code == 200:
        print('Success')
        break
    else:
        time.sleep(2 ** i)
else:
    print('Failed after retries')
AThis code will cause a syntax error due to else after for
BThis code correctly waits longer after each failed attempt using exponential backoff
CThis code does not retry on failure
DThis code waits the same amount of time after each retry
Step-by-Step Solution
Solution:
  1. Step 1: Understand exponential backoff

    Exponential backoff means waiting longer after each failure, here time.sleep(2 ** i) doubles wait time each retry.
  2. Step 2: Check code correctness

    Code retries 4 times, breaks on success, else after for runs if loop completes without break, no syntax error.
  3. Final Answer:

    This code correctly waits longer after each failed attempt using exponential backoff -> Option B
  4. Quick Check:

    Exponential backoff = increasing wait times [OK]
Quick Trick: Use time.sleep(2 ** attempt) for exponential backoff [OK]
Common Mistakes:
MISTAKES
  • Using fixed sleep time instead of exponential
  • Misunderstanding else after for loop
  • Not breaking loop on success

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes