I have multiple Grpc clients and each need to pack a client certificate. I am using Grpc.Net.ClientFactory to register all my clients.
Not understanding how HttpMessageHandler should be reused, I am concerned about creating a new HttpMessageHandler for each Grpc client being registered as Microsoft docs indicates that
each handler typically manages its own underlying HTTP connections; creating more handlers than necessary can result in connection delays
// register serviceAClient
builder.Services.AddGrpcClient<ServiceA.ServiceAClient>(o => o.Address = new Uri(serviceUrl))
.ConfigureChannel(o => o.HttpHandler = GetHttpHandler(certThumbprint));
// register serviceBClient
builder.Services.AddGrpcClient<ServiceB.ServiceBClient>(o => o.Address = new Uri(serviceUrl))
.ConfigureChannel(o => o.HttpHandler = GetHttpHandler(certThumbprint));
// creates a new HttpMessageHandler
private static HttpMessageHandler GetHttpHandler(string certThumbprint)
{
var httpHandler = new SocketsHttpHandler()
{
PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
KeepAlivePingDelay = TimeSpan.FromSeconds(60),
KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
EnableMultipleHttp2Connections = true,
SslOptions = new SslClientAuthenticationOptions
{
ClientCertificates = LoadClientCertificates(certThumbprint)
};
return httpHandler;
}
What is the better way to deal with HttpMessageHandler in multiple Grpc clients scenario - should each client be registered with a single HttpMessageHandler? Or each client should have its own HttpMessageHandler like in the example above? What are the trade-offs here?
According to this doc https://learn.microsoft.com/en-us/aspnet/core/grpc/performance?view=aspnetcore-8.0#reuse-grpc-channels.
It is better to reuse same channel for multiple clients.