runtime icon indicating copy to clipboard operation
runtime copied to clipboard

`HttpMetricsEnrichmentContext.AddCallback` seems to sometimes add duplicate tags

Open lindeberg opened this issue 2 years ago • 25 comments

Description

When using HttpMetricsEnrichmentContext.AddCallback, it sometimes seems to add duplicate tags to a metric.

For a metric, I got multiple amount of different amount of duplicates. For example, with prometheus exposed metrics, notice the custom label gateway_api:

http_client_request_duration_seconds_bucket{gateway_api="crm",http_request_method="GET",http_response_status_code="200",network_protocol_version="1.1",server_address="whatever.com",url_scheme="https",le="0.1"} 4234 1727271043861

http_client_request_duration_seconds_bucket{gateway_api="crm",gateway_api="crm",http_request_method="GET",http_response_status_code="200",network_protocol_version="1.1",server_address="whatever.com",url_scheme="https",le="0.1"} 108 1727271043861

http_client_request_duration_seconds_bucket{gateway_api="crm",gateway_api="crm",gateway_api="crm",http_request_method="GET",http_response_status_code="200",network_protocol_version="1.1",server_address="whatever.com",url_scheme="https",le="0.1"} 8 1727271043861

http_client_request_duration_seconds_bucket{gateway_api="crm",gateway_api="crm",gateway_api="crm",gateway_api="crm",http_request_method="GET",http_response_status_code="200",network_protocol_version="1.1",server_address="whatever.com",url_scheme="https",le="0.1"} 1 1727271043861

Which causes Prometheus scraper to stop working with error message label name "gateway_api" is not unique: invalid sample.

Reproduction Steps

I'm unable to reproduce it locally, but it happened in the production environment which has a high request rate.

public sealed class HttpClientMetricsEnrichmentHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpMetricsEnrichmentContext.AddCallback(request, context => context.AddCustomTag("gateway-api", "crm"););

        return base.SendAsync(request, cancellationToken);
    }
}
// While writing this, I realized the scope may be the problem somehow? 🦆
services.AddScoped<HttpClientMetricsEnrichmentHandler>();
services.AddHttpClient<ICrmClient, CrmClient>().AddHttpMessageHandler<HttpClientMetricsEnrichmentHandler>(); //Etc.

Followed by usage of the ICrmClient in the API.

Expected behavior

The custom tag should only be added once, I don't know how exactly. But maybe a duplicate check should be included?

Actual behavior

The custom tag is added multiple times, creating duplicate tags, which causes an error in Prometheus.

Regression?

No response

Known Workarounds

No response

Configuration

mcr.microsoft.com/dotnet/aspnet:8.0.8-alpine

Other information

No response

lindeberg avatar Sep 26 '24 14:09 lindeberg

// While writing this, I realized the scope may be the problem somehow? 🦆

I can't yet comment on whether this could be the cause of the duplication, but note that the handler used in AddHttpMessageHandler<THandler> must be registered as a Transient, see the Type Parameters section in the API docs.

CarnaViire avatar Sep 26 '24 14:09 CarnaViire

Without a repro or some other source of actionable data, it is not possible to determine if the bug lives in System.Net.Http, the application code, or some library your app is using.

// While writing this, I realized the scope may be the problem somehow? 🦆

This looks suspicious, can you please share more context and all the relevant code, including service registration CrmClient etc.

Edit: Natalia replied faster 😄

antonfirsov avatar Sep 26 '24 14:09 antonfirsov

Thank you! We can start by trying out registering the Message Handler correctly as transient.

lindeberg avatar Sep 26 '24 15:09 lindeberg

@lindeberg did the registration change help?

antonfirsov avatar Oct 01 '24 18:10 antonfirsov

@lindeberg also couple of additional thoughts/things to check:

  1. Whether it is possible that the message handler gets added to the same client twice
  2. Whether there is any resilience handler/pipeline set up before the HttpClientMetricsEnrichmentHandler, so if retry happens, the enrichment handler might end up executing twice over the same request message.

