Retrying failed requests

Often, we add back safe or retry requests in our system to make sure that if the service returns errors, we can retry the service if it is down for some time. In this sample, we have used an async/await pattern efficiently as an exponential retry parameter, that is, retry after 1, 2, 4, 8, and 16 seconds. A working example can be found in retry_failed_req.ts in a source code:

wait(timeout: number){
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, timeout)
})
}
async requestWithRetry(url: string){
const MAX_RETRIES = 10;
for (let i = 0; i <= MAX_RETRIES; i++) {
try { return await axios.get(url); }
catch (err) {
const timeout = Math.pow(2, i);
console.log('Waiting', timeout, 'ms');
await this.wait(timeout);
console.log('Retrying', err.message, i);
}
}
}

You will see output like the following:

Retrying request exponentially