Connection lifetime & pooling - DarkWanderer/ClickHouse.Client GitHub Wiki

Overview

ClickHouse.Client uses System.Net.Http.HttpClient under the hood. HttpClient has a per-endpoint connection pool. As a consequence:

  • a ClickHouseConnection object does not have 1:1 mapping to TCP connections - multiple database sessions will be multiplexed through several (2 by default) TCP connections per server
  • connections can stay alive after ClickHouseConnection object was disposed
  • this behavior can be tweaked by passing a bespoke HttpClient with custom HttpClientHandler

For DI environments, there is a bespoke constructor ClickHouseConnection(string connectionString, IHttpClientFactory httpClientFactory, string httpClientName = "") which allows to generalize HTTP client settings

Recommendations

  • A ClickHouseConnection represents a "session" with the server. It performs feature discovery by querying server version (so there is a minor overhead on opening), but generally it is safe to create and destroy such objects multiple times
  • Recommended lifetime for a connection is one connection object per large "transaction" spanning multiple queries. There is a minor overhead on connection startup, so it's not recommended to create a connection object for each query
  • If an application operates on large volumes of transactions and requires to create/destroy ClickHouseConnection objects often, it is recommended to use IHttpClientFactory or a static instance of HttpClient to manage connections

See also