Ben
Ben

Reputation: 609

HttpClient performance issues when deployed

I have the code below. Running it locally I get the response back from the API in under 1 second.

When I deploy it to a server, it's taking anywhere between 3 and 10 minutes to get the response!

I've deployed to 3 different servers with the same result. Any idea what might be wrong?

Below is my code:

string response = string.Empty;
try
{
    var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json");

    using (var client = new HttpClient())
    {
        var responseMessage = client.PostAsync("https://myapi/createshorturl", content).Result;
        response = responseMessage.Content.ReadAsStringAsync().Result;
        return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response);
    }
}
catch (Exception x)
{
    return null;
}

Upvotes: 0

Views: 824

Answers (2)

phuzi
phuzi

Reputation: 13060

It's likely you're using HttpClient wrong. Take a look at the following articles before continuing to use it:

TL;DR:

  • HttpClient holds on to the underlying socket far longer than you think.
  • Reuse HttpClient, do not create a new one for every request.
  • Use IHttpClientFactory
  • Don't .Result

Upvotes: 2

Tanveer Badar
Tanveer Badar

Reputation: 5523

HttpClient instances should be reused, that should be your first stop to making changes here. Secondly, don't ever do Task.Result if you can avoid it. It is a synchronous call likely falling behind under load.

class Something
{
    HttpClient client = new HttpClient();

    public async Task<CreateShortUrlResponse> GetResponseAsync()
    {
        string response = string.Empty;

        try
        {
            var content = new StringContent(JsonConvert.SerializeObject(request), System.Text.Encoding.UTF8, "application/json");

            {
                var responseMessage = await client.PostAsync("https://myapi/createshorturl", content);
                response = await responseMessage.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<CreateShortUrlResponse>(response);
            }
        }
        catch (Exception x)
        {
            //you should log something here, rather than silently returning null. Or let it propagate up to where it can be handled.
            return null;
        }
    }
}

Upvotes: 1

Related Questions