I have a simple webapp hosted on Azure (app service) that makes calls to two different external APIs. Yesterday we had a huge expected spike in traffic and the whole thing came crashing down which I now realize is because I was creating and disposing of new instances of HttpClient like so:
var url = "https://www.externalapi.com/someendpoint" +
    "/takethedata.js?" +
    "[form]email=" + visitor.EmailAddress +
    "&[form]name=" + visitor.FirstName + " " + visitor.LastName +
    "&[form]zip=" + visitor.zip +
    "&[form]location=" + city + ", " + state;
using(var handler = new HttpClientHandler())
{
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
    handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 |
        System.Security.Authentication.SslProtocols.Tls11 |
        System.Security.Authentication.SslProtocols.Tls;
    using(var client = new HttpClient(handler))
    {
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = await client.GetAsync(url);
    }
}
In the same controller in another method I am making another external API in the same way:
string AuthToken = "2678c7b5-3cvt-XXXX-XXXX-XXXXXXXXX";
string BaseUrl = "https://someotherdomain.com/dosomething/" + AuthToken;
var jsonContent = "{ \"param1\": \"" + value1 + "\", \"Timeout\":\"15\", \"Verbose\":\"True\" }";
using(var client = new HttpClient())
{
    client.BaseAddress = new Uri(BaseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.PostAsync(BaseUrl,
        new StringContent(jsonContent, Encoding.UTF8, "application/json"));
    if (!response.IsSuccessStatusCode)
    {
        return Json("Email Check Error");
    }
    else
    {
        var responseContent = await response.Content.ReadAsStringAsync();
        return Json(responseContent);
    }
}
I've been reading about the HttpClient and creating a singleton per external API? And issues with setting different URIs etc. and I am really confused on how to proceed. If I just dump the "using" will it potentially resolve? If I need to create a singleton is there anywhere that demonstrates how I might do this and have it apply to my scenario? Thanks!
 
     
    