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('/'));
Last active
May 9, 2018 18:11
-
-
Save rzane/188dc1ec75a43df98fb9ead5538a9206 to your computer and use it in GitHub Desktop.
Exponential backoff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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