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)
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 (
NullReferenceExceptiononcontext.Requestinside a callback andInvalidOperationException: 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.SendAsyncthat 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.PollyandPolly.Contrib.WaitAndRetryinstead ofMicrosoft.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_methodnetwork_protocol_version,url_scheme.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.
ApiGatewayBearerTokenMessageHandler.cs:line 30is the firstvar response = await base.SendAsync(request, cancellationToken);.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
ApiGatewayBearerTokenMessageHandlercallsbase.SendAsynctwice, as a refresh token strategy:We suspect this is not a good idea, and will investigate.
We are gonna try a workaround:
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:
I don’t see how we somehow could register the handler twice. But I could try adding the
.AddMetricsEnrichmentHandlermethod you mentioned.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.Resiliencewhich 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:
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
ConfigureAdditionalHttpMessageHandlersand checking the list of all the handlers (you can even create an extension method to use instead ofAddHttpMessageHandler), e.g.:You can check (2) in runtime by either collecting existing HttpClient logs, or by adding some tracking to the handler/message, e.g.:
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.This looks suspicious, can you please share more context and all the relevant code, including service registration
CrmClientetc.Edit: Natalia replied faster 😄
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.