Respect Retry-After header when available from 429 responses (#1182)

* 🩹 remove dead code for exponential backoff

This has been replaced by the withExponentialBackoff helper

* 🩹 respect Retry-After header when available
This commit is contained in:
Nejc Habjan 2024-04-25 00:53:18 +02:00 • committed by GitHub
parent 4bd76bd809
commit f616ae68bb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 4 additions and 24 deletions

View file

@ -1,23 +0,0 @@
export const fetchWithExponentialBackoff = async (
url: string,
options: RequestInit,
retries: number = 5,
delay: number = 1000,
): Promise<Response> => {
try {
const response = await fetch(url, options);
if (!response.ok && response.status === 429 && retries > 0) {
// Wait for delay milliseconds and retry
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
}
return response;
} catch (error) {
if (retries > 0) {
// Wait for delay milliseconds and retry
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
}
throw error;
}
};

View file

@ -2,6 +2,8 @@ interface APIError extends Error {
response?: Response;
}
const RETRY_AFTER_HEADER = "Retry-After";
const withExponentialBackoff = async <T>(
apiCall: () => Promise<T>,
maxRetries = 5,
@ -16,7 +18,8 @@ const withExponentialBackoff = async <T>(
(error as APIError).response?.status === 429 &&
attempt < maxRetries - 1
) {
const delay = initialDelaySeconds * 2 ** attempt;
const retryAfter = (error as APIError).response?.headers.get(RETRY_AFTER_HEADER);
const delay = retryAfter ? parseInt(retryAfter, 10) : initialDelaySeconds * 2 ** attempt;
console.log(
`Hit rate limit. Retrying in ${delay} seconds (attempt ${
attempt + 1