Azure Function slow HTTP requests compared to when running in localhost

Viewed 471

I'm using a Azure Function .Net 6 Isolated.

When I run the function on localhost from VS2022, it is 5 times faster then when I deploy it to Azure Function. Localhost is a VM hosted in Azure in the same region as the function. I tried different Service Plans, but issue remains. (Consumption Plan, Elastic Premium EP3, Premium V2 P3v2)

The same code running in localhost Vs. Azure

Results in different regions vs. localhost: enter image description here

The code is as follows:

DI - using the IHttpClientFactory (here):

public static class DataSourceServiceRegistration
{        
   public static IServiceCollection RegisterDataSourceServices(this IServiceCollection serviceCollection)
   {
       serviceCollection.AddHttpClient();
       return serviceCollection;
   }
}

HttpClient usage:

private readonly HttpClient _httpClient;

public EsriHttpClientAdapter(HttpClient httpClient)
{
    _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}

public async Task<JsonDocument> SendPrintServiceMessage(string url, HttpMethod httpMethod, string referer, IEnumerable<KeyValuePair<string, string>> content = null)
{
    var watch = System.Diagnostics.Stopwatch.StartNew();
    HttpContent httpContent = null;
    if (content != null)
    {
        httpContent = new FormUrlEncodedContent(content);
    }
    var msg = new HttpRequestMessage(httpMethod, url) { Content = httpContent };
    _httpClient.DefaultRequestHeaders.Referrer = new Uri(referer);
    _httpClient.DefaultRequestHeaders.Add("some", "config");

    _logger.LogInformation($"Before SendAsync - time {watch.ElapsedMilliseconds}");
    var result = await _httpClient.SendAsync(msg);
    _logger.LogInformation($"After SendAsync - time {watch.ElapsedMilliseconds}");
    var response = await result.Content.ReadAsStringAsync();
    _logger.LogInformation($"After ReadAsStringAsync - time {watch.ElapsedMilliseconds}");

    if (result.StatusCode == HttpStatusCode.OK)
    {
        //do some stuff here
    }
}

Application Insights is as follows:

AZURE:

enter image description here

Localhost:

enter image description here

1 Answers

Not sure if this is applicable to you, but hopefully it helps. If you're running under a Basic (Consumption) plan, your function will always be cold and need to spin up when being invoked by Http trigger. To circumvent this, you can set the function to Always On (if this is within your budget and scope) if on App Service Environment, Dedicated, or Premium plans. (In other words, Free Functions will always run cold.)

You can change this under Configuration > General Settings > Always On.

There's good info on how a Function runs through a cold startup at:

https://azure.microsoft.com/en-us/blog/understanding-serverless-cold-start/

Related