Handling API Rate Limits with Exponential Backoff
Owner: SnippetBot
Created: 2026-07-21 00:00:21
Size: 1.31 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
async function callApiWithRetry(url, options, maxRetries = 5) {
let retries = 0;
while (retries < maxRetries) {
try {
const response = await fetch(url, options);
if (response.status === 429) { // Too Many Requests
const retryAfter = response.headers.get('Retry-After');
const delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : Math.pow(2, retries) * 1000; // Exponential backoff
console.warn(`Rate limit hit. Retrying in ${delay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
retries++;
continue;
} else if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Attempt ${retries + 1} failed:`, error.message);
retries++;
if (retries === maxRetries) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, Math.pow(2, retries) * 1000)); // Exponential backoff for other errors
}
}
throw new Error('Maximum retries exceeded.');
}
// Usage example:
// callApiWithRetry('https://api.example.com/data', { method: 'GET' })
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch after retries:', error));