You can check (1) over the registration time by calling ConfigureAdditionalHttpMessageHandlers and checking the list of all the handlers (you can even create an extension method to use instead of AddHttpMessageHandler), e.g.:

public static IHttpClientBuilder AddMetricsEnrichmentHandler(this IHttpClientBuilder builder)
    => builder.ConfigureAdditionalHttpMessageHandlers((additionalHandlers, serviceProvider) =>
    {
        if (additionalHandlers.Any(h => h is HttpClientMetricsEnrichmentHandler))
        {
            throw new Exception("MetricsEnrichmentHandler added twice");
        }

        additionalHandlers.Add(serviceProvider.GetRequiredService<HttpClientMetricsEnrichmentHandler>());
    });

// -------------

services.AddHttpClient<ICrmClient, CrmClient>()
    .AddMetricsEnrichmentHandler(); // instead of AddHttpMessageHandler<HttpClientMetricsEnrichmentHandler>()

You can check (2) in runtime by either collecting existing HttpClient logs, or by adding some tracking to the handler/message, e.g.:

public sealed class HttpClientMetricsEnrichmentHandler : DelegatingHandler
{
    private static readonly HttpRequestOptionsKey<bool> HandlerAddedKey = new("MetricsEnrichmentHandlerAdded");

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Options.TryGetValue<bool>(HandlerAddedKey, out var _))
        {
            throw new Exception("MetricsEnrichmentHandler called twice");
        }
        request.Options.Set(HandlerAddedKey, true);

        HttpMetricsEnrichmentContext.AddCallback(request, context => context.AddCustomTag("gateway-api", "crm"));

        return base.SendAsync(request, cancellationToken);
    }
}

CarnaViire avatar Oct 02 '24 12:10 CarnaViire

@lindeberg did the registration change help?

@CarnaViire

I haven't had the time to try it out yet, but spot on about the resilience handler being registered before the HttpClientMetricsEnrichmentHandler. I didn't consider that, now it makes sense.

Full registration:

  services
            .AddHttpClient<ISalesClient, SalesClient>()
            .AddCompanyDefaultResilienceHandler()
            .AddHttpMessageHandler<HttpClientMetricsEnrichmentHandler>()
            .ConfigureHttpClient((serviceProvider, httpClient) =>
            {
                var settings = serviceProvider.GetRequiredService<IOptions<SalesClientSettings>>().Value;
                httpClient.BaseAddress = new Uri(settings.BaseAddress);
            });

So I should make sure to have the HttpClientMetricsEnrichmentHandler after the resilience handler?

lindeberg avatar Oct 07 '24 06:10 lindeberg

@lindeberg how is the resilience handler implemented? Does it reuse the HttpRequestMessage instance? If yes and the HttpClientMetricsEnrichmentHandler is being run after the resilience handler, that would explain double additions on retries.

antonfirsov avatar Oct 07 '24 23:10 antonfirsov

@antonfirsov

    private static Action<ResiliencePipelineBuilder<HttpResponseMessage>> Configure()
    {
        return resilience =>
        {
            resilience.AddRetry(new HttpRetryStrategyOptions
            {
                ShouldRetryAfterHeader = true,
                MaxRetryAttempts = 3,
                Delay = TimeSpan.FromSeconds(.2),
                UseJitter = true,
                BackoffType = DelayBackoffType.Exponential,
            });
            resilience.AddTimeout(TimeSpan.FromSeconds(10));
        };
    }

lindeberg avatar Oct 08 '24 07:10 lindeberg

Based on the code, I assume you are using Microsoft.Extensions.Resilience which AFAIK relies on Polly. Polly may reuse the request object between retries which can lead to the attribute duplication described.

@lindeberg can you confirm if changing the handler order fixes the issue?

We should document in API and conceptual docs that enrichment callbacks should be registered before running handlers that may retry the request.

antonfirsov avatar Oct 08 '24 22:10 antonfirsov

We should document in API and conceptual docs that enrichment callbacks should be registered before running handlers that may retry the request.

