Skip to content

Instantly share code, notes, and snippets.

@rzane
Last active May 9, 2018 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rzane/188dc1ec75a43df98fb9ead5538a9206 to your computer and use it in GitHub Desktop.
Save rzane/188dc1ec75a43df98fb9ead5538a9206 to your computer and use it in GitHub Desktop.
Exponential backoff

Usage

import Backoff from './Backoff';
import apisauce from 'apisauce';

const backoff = Backoff.create({
  shouldBackoff(response) {
    return response.status === 429;
  }
});

const client = apisauce.create({
  baseURL: 'https://google.com'
});

const response = await backoff.run(() => client.get('/'));
const create = ({
shouldBackoff,
factor = 5,
maxDelay = 32000,
maxAttempts = 20
}) => {
const backoff = attempt => {
const randomMs = Math.floor(Math.random() * 1000);
const exponential = Math.pow(factor, attempt) + randomMs;
const delay = Math.min(exponential, maxDelay);
return new Promise(resolve => setTimeout(resolve, delay));
};
const run = async request => {
let attempts = 0;
while (attempts <= maxAttempts) {
const response = await request();
if (!shouldBackoff(response)) {
return response;
}
await backoff(++attempts);
}
throw new Error("Backoff reached maximum attempts");
};
return {
run
};
};
export default {
create
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment