Skip to main content

Angular 14- Http Call with Retry

 

What is retry design pattern?

The retry pattern is a design pattern that can be used to handle errors and transient failures in a robust and fault-tolerant way. The basic idea behind the retry pattern is to automatically retry an operation in case of failure, with the hope that the operation will succeed on the next attempt.

The retry pattern typically involves the following steps:

  • Attempt to perform the operation.
  • If the operation fails, wait for a period of time before retrying.
  • Retry the operation.
  • If the operation still fails, increase the wait time before the next retry, or retry a fixed number of times before giving up.

The retry pattern can be implemented in various ways, such as using a loop with a fixed number of iterations or using a backoff algorithm that increases the wait time between retries exponentially.

The retry pattern can be useful in situations where the cause of the failure is transient, such as a temporary network outage or a temporary resource shortage. By retrying the operation, the system can automatically recover from these types of failures without the need for human intervention.


However, it's important to use the retry pattern carefully and with consideration to the specific use case. If a failure is likely to be permanent and not recoverable, retrying the operation will not be useful. Additionally, retrying too many times can cause additional load on the system and can also lead to an infinite loop

Here is an example of how you can retry an HTTP call in Angular 14 using the retryWhen operator from the rxjs library:


import { HttpClient } from '@angular/common/http';
import { retryWhen, delay, take } from 'rxjs/operators';

export class MyService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get('https://my-api.com/data').pipe(
      retryWhen(errors =>
        errors.pipe(
          delay(1000), // wait for 1 second before retrying
          take(5), // retry at most 5 times
          // if the error still persists after 5 retries, throw the error
          finalize(() => console.log("Retried 5 times, throwing error"))
        )
      )
    );
  }
}


In this example, the getData method makes a GET request to the specified URL and returns the response. The retryWhen operator is used to retry the request in case of an error. The errors observable passed to retryWhen emits an error event for each failed attempt. The errors observable is piped to delay operator which will wait for 1 second before retrying the request, take operator will retry the request at most 5 times, and finalize operator will log a message after retries are completed.


It is essential to set a maximum number of retries and a delay between retries to prevent an infinite loop of requests. In this example, we are retrying the request at most 5 times and waiting for 1 second between each retry. This helps avoid overwhelming the server with too many requests in a short time. Additionally, it is a good practice to log in or notify the user that the service is retrying the request, so they are aware of what is happening.


It is also important to note that retries should be used judiciously, as they may not always be the best solution for handling errors. In some cases, it may be better to handle the error and display a message to the user or take another action.


Comments

Popular posts from this blog

How to Make a Custom URL Shortener Using C# and .Net Core 3.1

C# and .Net Core 3.1:  Make a Custom URL Shortener Since a Random URL needs to be random and the intent is to generate short URLs that do not span more than 7 - 15 characters, the real thing is to make these short URLs random in real life too and not just a string that is used in the URLs Here is a simple clean approach to develop custom solutions Prerequisite:  Following are used in the demo.  VS CODE/VISUAL STUDIO 2019 or any Create one .Net Core Console Applications Install-Package Microsoft.AspNetCore -Version 2.2.0 Add a class file named ShortLink.cs and put this code: here we are creating two extension methods. public   static   class   ShortLink {      public   static   string   GetUrlChunk ( this   long   key ) =>            WebEncoders . Base64UrlEncode ( BitConverter . GetBytes ( key ));      public   static   long   GetK...

Azure key vault with .net framework 4.8

Azure Key Vault  With .Net Framework 4.8 I was asked to migrate asp.net MVC 5 web application to Azure and I were looking for the key vault integrations and access all the secrete out from there. Azure Key Vault Config Builder Configuration builders for ASP.NET  are new in .NET Framework >=4.7.1 and .NET Core >=2.0 and allow for pulling settings from one or many sources. Config builders support a number of different sources like user secrets, environment variables and Azure Key Vault and also you can create your own config builder, to pull in configuration from your own configuration management system. Here I am going to demo Key Vault integrations with Asp.net MVC(download .net framework 4.8). You will find that it's magical, without code, changes how your app can read secretes from the key vault. Just you have to do the few configurations in your web config file. Prerequisite: Following resource are required to run/complete this demo · ...

AWS FREE ASP.NET CORE (.NET 6.0) HOSTING WITH FREE SSL

  FREE ASP.NET CORE (.NET 6.0) Hosting on AWS (Amazon Web Services) Today I was able to host my asp.net 6.0  + ANGULAR 14 application  on AWS Free  Initial Setup of your AWS Account and your Computer Get ready with your asp.net core 3.1 /.net 6 application Install  "AWS toolkit for visual studio 2022" as  visual studio extensions :  it will be required to deploy smoothly from Visual Studio 2022 itself, your life will be easy. Let's finish the AWS account setup  Get signed up with: its free but it will be required a valid credit card or debit card, they will charge nothing for the free services for 1 year * https://portal.aws.amazon.com/billing/signup#/start/email AWS console  for services and offering http://console.aws.amazon.com/ Create a user in AWS Console:  IAM With the help of AWS Identity and Access Management (IAM), you can control who or what has access to the services and resources offered by AWS, centrally manage fine-grained...