I wonder if it would make sense to also consider an additional API to give an ability to do at least one of the following:

  • overwrite existing values for the keys
    • ClearCustomTag(name), or
    • SetCustomTag(name, value), or
    • AddCustomTag(name, value, overwrite: true)
  • add a key only once
    • TryAddCustomTag(name, value)
  • check if the key is added
    • ContainsTag(name)
  • list all the set keys and/or values
    • ListCustomTags()

CarnaViire avatar Oct 09 '24 11:10 CarnaViire

I wonder if it would make sense to also consider an additional API to give an ability to do at least one of the following

I would prefer if users wouldn't need to rely on such functionality to get things done and I must admit I'm not happy with the shape of HttpMetricsEnrichmentContext. It was designed around assumptions which are not necessarily true retrospectively, ie. per-request enrichment registration doesn't seem to be a thing users really need, and it has lead to issues like this one. If we will implement any improvements around metrics enrichment, they have to be designed in context of related requests like #96263 and #103130.

antonfirsov avatar Oct 09 '24 17:10 antonfirsov

Hello @antonfirsov @CarnaViire! Unfortunately the changes we made have not had an effect, and once again we got the duplicate tags.

The first change we made was to make the service registration Transient: services.AddTransient<HttpClientMetricsEnrichmentHandler>();

And the second change was to add resilience with retries later in the pipeline:

services
  .AddHttpClient<ISalesClient, SalesClient>()
  .ConfigureHttpClient((serviceProvider, httpClient) =>
  {
      var settings = serviceProvider.GetRequiredService<IOptions<SalesClientSettings>>().Value;
      httpClient.BaseAddress = new Uri(settings.BaseAddress);
  })
  .ConfigurePrimaryHttpMessageHandler<ApiGatewayBearerTokenMessageHandler>()
  .AddHttpMessageHandler<HttpClientMetricsEnrichmentHandler>()
  .AddCompanyDefaultResilienceHandler();

I don't see how we somehow could register the handler twice. But I could try adding the .AddMetricsEnrichmentHandler method you mentioned.

lindeberg avatar Oct 24 '24 14:10 lindeberg

We are gonna try a workaround:

   HttpMetricsEnrichmentContext.AddCallback(request, context =>
        {
            if (!context.Request.Options.TryAdd(GatewayApiTag, GatewayApiTag))
            {
                return;
            }

            var tag = GetGatewayApiTag(context.Request.RequestUri, apiGatewayHost);

            if (tag is null)
            {
                return;
            }

            context.AddCustomTag(GatewayApiTag, tag);
        });

lindeberg avatar Oct 24 '24 14:10 lindeberg

Guys!! @CarnaViire @antonfirsov

We have a new suspicion. You were on to something with "Whether it is possible that the message handler gets added to the same client twice". It is not added twice, but the ApiGatewayBearerTokenMessageHandler calls base.SendAsync twice, as a refresh token strategy:

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = await tokenClient.GetBearerToken(false, cancellationToken);

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = await base.SendAsync(request, cancellationToken);

        if (response.StatusCode != HttpStatusCode.Unauthorized)
        {
            return response;
        }

        token = await tokenClient.GetBearerToken(true, cancellationToken);

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

        response = await base.SendAsync(request, cancellationToken);

        return response;
    }

We suspect this is not a good idea, and will investigate.

lindeberg avatar Oct 30 '24 10:10 lindeberg

This definitely seems like it could be the culprit. Good catch!

I was thinking that reordering didn't really help, because in the end it was either (1) adding the callback twice if the retry is happening before the EnrichmentHandler, or (2) executing the callback twice, if the retry is happening after the EnrichmentHandler 😅 (cc @antonfirsov to validate my thoughts -- all the callbacks are bulk-executed at the "bottom" of the pipeline, before the message is sent on the wire, right?)

But the workaround you suggested in https://github.com/dotnet/runtime/issues/108284#issuecomment-2435501733 should work regardless, because it's checking within the callback itself.

CarnaViire avatar Oct 30 '24 13:10 CarnaViire

News

We have noticed default tags other than our custom one being added duplicates. The ones we have seen are: http_request_method network_protocol_version, url_scheme.

Image

We have also noticed an unhandled exception (shame on us we didn't notice earlier). We are however unusure how it correlates with the duplicate tag issue.

We don't see any resilience events logged in the trace of this request.

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at void System.Net.Http.Metrics.HttpMetricsEnrichmentContext.RecordDurationWithEnrichment(HttpRequestMessage request, HttpResponseMessage response, Exception exception, TimeSpan durationTime, in TagList commonTags, Histogram<double> requestDuration)
   at void System.Net.Http.Metrics.MetricsHandler.RequestStop(HttpRequestMessage request, HttpResponseMessage response, Exception exception, long startTimestamp, bool recordCurrentRequests)
   at async ValueTask<HttpResponseMessage> System.Net.Http.Metrics.MetricsHandler.SendAsyncWithMetrics(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
   at async ValueTask<HttpResponseMessage> System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
   at async Task<HttpResponseMessage> ApiNamespace.HttpClients.ApiGatewayBearerTokenMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /runner/_work/api-repo/api-repo/src/ApiNamespace/HttpClients/ApiGatewayBearerTokenMessageHandler.cs:line 30
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendCoreAsync(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken)+Core(?)
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Resilience.ResilienceHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)+(?) => { }
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Resilience.ResilienceHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendCoreAsync(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken)+Core(?)
   at async Task<HttpResponseMessage> System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request)+Core(?)
   at async Task<ICollection<UserModel>> ApiNamespace.Integrations.Crm.Client.CrmClient.GetUsersAsync(string userId, CancellationToken cancellationToken) in /runner/_work/api-repo/api-repo/src/ApiNamespace/Integrations/CRM/Client/CrmClient.cs:line 3655
   at async Task<ICollection<User>> ApiNamespace.Services.CrmService.GetUserList(Guid userId, CancellationToken cancellationToken) in /runner/_work/api-repo/api-repo/src/ApiNamespace/Services/CrmService.cs:line 110
   at async Task<UserAccountInfo> ApiNamespace.ServiceAggregators.UserAccountInfoAggregator.GetUserAccountInfo(User user, CancellationToken cancellationToken) in /runner/_work/api-repo/api-repo/src/ApiNamespace/ServiceAggregators/UserAccountInfoAggregator.cs:line 22
   at async Task<ActionResult<UserAccountInfo>> ApiNamespace.Endpoints.Users.UserAccountInfoEndpoint.GetUserAccountInfo(CancellationToken cancellationToken) in /runner/_work/api-repo/api-repo/src/ApiNamespace/Endpoints/Users/UserAccountInfoEndpoint.cs:line 32
   at object lambda_method17(Closure, object)
   at async ValueTask<IActionResult> Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()+Awaited(?)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()+Awaited(?)
   at void Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()+Awaited(?)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()+Awaited(?)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeAsync()+Awaited(?) x 2
   at async Task Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at async Task Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at async Task ApiNamespace.Instrumentation.Metrics.HttpMetricsTagsEnricherMiddleware.InvokeAsync(HttpContext httpContext) in /runner/_work/api-repo/api-repo/src/ApiNamespace/Instrumentation/Metrics/HttpMetricsTagsEnricherMiddleware.cs:line 16
   at async Task ApiNamespace.Middleware.DefaultExceptionHandlingMiddleware.InvokeAsync(HttpContext httpContext) in /runner/_work/api-repo/api-repo/src/ApiNamespace/Middleware/DefaultExceptionHandlingMiddleware.cs:line 36

ApiGatewayBearerTokenMessageHandler.cs:line 30 is the first var response = await base.SendAsync(request, cancellationToken);.

public class HttpMetricsTagsEnricherMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext httpContext)
    {
        var metricsTagsFeature = httpContext.Features.GetRequiredFeature<IHttpMetricsTagsFeature>();

        var operationId = httpContext.GetEndpoint()?.Metadata.GetMetadata<SwaggerOperationAttribute>()?.OperationId;

        if (!string.IsNullOrWhiteSpace(operationId))
        {
            metricsTagsFeature.Tags.Add(new("http.route.operation.id", operationId));
        }

        await next(httpContext);
    }
}
app.UseExceptionHandler();
        app.UseMiddleware<DefaultExceptionHandlingMiddleware>();
        app.UseMiddleware<HttpMetricsTagsEnricherMiddleware>();
        app.UseHeaderPropagation();
        app.UseAuthentication();
        app.UseAuthorization();
        app.MapControllers().RequireAuthorization();

lindeberg avatar Oct 30 '24 15:10 lindeberg

We have noticed default tags other than our custom one being added duplicates. Examples: http_request_method network_protocol_version.

Is is always the same set of tags that get duplicated, or it varies? Is it reproducible even if you don't use your own enrichment?

CarnaViire avatar Oct 30 '24 15:10 CarnaViire

@CarnaViire it varies. I found one like this: http_client_request_duration_seconds_bucket{gateway_api="crm",http_request_method="GET",http_response_status_code="200",network_protocol_version="1.1",network_protocol_version="1.1",url_scheme="https",url_scheme="https"..}

  • gateway_api not duplicated
  • http_request_method not duplicated
  • network_protocol_version duplicated
  • url_scheme duplicated

(same for the http_client_request_duration_seconds_sum and http_client_request_duration_seconds_count).

And another one like this

http_client_request_duration_seconds_bucket{gateway_api="crm",gateway_api="crm",http_request_method="GET",http_response_status_code="200",network_protocol_version="1.1",url_scheme="https",url_scheme="https"..}

We will try removing the custom enricher tomorrow.

All pods that have the problem has logged one of the exceptions.

lindeberg avatar Oct 30 '24 20:10 lindeberg

Other, similiar exceptions found, even though we have the workaround:

