Correct usage of HttpClient

In the real world, where in an organisation various microservices are sharing the same Virtual Machines, it becomes really mandatory to correctly use the httpclient object. HttpClient object is very expensive in terms of memory usage,sockets. Mishandling of which can very quickly eat away the sockets and end up giving lot of trouble in Production. Even if one or very few no of the frequently used Microservices are not handling the HttpClient object properly, it might eat away the sockets really quickly and causing apps to slow down.

 Wrong Usage: Instantiating HttpClients inside using block.

 using (var http = new HttpClient())

 Problem: The HttpClient works differently, even if you try to dispose the httpclient object from your code, in the Azure machine the connection remains in a TIME_WAIT state for a very long time, and it takes a lot of time to actually close the used sockets which were opened when you had instantiated the HttpClient.

A single Instance of the HttpClient will reuse the sockets much more efficiently and will avoid run time errors during excessive loads.

No alt text provided for this image

Source of Image: https://www4.cs.fau.de/Projects/JX/Projects/TCP/tcpstate.html

Recommended Approach:

Microsoft’s recommended approach is to use a single instance of HttpClient throughout your application, at the very first instantiation of the service.

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.6.1 

Common Usage Scenario:

A Common usage scenario where we are making multiple calls to different apis, the base addresses are different and some-times the headers are also different.

We shouldn’t change the properties of httpclient directly, instead we should use the HttpRequestMessage to create an object with the appropriate headers and the APIToken etc and pass it to the HttpClient object.

 SampleCode:

 var httpRequestMessage = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri(“baseaddress”),
            Headers = { 
                { HttpRequestHeader.Authorization.ToString(), "bearertoken" },
                { HttpRequestHeader.Accept.ToString(), "application/json" },
                { "X-Version", "1" }
            },
            Content = new StringContent(“”)
        };
var response = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);

To view or add a comment, sign in

More articles by Ashutosh Kumar

  • Trusted Signing Client Tools Public Release

    Hi Everyone, Over the past year, we have worked diligently to deliver this solution to our customers, enhancing their…

Others also viewed

Explore content categories