-
Notifications
You must be signed in to change notification settings - Fork 33
[BR-1794]: Add rate limit retry mechanism with exponential backoff #1834
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
terrerox
wants to merge
5
commits into
master
Choose a base branch
from
feature/retry-with-backoff
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+273
−31
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
31e89e9
feature: Add rate limit retry mechanism with exponential backoff
terrerox 22e0f9c
refactor: Improve rate limit retry mechanism with user feedback
terrerox cd0f3ad
refactor: Simplify rate limit retry mechanism and improve toast persi…
terrerox 6b7760c
refactor: Show rate limit notification only once per session
terrerox 34d5f3b
refactor: Move rate limit notification logic to UI layer
terrerox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
| import { retryWithBackoff } from './retry-with-rate-limit'; | ||
| import * as timeUtils from 'utils/timeUtils'; | ||
|
|
||
| vi.mock('utils/timeUtils', () => ({ | ||
| wait: vi.fn(() => Promise.resolve()), | ||
| })); | ||
|
|
||
| const createRateLimitError = (resetDelay: string, additionalHeaders?: Record<string, string>) => ({ | ||
| status: 429, | ||
| headers: { 'x-internxt-ratelimit-reset': resetDelay, ...additionalHeaders }, | ||
| }); | ||
|
|
||
| const createRateLimitMock = (resetDelay: string, additionalHeaders?: Record<string, string>) => | ||
| vi.fn().mockRejectedValueOnce(createRateLimitError(resetDelay, additionalHeaders)).mockResolvedValueOnce('success'); | ||
|
|
||
| describe('retryWithBackoff', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('when function succeeds immediately then returns result without retry', async () => { | ||
| const mockFn = vi.fn().mockResolvedValue('success'); | ||
|
|
||
| const result = await retryWithBackoff(mockFn); | ||
|
|
||
| expect(result).toBe('success'); | ||
| expect(mockFn).toHaveBeenCalledTimes(1); | ||
| expect(timeUtils.wait).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('when rate limited then retries with delay from headers', async () => { | ||
| const mockFn = createRateLimitMock('5000'); | ||
|
|
||
| const result = await retryWithBackoff(mockFn); | ||
|
|
||
| expect(result).toBe('success'); | ||
| expect(mockFn).toHaveBeenCalledTimes(2); | ||
| expect(timeUtils.wait).toHaveBeenCalledWith(5000); | ||
| }); | ||
|
|
||
| it('when error is not rate limit then throws immediately without retry', async () => { | ||
| const mockFn = vi.fn().mockRejectedValue({ status: 500, message: 'Internal Server Error' }); | ||
|
|
||
| await expect(retryWithBackoff(mockFn)).rejects.toEqual({ status: 500, message: 'Internal Server Error' }); | ||
|
|
||
| expect(mockFn).toHaveBeenCalledTimes(1); | ||
| expect(timeUtils.wait).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('when rate limited multiple times then calls onRetry for each retry', async () => { | ||
| const error = createRateLimitError('1000'); | ||
| const mockFn = vi.fn().mockRejectedValueOnce(error).mockRejectedValueOnce(error).mockResolvedValueOnce('success'); | ||
|
|
||
| const onRetry = vi.fn(); | ||
|
|
||
| const result = await retryWithBackoff(mockFn, { onRetry }); | ||
|
|
||
| expect(result).toBe('success'); | ||
| expect(mockFn).toHaveBeenCalledTimes(3); | ||
| expect(onRetry).toHaveBeenCalledTimes(2); | ||
| expect(onRetry).toHaveBeenNthCalledWith(1, 1, 1000); | ||
| expect(onRetry).toHaveBeenNthCalledWith(2, 2, 1000); | ||
| }); | ||
|
|
||
| it('when headers missing or invalid then throws error', async () => { | ||
| const testCases = [ | ||
| { status: 429 }, | ||
| { status: 429, headers: {} }, | ||
| { status: 429, headers: { 'x-internxt-ratelimit-reset': 'invalid' } }, | ||
| ]; | ||
|
|
||
| for (const error of testCases) { | ||
| const mockFn = vi.fn().mockRejectedValue(error); | ||
| await expect(retryWithBackoff(mockFn)).rejects.toEqual(error); | ||
| expect(mockFn).toHaveBeenCalledTimes(1); | ||
| vi.clearAllMocks(); | ||
| } | ||
| }); | ||
|
|
||
| it('when max retries exceeded then throws original error', async () => { | ||
| const error = new Error('Rate limit exceeded'); | ||
| Object.assign(error, { status: 429, headers: { 'x-internxt-ratelimit-reset': '1000' } }); | ||
| const mockFn = vi.fn().mockRejectedValue(error); | ||
|
|
||
| await expect(retryWithBackoff(mockFn, { maxRetries: 2 })).rejects.toThrow('Rate limit exceeded'); | ||
|
|
||
| expect(mockFn).toHaveBeenCalledTimes(3); | ||
| expect(timeUtils.wait).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| it('when error is not an object then throws immediately without retry', async () => { | ||
| const testCases = ['string error', null]; | ||
|
|
||
| for (const error of testCases) { | ||
| const mockFn = vi.fn().mockRejectedValue(error); | ||
| await expect(retryWithBackoff(mockFn)).rejects.toBe(error); | ||
| expect(mockFn).toHaveBeenCalledTimes(1); | ||
| vi.clearAllMocks(); | ||
| } | ||
|
|
||
| expect(timeUtils.wait).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { wait } from 'utils/timeUtils'; | ||
| import { HTTP_CODES } from 'app/core/constants'; | ||
|
|
||
| export interface RetryOptions { | ||
| maxRetries?: number; | ||
| onRetry?: (attempt: number, delay: number) => void; | ||
| } | ||
|
|
||
| interface ErrorWithStatus { | ||
| status?: number; | ||
| headers?: Record<string, string>; | ||
| } | ||
|
|
||
| const isErrorWithStatus = (error: unknown): error is ErrorWithStatus => { | ||
| return typeof error === 'object' && error !== null; | ||
| }; | ||
|
|
||
| const isRateLimitError = (error: unknown): boolean => { | ||
| if (!isErrorWithStatus(error)) { | ||
| return false; | ||
| } | ||
| return error.status === HTTP_CODES.TOO_MANY_REQUESTS; | ||
| }; | ||
|
|
||
| const extractRetryAfter = (error: ErrorWithStatus): number | undefined => { | ||
| const headers = error.headers; | ||
CandelR marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const resetHeader = headers?.['x-internxt-ratelimit-reset']; | ||
| if (!resetHeader) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const resetValueMs = Number.parseInt(resetHeader, 10); | ||
| if (Number.isNaN(resetValueMs)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return resetValueMs; | ||
| }; | ||
|
|
||
| /** | ||
| * Retries a function when it encounters a rate limit error (429). | ||
| * Uses the retry-after value from the x-internxt-ratelimit-reset header to wait before retrying. | ||
| * | ||
| * @param fn - The async function to execute with retry logic | ||
| * @param options - Configuration options for retry behavior | ||
| * @param options.maxRetries - Maximum number of retry attempts (default: 5) | ||
| * @param options.onRetry - Optional callback invoked before each retry with attempt number and retry after value | ||
| * @returns The result of the function if successful | ||
| * @throws The original error if it's not a rate limit error, if max retries exceeded, or if rate limit headers are missing | ||
| */ | ||
| export const retryWithBackoff = async <T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> => { | ||
| const opts = { | ||
| maxRetries: 5, | ||
| onRetry: () => {}, | ||
| ...options, | ||
| }; | ||
|
|
||
| for (let attempt = 0; attempt < opts.maxRetries; attempt++) { | ||
| try { | ||
| return await fn(); | ||
| } catch (error: unknown) { | ||
| if (!isRateLimitError(error)) { | ||
| throw error; | ||
| } | ||
|
|
||
| const retryAfter = extractRetryAfter(error as ErrorWithStatus); | ||
|
|
||
| if (!retryAfter) { | ||
| throw error; | ||
| } | ||
|
|
||
| opts.onRetry(attempt + 1, retryAfter); | ||
|
|
||
| await wait(retryAfter); | ||
| } | ||
| } | ||
|
|
||
| return await fn(); | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems that here is missing
error-deleting-linkstranslation, can you add it? :)