0.3.1 • Published 8 months ago

@commenthol/exponential-backoff v0.3.1

Weekly downloads
-
License
MIT-0
Repository
gitlab
Last release
8 months ago

npm-badge types-badge ci-badge

@commenthol/exponential-backoff

Exponential backoff for failed Promises

  • Support for AbortSignal.
  • Pure ESM module with 0 dependencies.

Usage

npm i @commenthol/exponential-backoff

Signature

function backoff<T>(
  request: () => Promise<T>,
  options?: BackoffOptions
): Promise<T>

Example

Fetch from URL with exponential backoff retries for 50x responses and and early abort on timeout using AbortSignal.

import { backoff } from '@commenthol/exponential-backoff'

const timeout = 10e3
const url = 'https://httpbin.org/status/500'
const signal = AbortSignal.timeout(timeout)

const fetchRetryOn50x = async (url, init) => {
  const res = await fetch(url, init)
  if (res.status >= 500) {
    throw new Error(res.statusText)
  }
  return res
}

const res = await backoff(() => fetchRetryOn50x(url, { signal }), { signal })

Options

export interface BackoffOptions {
  /**
   * Maximum number of attempts
   * @default 10
   */
  maxAttempts?: number
  /**
   * Maximum interval between retries in ms
   * @default Infinity
   */
  maxInterval?: number
  /**
   * Interval for first retry in ms;
   * With defaults: maxAttempts = 10, this gives
   * max. duration = 100ms * 2^11 ≃ 20secs if promise rejects immediately
   * @default 100
   */
  initialInterval?: number
  /**
   * Coefficient used to calculate the next retry interval
   * @default 2
   */
  retryMultiple?: number
  /**
   * If `true` random jitter is applied to retry delay within
   * range [delay/2..delay]
   * @default false
   */
  jitter?: boolean
  /**
   * If `true` first request is delayed;
   * @default false
   */
  delayFirstAttempt?: boolean
  /**
   * abort signal e.g. from AbortController
   */
  signal?: AbortSignal
  /**
   * Hook called on every failure before retrying. If result resolves to `false` 
   * the retry is aborted.
   * @param err - error thrown by the promise
   * @param attempt - current attempt number
   * @returns `true` to retry, `false` to abort
   */
  retryHook?: (err: any, attempt: number) => boolean | Promise<boolean>
}

License

MIT-0 licensed

0.3.1

8 months ago

0.3.0

8 months ago

0.2.1

8 months ago

0.2.0

8 months ago