Too many HttpClients are created
Hello,
we have severe CPU usage problems with a Docker based .Net Core service and I think they are related to the WCF implementation for .Net Core.
I used perfcollect to start an event trace (which took something like 2-3 minutes):
perfcollect collect sample1 -pid 1 -events
After that I started to analyze this using babeltrace and received the following result:
root@5f211d84897a:~# babeltrace ~/lttng-traces/auto* | grep '\.ctor' | grep Enter | grep thisOrContextObject | sed 's/.*\\"thisOrContextObject\\":\\"\([^ ]*\)#.*/\1/' | sort | uniq -c | sort -n
26 BufferedMessageContent
26 HttpRequestMessage
52 HttpClient
52 HttpConnectionResponseContent
52 HttpResponseMessage
52 Socket
(Probably this pipe chain could be simplified, sorry.) The one thing that scares me most are the 52 HttpClients that are created.
Then, I used an EventListener to get proper stack traces in our log files:
using System.Diagnostics;
using System.Diagnostics.Tracing;
using NLog;
namespace Uny.con.IssueService.Host.Configuration
{
sealed class EventSourceEventListener : EventListener
{
ILogger logger;
public EventSourceEventListener(ILogger lggr)
{
logger = lggr;
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name.Equals("Microsoft-System-Net-Http"))
{
EnableEvents
(
eventSource,
EventLevel.Verbose
);
}
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
if (!eventData.EventName.Equals("Enter"))
{
return;
}
var memberName = GetPayloadValue("memberName", eventData);
var thisOrContextObject = GetPayloadValue("thisOrContextObject", eventData) as string;
if (".ctor".Equals(memberName) && thisOrContextObject != null && thisOrContextObject.StartsWith("HttpClient#"))
{
var stackTrace = new StackTrace(true);
logger.Info(stackTrace);
}
}
private object GetPayloadValue(string name, EventWrittenEventArgs eventData)
{
var index = eventData.PayloadNames.IndexOf(name);
var result = (index >= 0) ? eventData.Payload[index] : null;
return result;
}
}
}
We see a lot of the following two log messages in our log files:
2019-06-14T15:52:36.9855856+00:00 instance=5f211d84897a srv=issue-service level=Info
at Uny.con.IssueService.Host.Configuration.EventSourceEventListener.OnEventWritten(EventWrittenEventArgs eventData) in /build/src/Uny.con.IssueService.Host/Configuration/EventSourceEventListener.cs:line 41,
at System.Diagnostics.Tracing.EventSource.DispatchToAllListeners(Int32 eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs),
at System.Diagnostics.Tracing.EventSource.WriteToAllListeners(Int32 eventId, Guid* activityID, Guid* childActivityID, Int32 eventDataCount, EventData* data),
at System.Diagnostics.Tracing.EventSource.WriteEventWithRelatedActivityIdCore(Int32 eventId, Guid* relatedActivityId, Int32 eventDataCount, EventData* data),
at System.Diagnostics.Tracing.EventSource.WriteEvent(Int32 eventId, String arg1, String arg2, String arg3),
at System.Net.NetEventSource.Enter(Object thisOrContextObject, Object arg0, String memberName),
at System.Net.Http.HttpMessageInvoker..ctor(HttpMessageHandler handler, Boolean disposeHandler),
at System.Net.Http.HttpClient..ctor(HttpMessageHandler handler, Boolean disposeHandler),
at System.ServiceModel.Channels.HttpChannelFactory`1.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.HttpChannelFactory`1.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper),
at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout),
at System.ServiceModel.Channels.RequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state),
at System.ServiceModel.Dispatcher.RequestChannelBinder.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state),
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.StartSend(Boolean completedSynchronously),
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.FinishEnsureOpen(IAsyncResult result, Boolean completedSynchronously),
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result),
at System.Runtime.TaskHelpers.<>c.<ToApm>b__2_1(Task antecedent, Object obj),
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state),
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot),
at System.Threading.ThreadPoolWorkQueue.Dispatch()
2019-06-14T15:52:36.9907784+00:00 instance=5f211d84897a srv=issue-service level=Info
at Uny.con.IssueService.Host.Configuration.EventSourceEventListener.OnEventWritten(EventWrittenEventArgs eventData) in /build/src/Uny.con.IssueService.Host/Configuration/EventSourceEventListener.cs:line 41,
at System.Diagnostics.Tracing.EventSource.DispatchToAllListeners(Int32 eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs),
at System.Diagnostics.Tracing.EventSource.WriteToAllListeners(Int32 eventId, Guid* activityID, Guid* childActivityID, Int32 eventDataCount, EventData* data),
at System.Diagnostics.Tracing.EventSource.WriteEventWithRelatedActivityIdCore(Int32 eventId, Guid* relatedActivityId, Int32 eventDataCount, EventData* data),
at System.Diagnostics.Tracing.EventSource.WriteEvent(Int32 eventId, String arg1, String arg2, String arg3),
at System.Net.NetEventSource.Enter(Object thisOrContextObject, Object arg0, String memberName),
at System.Net.Http.HttpClient..ctor(HttpMessageHandler handler, Boolean disposeHandler),
at System.ServiceModel.Channels.HttpChannelFactory`1.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.HttpChannelFactory`1.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, CancellationToken cancellationToken),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper),
at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout),
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine),
at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout),
at System.ServiceModel.Channels.RequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state),
at System.ServiceModel.Dispatcher.RequestChannelBinder.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, Object state),
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.StartSend(Boolean completedSynchronously),
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.FinishEnsureOpen(IAsyncResult result, Boolean completedSynchronously),
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result),
at System.Runtime.TaskHelpers.<>c.<ToApm>b__2_1(Task antecedent, Object obj),
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state),
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot),
at System.Threading.ThreadPoolWorkQueue.Dispatch()
I have no idea, what else we can do, especially since HttpChannelFactory is part of the private implementation and not meant to be used/subclassed directly.
Do you think this could be a bug in the WCF implementation? In the WCF client service we are using:
- .Net Core 2.1
- System.ServiceModel.Http 4.5.3
- System.ServiceModel.NetTcp 4.5.3
- System.ServiceModel.Primitives 4.5.3
Any hints are greatly appreciated!
Ciao, Mark
@MarkLie Thank you for reporting the issue. @mconnew Could you take a look at this?
The method System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.FinishEnsureOpen in the call stack means you are opening a new channel each time. If you are creating a new instance of HttpClient each time, that means you are creating a new ChannelFactory instance each time too. So you are doing one of two things:
- Using a client generated by Connected Services and instantiating a new instance each time you make a request (which creates a new instance of ChannelFactory).
- You are creating a new instance of ChannelFactory for each request.
Each instance of ChannelFactory creates a new instance of HttpClient on .NET Core. So basically you are either directly or indirectly creating a new ChannelFactory instance on each request.
@MarkLie let us know if you need anything else.