Consider this pseudocode for retrying a REST API call up to 3 times on failure. What will be the final output if the API fails twice and succeeds on the third try?
attempts = 0 max_attempts = 3 success = False while attempts < max_attempts and not success: attempts += 1 if attempts < 3: print(f"Attempt {attempts}: Failed") else: print(f"Attempt {attempts}: Success") success = True if success: print("Result: Success") else: print("Result: Failure")
Look at how the loop increments attempts and when it sets success to True.
The loop tries up to 3 times. The first two attempts print 'Failed'. The third attempt prints 'Success' and sets success to True, so the final print is 'Result: Success'.
When implementing retry logic for REST API calls, which HTTP status code is generally appropriate to trigger a retry?
Think about server errors vs client errors.
500 Internal Server Error indicates a temporary server problem, so retrying might succeed later. 404 and 401 are client errors and usually should not be retried.
Examine the following retry code snippet. Why does it cause an infinite loop?
max_retries = 3 retry_count = 0 success = False while not success: try: # simulate API call if retry_count < max_retries: raise Exception("API failure") else: success = True except Exception as e: print(f"Retry {retry_count}: {e}")
Check if the retry_count changes inside the loop.
The variable retry_count is never increased, so the condition retry_count < max_retries is always true, causing the loop to never exit.
Consider this Python decorator for retrying a function. What error will it raise when used?
def retry(func): def wrapper(*args, **kwargs): for i in range(3): try: return func(*args, **kwargs) except Exception: pass return wrapper @retry def fail_once(): fail_once.counter += 1 if fail_once.counter < 2: raise Exception("Fail") return "Success" fail_once.counter = 0 print(fail_once())
Look at what the decorator returns after retries fail.
The decorator returns the wrapper function itself after retries fail, causing infinite recursion when called again, leading to RecursionError.
Given this pseudocode implementing exponential backoff retry for a REST API call, how many times will the API be called before the function returns?
def call_api_with_retry(): max_attempts = 4 delay = 1 for attempt in range(1, max_attempts + 1): response = api_call() if response == 'success': return attempt else: sleep(delay) delay *= 2 return max_attempts # Assume api_call() returns 'fail' for first 3 calls, then 'success' on 4th call.
Count how many times the loop runs until success.
The API fails 3 times, then succeeds on the 4th call. The loop runs 4 times, so the API is called 4 times.