-
Notifications
You must be signed in to change notification settings - Fork 21
feat(retry): add exponential backoff for transient API failures #91
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
qorexdev
wants to merge
2
commits into
linearis-oss:main
Choose a base branch
from
qorexdev:feat/retry-exponential-backoff
base: main
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.
+151
−8
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| interface RetryOptions { | ||
| maxRetries?: number; | ||
| baseDelayMs?: number; | ||
| } | ||
|
|
||
| interface RetryableError { | ||
| response?: { | ||
| status?: number; | ||
| }; | ||
| } | ||
|
|
||
| export function isRetryable(error: unknown): boolean { | ||
| const err = error as RetryableError; | ||
| const status = err?.response?.status; | ||
| if (typeof status === "number") { | ||
| return status === 429 || (status >= 500 && status < 600); | ||
| } | ||
| // network-level errors (ECONNRESET, ETIMEDOUT, etc.) | ||
| if (error instanceof Error) { | ||
| const msg = error.message.toLowerCase(); | ||
| return ( | ||
| msg.includes("timed out") || | ||
| msg.includes("econnreset") || | ||
| msg.includes("network") | ||
| ); | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| export async function withRetry<T>( | ||
| fn: () => Promise<T>, | ||
| options?: RetryOptions, | ||
| ): Promise<T> { | ||
| const { maxRetries = 3, baseDelayMs = 500 } = options ?? {}; | ||
| for (let attempt = 0; attempt <= maxRetries; attempt++) { | ||
| try { | ||
| return await fn(); | ||
| } catch (error) { | ||
| if (attempt === maxRetries || !isRetryable(error)) throw error; | ||
| const delay = baseDelayMs * 2 ** attempt; | ||
| await new Promise<void>((r) => setTimeout(r, delay)); | ||
| } | ||
| } | ||
| // unreachable, but TypeScript needs it | ||
| throw new Error("withRetry: exhausted attempts"); | ||
| } |
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,73 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { isRetryable, withRetry } from "../../../src/common/retry.js"; | ||
|
|
||
| describe("isRetryable", () => { | ||
| it("returns true for 429", () => { | ||
| expect(isRetryable({ response: { status: 429 } })).toBe(true); | ||
| }); | ||
|
|
||
| it("returns true for 500", () => { | ||
| expect(isRetryable({ response: { status: 500 } })).toBe(true); | ||
| }); | ||
|
|
||
| it("returns true for 503", () => { | ||
| expect(isRetryable({ response: { status: 503 } })).toBe(true); | ||
| }); | ||
|
|
||
| it("returns false for 400", () => { | ||
| expect(isRetryable({ response: { status: 400 } })).toBe(false); | ||
| }); | ||
|
|
||
| it("returns false for 404", () => { | ||
| expect(isRetryable({ response: { status: 404 } })).toBe(false); | ||
| }); | ||
|
|
||
| it("returns false for auth errors", () => { | ||
| expect(isRetryable({ response: { status: 401 } })).toBe(false); | ||
| }); | ||
|
|
||
| it("returns true for timeout errors", () => { | ||
| expect(isRetryable(new Error("Request timed out"))).toBe(true); | ||
| }); | ||
|
|
||
| it("returns false for generic errors", () => { | ||
| expect(isRetryable(new Error("Entity not found"))).toBe(false); | ||
| }); | ||
| }); | ||
|
|
||
| describe("withRetry", () => { | ||
| it("returns result on first success", async () => { | ||
| const fn = vi.fn().mockResolvedValueOnce("ok"); | ||
| const result = await withRetry(fn, { baseDelayMs: 1 }); | ||
| expect(result).toBe("ok"); | ||
| expect(fn).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("retries on 429 and succeeds", async () => { | ||
| const fn = vi | ||
| .fn() | ||
| .mockRejectedValueOnce({ response: { status: 429 } }) | ||
| .mockResolvedValueOnce("ok"); | ||
| const result = await withRetry(fn, { maxRetries: 3, baseDelayMs: 1 }); | ||
| expect(result).toBe("ok"); | ||
| expect(fn).toHaveBeenCalledTimes(2); | ||
| }); | ||
|
|
||
| it("retries on 503 up to maxRetries then throws", async () => { | ||
| const err = { response: { status: 503 } }; | ||
| const fn = vi.fn().mockRejectedValue(err); | ||
| await expect( | ||
| withRetry(fn, { maxRetries: 2, baseDelayMs: 1 }), | ||
| ).rejects.toEqual(err); | ||
| expect(fn).toHaveBeenCalledTimes(3); // 1 initial + 2 retries | ||
| }); | ||
|
|
||
| it("does not retry non-retryable errors", async () => { | ||
| const err = new Error("Entity not found"); | ||
| const fn = vi.fn().mockRejectedValue(err); | ||
| await expect(withRetry(fn, { baseDelayMs: 1 })).rejects.toThrow( | ||
| "Entity not found", | ||
| ); | ||
| expect(fn).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
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.
The tests for
withRetryvalidate retry counts, but they don’t verify the exponential backoff timing (e.g., 500ms → 1s → 2s). Since backoff is a core requirement of this PR, consider adding a test with fake timers that asserts the scheduled delays (or at least the sequence ofsetTimeoutdurations) to ensure future changes don’t accidentally make the backoff linear or constant.