Skip to content

Commit b364361

Browse files
authored
Add exponential backoff to requestWithRetry (#145)
* Add exponential backoff to requestWithRetry - Adds a retryCount and increases the wait time between calls - Adds max wait of 30 seconds - Ends after 10 retry attempts * Adjust to not error out after 10 retries, up wait to 60s
1 parent 1acb720 commit b364361

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

packages/homebridge-hatch-baby-rest/rest-client.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ export function apiPath(path: string) {
1919

2020
export async function requestWithRetry<T>(
2121
options: RequestInit & { url: string; json?: object },
22+
retryCount: number = 1,
2223
): Promise<T> {
2324
try {
2425
const optionsWithDefaults: RequestInit = {
@@ -50,11 +51,16 @@ export async function requestWithRetry<T>(
5051
return responseJson as T
5152
} catch (e: any) {
5253
if (!e.response) {
54+
55+
// Exponential backoff doubled each retry
56+
// Cap at 60 seconds to avoid extremely long waits
57+
const backoffTime = Math.min(1000 * Math.pow(2, retryCount), 60000)
58+
5359
logError(
54-
`Failed to reach Hatch Baby server at ${options.url}. ${e.message}. Trying again in 5 seconds...`,
60+
`Failed to reach Hatch Baby server at ${options.url}. ${e.message}. Trying again in ${backoffTime / 1000} seconds... (Attempt ${retryCount + 1})`,
5561
)
56-
await delay(5000)
57-
return requestWithRetry(options)
62+
await delay(backoffTime)
63+
return requestWithRetry(options, retryCount + 1)
5864
}
5965

6066
throw e

0 commit comments

Comments
 (0)