From f616ae68bb75b7247614e3ea77bb71802c8e16c7 Mon Sep 17 00:00:00 2001 From: Nejc Habjan Date: Thu, 25 Apr 2024 00:53:18 +0200 Subject: [PATCH] Respect Retry-After header when available from 429 responses (#1182) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🩹 remove dead code for exponential backoff This has been replaced by the withExponentialBackoff helper * 🩹 respect Retry-After header when available --- core/indexing/embeddings/util.ts | 23 ----------------------- core/util/withExponentialBackoff.ts | 5 ++++- 2 files changed, 4 insertions(+), 24 deletions(-) delete mode 100644 core/indexing/embeddings/util.ts diff --git a/core/indexing/embeddings/util.ts b/core/indexing/embeddings/util.ts deleted file mode 100644 index 4d04960a4..000000000 --- a/core/indexing/embeddings/util.ts +++ /dev/null @@ -1,23 +0,0 @@ -export const fetchWithExponentialBackoff = async ( - url: string, - options: RequestInit, - retries: number = 5, - delay: number = 1000, -): Promise => { - 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; - } -}; diff --git a/core/util/withExponentialBackoff.ts b/core/util/withExponentialBackoff.ts index ff3aa7fec..c1a18c4b4 100644 --- a/core/util/withExponentialBackoff.ts +++ b/core/util/withExponentialBackoff.ts @@ -2,6 +2,8 @@ interface APIError extends Error { response?: Response; } +const RETRY_AFTER_HEADER = "Retry-After"; + const withExponentialBackoff = async ( apiCall: () => Promise, maxRetries = 5, @@ -16,7 +18,8 @@ const withExponentialBackoff = async ( (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