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?
I ended up "modifying" the HttpMessageHandler instead of adding/replacing one.
This approach feels better as its not invasive in how Grpc.Net.ClientFactory is taking care of the grpcChannel and the underlying http connections and that default chain of HttpMessageHandler is preserved.
This approach however assumes that the final http handler is always the SocketsHttpHandler.