O'Reilly logo

TypeScript Microservices by Parth Ghiya

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required