Make jitter subtract only

This commit is contained in:
2026-07-13 22:07:40 +10:00
parent f346a1fc4f
commit bce4c1552e
2 changed files with 18 additions and 17 deletions

View File

@@ -5,7 +5,7 @@ import { ExponentialBackoffMaxRetriesHitError } from './errors.ts';
*
* The delay increases exponentially with each attempt, up to a maximum delay.
*
* The jitter is a random amount of time added to the delay to prevent thundering herd problems.
* The jitter is a random amount of time subtracted from the delay to prevent thundering herd problems.
*
* The growth rate is the factor by which the delay increases with each attempt.
*/
@@ -51,7 +51,7 @@ export class ExponentialBackoff {
* @param options.maxAttempts - Maximum number of attempts; `0` retries indefinitely. Default: `10`.
* @param options.baseDelay - Delay used as the basis for the first retry. Default: `1_000` ms.
* @param options.growthRate - Multiplier applied to the delay after each attempt. Default: `2`.
* @param options.jitter - Random proportional variation applied to each delay. Default: `0.1`.
* @param options.jitter - Maximum proportional reduction subtracted from each delay (01). Default: `0.1`.
*/
constructor(options: Partial<ExponentialBackoffOptions> = {}) {
this.options = {
@@ -114,8 +114,6 @@ export class ExponentialBackoff {
/**
* Calculate the delay before we should attempt to retry
*
* NOTE: The maximum delay is (maxDelay * (1 + jitter))
*
* @param attempt
* @returns The time in milliseconds before another attempt should be made
*/
@@ -129,14 +127,14 @@ export class ExponentialBackoff {
// Cap the delay to the maximum. Do this before the jitter so jitter does not become larger than delay
const cappedDelay = Math.min(rawDelay, options.maxDelay);
// Get the jitter direction. This will be between -1 and 1
const jitterDirection = 2 * Math.random() - 1;
// Get a random number for the amount to "jitter" the delay by
const jitterAmount = Math.random();
// Calculate the jitter
const jitter = jitterDirection * options.jitter * cappedDelay;
const jitter = jitterAmount * options.jitter * cappedDelay;
// Add the jitter to the delay
return cappedDelay + jitter;
// Subtract the jitter from the delay
return cappedDelay - jitter;
}
}
@@ -163,7 +161,7 @@ export type ExponentialBackoffOptions = {
growthRate: number;
/**
* The jitter of the delay as a percentage of growthRate
* The jitter of the delay as a percentage of growthRate. The jitter is subtracted from the delay.
*/
jitter: number;
};