Skip to content

Cookbook: retry

Eugene Lazutkin edited this page Nov 27, 2019 · 5 revisions

In order to use io.retry make sure that it is enabled:

// optional:
// set custom properties (can be done at any time)
io.retry.initDelay = 100; // ms (the default: 50)
// defaults are sane, so you are unlikely to break anything

// activate the package
io.retry.attach();

See How to include for more details. See retry for the full documentation.

Retry any failures

The snippet below will retry all failed requests up to 5 times:

const req = io.get({
  url: '/abc',
  retries: 5
});

Retry 5XX

The snippet below will retry all requests failed with 5XX up to 3 times:

const req = io.get({
  url: '/abc',
  retries: 3,
  continueRetries: result => result.xhr.status >= 500
});

Retry 502, 503, 504 without limits

Imagine that our server is being updated and while it restarts a deployment system returns 502 (bad gateway), 503 (service unavailable), or 504 (gateway timeout). We want to skip those codes retrying until our service returns something useful, like 500:

const req = io.get({
  url: '/abc',
  retries: 0, // important!
  continueRetries: result => result.xhr.status >= 502 && result.xhr.status <= 504
});

Implement polling

Imagine that we start some asynchronous process which we want to poll at some endpoint. That endpoint takes a process id and returns 204 if the process is still running or 200 with a payload which describes how it has finished:

const req = io.get({
  url: '/status',
  query: {pId: 12345},
  retries: 0, // no limit
  continueRetries: result => result.xhr.status == 204
});

Exponential backoff and jitter retries

Let's implement exponential backoff and jitter recommended by AWS:

const CAP = 5000; // Delays should be less than 5 seconds

io.retry.initDelay = 10; // we start with 10 milliseconds
io.retry.nextDelay = delay => {
  const jitter = delay * Math.random();
  return Math.min(CAP, delay + jitter);
};

The same algorithm implemented for a specific request:

const req = io.get({
  url: '/abc',
  retries: 3,
  initDelay: 10,
  nextDelay(delay) {
    const jitter = delay * Math.random();
    return Math.min(CAP, delay + jitter);
  }
});
Clone this wiki locally