Repository navigation
TCP: replica-aware routing with a ReplicaTag setting - #724
alex-clickhouse wants to merge 7 commits into
Conversation
ClickHouse Cloud sends a native-protocol connection to the replica that its TLS server name (SNI) asks for: <tag>.sticky.<host>. This adds a ReplicaTag setting at three levels: ClickHouseTcpClientOptions (and the ReplicaTag connection-string key), ClickHouseTcpQueryOptions for one operation, and the new ClickHouseTcpSessionOptions for OpenSessionAsync. - The client sends the sticky name as SNI and checks the certificate against the normal host name, because Cloud certificates name <host> and *.<host> only. The chain is checked as usual. - A tag needs TLS and must be one DNS label; other values are refused. - The pool reuses a connection only for the same tag. All tags share MaxPoolSize: a checkout that must open a connection closes the longest-idle connection of another tag when the pool is full. - A session keeps the tag of its connection and refuses an operation with another tag. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g scan - The reuse-policy test puts the connection with another tag where each policy looks first, so the scan must skip it. - Log events 2004 (tagged dial) and 3008 (connection closed for another tag) are asserted. - ClickHouseTcpDataSource.OpenSessionAsync with session options is called through the TLS proxy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AI review gate — AI review passedClean review from: Cursor Bugbot. |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
🟡 Changes recommended
Evicted connections are removed from pool accounting before their sockets close, allowing concurrent tagged checkouts to exceed MaxPoolSize.
2 open issues
What changed in this PR
Adds ClickHouse Cloud replica-aware routing to the native TCP client through ReplicaTag, allowing related operations and sessions to target the same replica. The HTTP client is unchanged.
Changes:
- Adds client, connection-string, operation, and session tag options, with TLS server-name routing and certificate validation.
- Makes connection pooling tag-aware, including eviction under the shared pool limit and new diagnostic events.
- Adds routing tests, documentation, an opt-in Cloud example, and a changelog fragment.
| File | Description |
|---|---|
| examples/Tcp/Connection/Tcp_005_ReplicaRouting.cs | Demonstrates tagged Cloud connections and sessions. |
| examples/README.md | Indexes the routing example. |
| examples/ExampleRunner.cs | Marks the example as opt-in. |
| examples/AGENTS.md | Documents the example’s configuration exemptions. |
| docs/tcp.mdx | Explains tag options, TLS, pooling, and sessions. |
| ClickHouse.Driver.Tcp/PublicAPI/PublicAPI.Unshipped.txt | Records new public options and overloads. |
| ClickHouse.Driver.Tcp/Protocol/TlsParameters.cs | Adds sticky TLS names and certificate-name fallback. |
| ClickHouse.Driver.Tcp/Protocol/ReplicaRouting.cs | Validates tags and constructs routing names. |
| ClickHouse.Driver.Tcp/Protocol/ClickHouseTcpConnection.cs | Passes tags into TLS setup. |
| ClickHouse.Driver.Tcp/Logging/PoolLog.cs | Adds tag-eviction logging. |
| ClickHouse.Driver.Tcp/Logging/ConnectionLog.cs | Adds tagged-connection logging. |
| ClickHouse.Driver.Tcp/Client/PooledConnection.cs | Stores each connection’s tag. |
| ClickHouse.Driver.Tcp/Client/PinnedConnectionSource.cs | Rejects tag changes within sessions. |
| ClickHouse.Driver.Tcp/Client/IConnectionSource.cs | Adds tags to checkout and lease contracts. |
| ClickHouse.Driver.Tcp/Client/IConnectionFactory.cs | Carries tags into connection creation. |
| ClickHouse.Driver.Tcp/Client/IClickHouseTcpDataSource.cs | Exposes session options through the interface. |
| ClickHouse.Driver.Tcp/Client/IClickHouseTcpClient.cs | Declares the session-options overload. |
| ClickHouse.Driver.Tcp/Client/ConnectionPool.cs | Implements tag-matched reuse, eviction, and defaults. |
| ClickHouse.Driver.Tcp/Client/ClickHouseTcpSessionOptions.cs | Introduces session-level replica tags. |
| ClickHouse.Driver.Tcp/Client/ClickHouseTcpQueryOptions.cs | Adds operation-level replica tags. |
| ClickHouse.Driver.Tcp/Client/ClickHouseTcpDataSource.cs | Forwards session options to the client. |
| ClickHouse.Driver.Tcp/Client/ClickHouseTcpConnectionStringBuilder.cs | Parses and exposes ReplicaTag. |
| ClickHouse.Driver.Tcp/Client/ClickHouseTcpClientOptions.cs | Adds and validates the default tag. |
| ClickHouse.Driver.Tcp/Client/ClickHouseTcpClient.cs | Routes operation and session tags into checkout. |
| ClickHouse.Driver.Tcp.Tests/Utilities/TlsTerminatingProxy.cs | Records TLS names and optional client traffic. |
| ClickHouse.Driver.Tcp.Tests/Utilities/PoolTestDoubles.cs | Records tags used to create connections. |
| ClickHouse.Driver.Tcp.Tests/Utilities/ConnectionSourceExtensions.cs | Preserves untagged test checkout shorthand. |
| ClickHouse.Driver.Tcp.Tests/Protocol/TlsParametersTests.cs | Tests tagged TLS names and certificate validation. |
| ClickHouse.Driver.Tcp.Tests/Protocol/ReplicaRoutingTests.cs | Tests tag validation and routing-name construction. |
| ClickHouse.Driver.Tcp.Tests/Integration/TcpServerFixture.cs | Adapts factory calls to accept tags. |
| ClickHouse.Driver.Tcp.Tests/Integration/ReplicaRoutingIntegrationTests.cs | Tests routing across queries, inserts, and sessions. |
| ClickHouse.Driver.Tcp.Tests/Integration/ReplicaRoutingCloudIntegrationTests.cs | Tests replica affinity and distribution on Cloud. |
| ClickHouse.Driver.Tcp.Tests/Integration/CompressionIntegrationTests.cs | Forwards tags through the counting factory. |
| ClickHouse.Driver.Tcp.Tests/Client/TcpConnectionFactoryTests.cs | Updates existing factory calls. |
| ClickHouse.Driver.Tcp.Tests/Client/PinnedConnectionSourceTests.cs | Adds tag metadata to test leases. |
| ClickHouse.Driver.Tcp.Tests/Client/ConnectionPoolReplicaTagTests.cs | Tests tag-aware pooling and session constraints. |
| ClickHouse.Driver.Tcp.Tests/Client/ConnectionPoolLoggingTests.cs | Verifies eviction log events. |
| ClickHouse.Driver.Tcp.Tests/Client/ClickHouseTcpConnectionStringBuilderTests.cs | Tests tag parsing and defaults. |
| ClickHouse.Driver.Tcp.Tests/Client/ClickHouseTcpClientOptionsTests.cs | Extends default, validation, and copying tests. |
| changelog.d/tcp-replica-routing.features.md | Announces TCP replica-aware routing. |
Review effort: Balanced
| while (idle.Count > 0 && AccountedConnections > options.MaxPoolSize) | ||
| { | ||
| (evicted ??= new List<PooledConnection>()).Add(idle[0]); | ||
| idle.RemoveAt(0); |
There was a problem hiding this comment.
Fixed in cbc75d8, with a different approach than "make dials wait".
The cause was the count: idle + leased + pending also counted checkouts that had not yet looked at the idle set. So one checkout could take several idle connections out of the count, and other checkouts then dialed while those sockets were still open.
Now a checkout chooses between reuse and a dial, and takes the connection to close, in one lock. It compares against a count that leaves those checkouts out (CommittedConnections). That count stays within MaxPoolSize: reuse moves a connection from idle to a checkout, and a dial adds one. So a dial closes at most one idle connection. The checkout closes it before it dials, and its own slot covers that socket until it is closed. No dial has to wait.
New tests in ConnectionPoolReplicaTagTests:
RentAsync_ConcurrentCheckoutsOnAFullPool_ClosesOnlyTheConnectionTheNewTagNeeds: 300 rounds.RentAsync_ManyConcurrentCheckoutsWithManyTags_NeverHasMoreThanMaxPoolSizeConnectionsOpen: 20 rounds of 800 checkouts over 7 tags. A connection counts as open from the start of its dial until its socket is closed.
Both pass on the new code. One limit: they did not reliably fail on the previous code either, because a checkout makes its choice in microseconds and the bad interleaving is rare. The fix rests on the count argument above, not on these tests.
| "CreateTableCluster", | ||
| "CreateTableCloud", | ||
| "JwtAuthentication", | ||
| "TcpReplicaRouting", |
There was a problem hiding this comment.
Fixed in cbc75d8: TcpReplicaRouting is now in _customEndpoint as well as _optIn. examples/AGENTS.md now says that an opt-in example with its own endpoint goes in both. Checked locally with no server on port 9000: dotnet run -- --filter TcpReplicaRouting reaches the example and prints its message about the missing Cloud variables.
|
This PR adds replica-aware routing to the native TCP client through client and session replica tags, with TLS hostname validation and dedicated connections for session overrides. No actionable findings remain in the current snapshot. The previously reported Cloud example preflight issue is fixed. ✅ Approve based on static review; builds, tests, and live Cloud routing were not independently run in this sandbox. Final verdict✅ Approve Automated review by Polyglot AI (gpt-6-astra) of |
The pool decided whether a dial must first close an idle connection of another tag from idle + leased + pending. `pending` also counts checkouts that have not yet looked at the idle set, so one checkout could close connections that others were about to reuse, and the closed sockets left the count before they were closed. A checkout now chooses between reuse and a dial, and takes the connection to close, in one lock against a count that leaves those checkouts out. That count stays within MaxPoolSize, so a dial closes at most one connection, and closes it before it dials. - Tests: concurrent checkouts on a full pool close only the connection the new tag needs; many concurrent checkouts over many tags never have more than MaxPoolSize connections open; the TLS name fallback refuses a mismatch without a certificate. - Example: TcpReplicaRouting is a custom-endpoint example, so a filtered run does not check the local endpoint first. - Docs: a tag chooses a replica, not a connection, so temporary tables need a session; MinPoolSize with other tags; certificate wording; ConfigureTls with a tag. Shorter changelog entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It must leave both `pending` and `undecided` and release its slot, or the drain waits out PoolTimeout. Also name the changelog fragment after the pull request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Remove ClickHouseTcpQueryOptions.ReplicaTag. A per-operation tag made the pool keep connections with many tags in one idle set, search that set by tag, and count undecided checkouts to keep MaxPoolSize. Now every pooled connection has the client's tag. A session with another tag gets a new connection that only it uses; the pool never puts that connection in the idle set. When the pool is full, the session dial first closes the longest-idle connection. A connection the pool does not keep is closed before it leaves the leased set, so that count never misses an open socket. Remove the docs sections on how the client sends the tag and on pooling with tags. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eplica-routing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Docs drift check: this PR looks like it needs doc updates.
|
There was a problem hiding this comment.
Auto-approved by the AI review gate on c911486. Details in the approver's comment on this pull request.
AI review gate — auto-approved
History (latest 5 heads, newest first)
|


Summary
Adds replica-aware routing for ClickHouse Cloud to the native TCP client, as a
ReplicaTagsetting.What. A replica tag can be set in two places:
ClickHouseTcpClientOptions.ReplicaTag, orReplicaTag=in the connection string. Every pooled connection of the client uses it.ClickHouseTcpSessionOptions.ReplicaTag, through a newOpenSessionAsync(ClickHouseTcpSessionOptions, CancellationToken)overload on the client, the data source and their interfaces.A session tag replaces the client tag. Null or empty means the client tag. There is no tag per operation: to run work on one replica, set the client tag or open a session with a tag.
How.
<tag>.sticky.<host>. The client still dialsHost. This is whatclickhouse-client --tls-sni-overridedoes.SslClientAuthenticationOptions.TargetHostfor the SNI and for the certificate name check. A certificate for the service host does not cover the sticky name (a wildcard covers one label). So a tagged connection sets the sticky name asTargetHostand installs a validation callback that accepts the certificate when it names the sticky name, or when its only fault is that it names the normal host (X509Certificate2.MatchesHostname). Chain errors still refuse it. The pinned-CA chain policy,TlsAllowInvalidCertificatesand theConfigureTlshook work as before.UseTlsand a DNS host name, and must be one DNS label (1-63 characters,A-Z a-z 0-9 -). Other values are refused withArgumentException, so the same string reaches the same replica as withclickhouse-client. The client tag is checked at construction, a session tag before the checkout takes a permit.MinPoolSizework as before.PooledConnection.Dedicated), and the pool never puts that connection back in the idle set. Idle connections hold no permit, so when the pool is full the session first closes the longest-idle connection, and dials only after that.Returncloses a connection that it does not keep before it removes it from the leased set. Otherwise the socket is in no counted set while it closes, and a session dial at that moment sees one socket too few. This also covers ordinary connections that come back expired or broken.Why. Requests that must reach one replica (read your own writes before the other replicas catch up, cache reuse, data that only one replica has) had no first-class way to do it on the native protocol. A tag chooses a replica, not a connection: temporary tables and
SETsettings still need a session. The HTTP client can already send theX-ClickHouse-Replica-Tagheader withCustomHeaders, so this PR does not change the HTTP client.An earlier version of this PR also had a tag per operation. That needed a pool that keeps connections with many tags in one idle set, searches it by tag and counts undecided checkouts to keep
MaxPoolSize. It was removed to keep the pool simple.Tests
ReplicaRoutingTests); SNI that the server receives and which certificates are accepted or refused with a tag, against an in-process TLS server (TlsParametersTests). Pool (ConnectionPoolReplicaTagTests): the client tag is used and reused; a session tag opens a new connection and leaves idle ones alone; its connection is closed on return; the longest-idle connection is closed when the pool is full; a pool full of leased connections makes the session wait; a connection thatReturncloses stays counted while a session dials (deterministic); 800 concurrent checkouts, half with session tags, never have more thanMaxPoolSizeconnections open; top-up tag; invalid tags; sessions. Log event 3008.TlsTerminatingProxyrecords the SNI of each connection and, on request, the plaintext the client sent. The tests find the connection that carried each query id and check its SNI: client tag, no tag, connection string, log event 2004, the data source overload, a session with its own tag that keeps a temporary table while the client uses its tag, and a session without a tag that uses the client tag. The proxy certificate names only the normal host, as a Cloud certificate does.ReplicaRoutingCloudIntegrationTests,[Category("Cloud")], ignored outside Cloud):MaxPoolSize2).ClickHouse.Driver.Tcp.Testsafter mergingmain(TCP: report the driver version, not 0.0.0, so distributed queries work #725): net9.0 and net10.0 4254 passed, 6 skipped (the Cloud tests); net8.0 also passed before the merge. No new build warnings. No RS public API diagnostics.changelog.cs --checkOK.Checklist
🤖 Generated with Claude Code
Note
Medium Risk
Touches TLS validation, connection pooling concurrency, and public API (
ReplicaTag, session options); incorrect pool or cert logic could cause wrong-replica routing or connection leaks, but changes are heavily tested.Overview
Adds replica-aware routing for the native TCP client on ClickHouse Cloud via a new
ReplicaTagonClickHouseTcpClientOptionsand connection strings, plusClickHouseTcpSessionOptionsforOpenSessionAsyncoverloads.Tagged TLS connections send SNI as
<tag>.sticky.<host>(implemented inReplicaRoutingandTlsParameters) while still validating certificates against the normal host name. The connection pool opens and reuses connections per client tag; sessions with a different tag get dedicated connections that are closed on return, and may evict the longest-idle connection when atMaxPoolSize. Factory APIs now passreplicaTagthrough dial/handshake.Includes docs, changelog, a Cloud-only example, and broad unit/integration/Cloud tests for validation, TLS, pooling, and routing behavior.
Reviewed by Cursor Bugbot for commit c911486. Bugbot is set up for automated code reviews on this repo. Configure here.