System.ArgumentException: An item with the same key has already been added. Key: gateway-api
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Net.Http.Metrics.HttpMetricsEnrichmentContext.RecordDurationWithEnrichment(HttpRequestMessage request, HttpResponseMessage response, Exception exception, TimeSpan durationTime, TagList& commonTags, Histogram`1 requestDuration)
   at System.Net.Http.Metrics.MetricsHandler.RequestStop(HttpRequestMessage request, HttpResponseMessage response, Exception exception, Int64 startTimestamp, Boolean recordCurrentRequests)
   at System.Net.Http.Metrics.MetricsHandler.SendAsyncWithMetrics(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at [Company].Api.HttpClients.ApiGatewayBearerTokenMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/HttpClients/ApiGatewayBearerTokenMessageHandler.cs:line 30
   at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.<SendCoreAsync>g__Core|5_0(HttpRequestMessage request, Boolean useAsync, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Resilience.ResilienceHandler.<>c.<<SendAsync>b__3_0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.Extensions.Http.Resilience.ResilienceHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<SendCoreAsync>g__Core|5_0(HttpRequestMessage request, Boolean useAsync, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at [Company].Api.Integrations.Client.Customer_GetTravelersAsync(String scimId, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/Integrations/Client/Client.cs:line 3655
   at [Company].Api.Services.Service.GetCustomerTravelers(Guid scimId, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/Services/Service.cs:line 110
   at [Company].Api.ServiceAggregators.InformationServiceAggregator.GetInformation(Account account, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/ServiceAggregators/InformationServiceAggregator.cs:line 22
   at [Company].Api.Endpoints.Persons.GetInformationEndpoint.GetInformation(CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/Endpoints/Persons/GetInformationEndpoint.cs:line 32
   at lambda_method54(Closure, Object)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at [Company].Api.Instrumentation.Metrics.HttpMetricsTagsEnricherMiddleware.InvokeAsync(HttpContext httpContext) in /runner/_work/api/api/src/[Company]/Api/Instrumentation/Metrics/HttpMetricsTagsEnricherMiddleware.cs:line 16
   at [Company].Api.Middleware.DefaultExceptionHandlingMiddleware.InvokeAsync(HttpContext httpContext) in /runner/_work/api/api/src/[Company]/Api/Middleware/DefaultExceptionHandlingMiddleware.cs:line 36

System.NullReferenceException: Object reference not set to an instance of an object.
   at void System.Net.Http.Metrics.HttpMetricsEnrichmentContext.RecordDurationWithEnrichment(HttpRequestMessage request, HttpResponseMessage response, Exception exception, TimeSpan durationTime, in TagList commonTags, Histogram<double> requestDuration)
   at void System.Net.Http.Metrics.MetricsHandler.RequestStop(HttpRequestMessage request, HttpResponseMessage response, Exception exception, long startTimestamp, bool recordCurrentRequests)
   at async ValueTask<HttpResponseMessage> System.Net.Http.Metrics.MetricsHandler.SendAsyncWithMetrics(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
   at async ValueTask<HttpResponseMessage> System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, bool async, CancellationToken cancellationToken)
   at async Task<HttpResponseMessage> [Company].Api.HttpClients.ApiGatewayBearerTokenMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/HttpClients/ApiGatewayBearerTokenMessageHandler.cs:line 30
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendCoreAsync(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken)+Core(?)
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Resilience.ResilienceHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)+(?) => { }
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Resilience.ResilienceHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at async Task<HttpResponseMessage> Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendCoreAsync(HttpRequestMessage request, bool useAsync, CancellationToken cancellationToken)+Core(?)
   at async Task<HttpResponseMessage> System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request)+Core(?)
   at async Task<ICollection<TravelerModelPrivate>> [Company].Api.Integrations.Client.CrmClient.PrivateCustomer_GetTravelersAsync(string scimId, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/Integrations/Client/Client.cs:line 3655
   at async Task<ICollection<Traveler>> [Company].Api.Services.Service.GetCustomerTravelers(Guid scimId, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/Services/Service.cs:line 110
   at async Task<AccountInformation> [Company].Api.ServiceAggregators.InformationServiceAggregator.GetInformation(Account account, CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/ServiceAggregators/InformationServiceAggregator.cs:line 22
   at async Task<ActionResult<AccountInformation>> [Company].Api.Endpoints.Persons.GetInformationEndpoint.GetInformation(CancellationToken cancellationToken) in /runner/_work/api/api/src/[Company]/Api/Endpoints/Persons/GetInformationEndpoint.cs:line 32
   at object lambda_method54(Closure, object)
   at async ValueTask<IActionResult> Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()+Awaited(?)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()+Awaited(?)
   at void Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()+Awaited(?)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()+Awaited(?)
   at async Task Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeAsync()+Awaited(?) x 2
   at async Task Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at async Task Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at async Task [Company].Api.Instrumentation.Metrics.HttpMetricsTagsEnricherMiddleware.InvokeAsync(HttpContext httpContext) in /runner/_work/api/api/src/[Company]/Api/Instrumentation/Metrics/HttpMetricsTagsEnricherMiddleware.cs:line 16
   at async Task [Company].Api.Middleware.DefaultExceptionHandlingMiddleware.InvokeAsync(HttpContext httpContext) in /runner/_work/api/api/src/[Company]/Api/Middleware/DefaultExceptionHandlingMiddleware.cs:line 36

lindeberg avatar Oct 30 '24 20:10 lindeberg

It SEEMS to always be the same client.SendAsync that triggers the exception, even if we have dozens of them in hot paths of the codebase using the same pipeline. (it is also just one of the hottest paths)

I doesn't happen every request. It happened in 27 out of 25345 requests on the endpoint in question. Points to some race-condition? Nothing else is logged >= level Information around it.

The endpoint has had a load of 20-80 req/sec while the errors has occurred.

We are not seeing the problem on other codebases that have an almost identical pipeline except they are using Microsoft.Extensions.Http.Polly and Polly.Contrib.WaitAndRetry instead of Microsoft.Extensions.Http.Resilience. But I really don't know if that's a clue or coincidence.

The problem has stopped occurring after removing the HttpClientMetricsEnrichmentHandler .

lindeberg avatar Oct 31 '24 06:10 lindeberg