runtime: `HttpMetricsEnrichmentContext.AddCallback` seems to sometimes add duplicate tags

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

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 25 (13 by maintainers)

Most upvoted comments

Hi there,

We are also facing the same issue in some of our applications.

We are looking at this and and we will likely consider backporting the fix.

The changes should be available in 8.0.13 and 9.0.2 servicing releases.

Hi there,

I’m facing a similar issue (NullReferenceException on context.Request inside a callback and InvalidOperationException: Collection was modified; enumeration operation may not execute, also using retries from Polly and Duende).

It seems that after calling a callback, the context resets its fields and might be returned to the pool. However, if there’s a retry with the same request instance, the request gets the context from the options, even though this context might have already been picked up by another request.

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 .

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();

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.

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);
        });

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.

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.

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.

@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);
    }
}

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 😄

// 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.