Skip to content

Commit

Permalink
Add retry option to configure backoff limit
Browse files Browse the repository at this point in the history
The default backoff function is exponential, so after a couple of retries the delay will become very large.
In case you are polling an api, you want at least that there is an upper limit to this delay, for example 1000ms.
  • Loading branch information
Frank van Wijk committed Sep 14, 2022
1 parent da40323 commit b261374
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion source/core/Ky.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ export class Ky {
}

const BACKOFF_FACTOR = 0.3;
return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
return Math.min(this._options.retry.backoffLimit, BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000);
}

return 0;
Expand Down
12 changes: 12 additions & 0 deletions source/types/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,16 @@ export interface RetryOptions {
@default Infinity
*/
maxRetryAfter?: number;

/**
The upper limit of the `computedValue`.
By default, the computedValue is calculated in the following way:
0.3 * (2 ** (attemptCount - 1)) * 1000
The delay increases exponentially.
In order to prevent this, you can set this value to a fixed value, such as 1000.
*/
backoffLimit?: number;
}
1 change: 1 addition & 0 deletions source/utils/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const defaultRetryOptions: Required<RetryOptions> = {
statusCodes: retryStatusCodes,
afterStatusCodes: retryAfterStatusCodes,
maxRetryAfter: Number.POSITIVE_INFINITY,
backoffLimit: Number.POSITIVE_INFINITY,
};

export const normalizeRetryOptions = (retry: number | RetryOptions = {}): Required<RetryOptions> => {
Expand Down

0 comments on commit b261374

Please sign in to comment.