When interacting with APIs, you may encounter various error responses, one of the most common being the 429 Too Many Requests
error. This error indicates that the client has sent too many requests in a given amount of time, and it’s a signal to slow down. Handling this error gracefully is crucial for maintaining a stable and efficient application. In this article, we will explore three practical examples of retrying API calls after receiving a 429 error.
In this example, we will implement an exponential backoff strategy to handle a 429 Too Many Requests
error when calling a third-party API for user data.
When our application makes requests to the API, it may hit the rate limit. Instead of retrying immediately, we will wait progressively longer periods with each failed attempt. This approach helps reduce the load on the API server and increases the chances of a successful request on subsequent attempts.
import time
import requests
url = 'https://api.example.com/user/data'
max_retries = 5
retry_count = 0
while retry_count < max_retries:
response = requests.get(url)
if response.status_code == 429:
# Calculate wait time using exponential backoff
wait_time = 2 ** retry_count
print(f'Received 429. Retrying in {wait_time} seconds...')
time.sleep(wait_time)
retry_count += 1
else:
# Successful response
print('Data retrieved successfully:', response.json())
break
else:
print('Max retries reached. Exiting.')
In this example, we will implement a fixed delay with random jitter to retry API calls after encountering a 429 Too Many Requests
error. This approach adds a random delay to each retry, which can help prevent a