Bird
0
0

You want to implement retry logic that tries up to 4 times with increasing wait times: 1s, 2s, 4s, then stops. Which code snippet correctly implements this?

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

You want to implement retry logic that tries up to 4 times with increasing wait times: 1s, 2s, 4s, then stops. Which code snippet correctly implements this?

Option A:
for i in range(3):
    response = call_api()
    if response.ok:
        break
    time.sleep(2 ** i)

Option B:
for i in range(1, 5):
    response = call_api()
    if response.ok:
        break
    time.sleep(i)

Option C:
for i in range(4):
    response = call_api()
    if response.ok:
        break
    time.sleep(i)

Option D:
for i in range(4):
    response = call_api()
    if response.ok:
        break
    time.sleep(2 * i)
AOption A
BOption B
COption C
DOption D
Step-by-Step Solution
Solution:
  1. Step 1: Understand wait time pattern

    Wait times should double each retry: 1s, 2s, 4s, then stop after 4 tries.
  2. Step 2: Check the options' sleep times

    The code with time.sleep(2 ** i) and range(3) gives waits of 1s (i=0), 2s (i=1), 4s (i=2). This matches exponential backoff for up to 4 tries (3 retries after initial call).
  3. Step 3: Compare distractors

    The range(1,5) with time.sleep(i) uses linear 1,2,3,4s. range(4) with time.sleep(i) uses 0,1,2,3s. time.sleep(2 * i) uses 0,2,4,6s. None match doubling from 1s.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Exponential backoff uses 2 ** i [OK]
Quick Trick: Use 2 ** i for doubling wait times [OK]
Common Mistakes:
MISTAKES
  • Starting wait time at 0 seconds
  • Using linear instead of exponential waits
  • Not stopping after max retries

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes