Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(clickhouse): retry connect-time query-limit rejections with backoff (#81770)

Tom Owers5601db437518
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py
index a02ab458985d..03b7d40240b7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/clickhouse.py
@@ -176,8 +176,25 @@ def _is_rate_limited(error_message: str) -> bool:
return _TRANSIENT_RATE_LIMIT_SUBSTRING in error_message
+# The source server's own concurrency limit ("Code: 202. DB::Exception: Too many
+# simultaneous queries for all users. Current: N, maximum: N. (TOO_MANY_SIMULTANEOUS_QUERIES)")
+# rejects even the client-construction probe query when the server is already at capacity.
+# Like a 429, this is the server asking us to back off, not a config error, and it clears on
+# its own as other queries finish — so a backed-off retry recovers it the same way. The
+# "Current"/"maximum" counts are volatile; the ClickHouse error-code name is stable.
+_TRANSIENT_TOO_MANY_QUERIES_SUBSTRING = "TOO_MANY_SIMULTANEOUS_QUERIES"
+
+
+def _is_too_many_queries(error_message: str) -> bool:
+ return _TRANSIENT_TOO_MANY_QUERIES_SUBSTRING in error_message
+
+
def _is_retryable_connect_error(error_message: str) -> bool:
- return _is_transient_connect_drop(error_message) or _is_rate_limited(error_message)
+ return (
+ _is_transient_connect_drop(error_message)
+ or _is_rate_limited(error_message)
+ or _is_too_many_queries(error_message)
+ )
def _apply_session_settings(client: ClickHouseClient, settings: dict[str, Any]) -> None:
@@ -349,10 +366,15 @@ def _get_client(
attempt += 1
message = str(e)
if attempt < _MAX_CONNECT_ATTEMPTS and _is_retryable_connect_error(message):
- # A 429 is the server asking us to slow down, so back off
- # exponentially to give the rate limit room to clear; a dropped
- # connection just needs a re-dial, so a short linear wait is enough.
- wait = _RATE_LIMIT_BACKOFF_BASE_SECONDS * (2 ** (attempt - 1)) if _is_rate_limited(message) else attempt
+ # A 429 or a too-many-queries rejection is the server asking us to
+ # slow down, so back off exponentially to give it room to clear; a
+ # dropped connection just needs a re-dial, so a short linear wait
+ # is enough.
+ wait = (
+ _RATE_LIMIT_BACKOFF_BASE_SECONDS * (2 ** (attempt - 1))
+ if _is_rate_limited(message) or _is_too_many_queries(message)
+ else attempt
+ )
structlog.get_logger().warning(
"Transient ClickHouse connect error; retrying",
attempt=attempt,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
index c81e64964abd..0d3b5f405472 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py
@@ -354,6 +354,12 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val
# (a slow-to-wake service needs real wall-clock time, not an immediate re-dial);
# Temporal's activity retry provides that backoff and reopens a fresh connection.
"Read timed out",
+ # The source server rejected the client-construction probe because it was already
+ # at its concurrent-query limit (Code: 202, TOO_MANY_SIMULTANEOUS_QUERIES).
+ # `_get_client` already backs off and retries this in-process like a 429; this
+ # entry covers the case where the server stays saturated past all in-process
+ # attempts, so Temporal's own retry — with a fresh backoff budget — isn't noise.
+ "TOO_MANY_SIMULTANEOUS_QUERIES",
}
@contextmanager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py
index 6c2809186c8d..19cbc01c3a1d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/test_clickhouse.py
@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse
_get_partition_settings,
_has_duplicate_primary_keys,
_is_rate_limited,
+ _is_too_many_queries,
_is_transient_connect_drop,
_parse_mv_target,
_project_columns,
@@ -733,6 +734,11 @@ class TestClickHouseSourceRetryableErrors:
# typically ClickHouse Cloud still cold-resuming past our allowance.
"Error HTTPSConnectionPool(host='play.clickhouse.com', port=8443): Read timed out. "
"(read timeout=120) executing HTTP request attempt 1 (https://play.clickhouse.com:8443)",
+ # The source server was already at its concurrent-query limit when the
+ # client-construction probe ran; the exact wrapped message reached error tracking.
+ "HTTPDriver for https://play.clickhouse.com:8443 received ClickHouse error code 202\n "
+ "Code: 202. DB::Exception: Too many simultaneous queries for all users. Current: 500, "
+ "maximum: 500. (TOO_MANY_SIMULTANEOUS_QUERIES) (version 24.8.1.1 (official build))",
],
)
def test_transient_errors_are_retryable(self, source, error_msg):
@@ -816,6 +822,32 @@ class TestIsRateLimited:
assert not _is_rate_limited(message)
+class TestIsTooManyQueries:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Code: 202. DB::Exception: Too many simultaneous queries for all users. Current: 500, "
+ "maximum: 500. (TOO_MANY_SIMULTANEOUS_QUERIES)",
+ "HTTPDriver for https://host:8443 received ClickHouse error code 202\n "
+ "Code: 202. DB::Exception: Too many simultaneous queries for all users. Current: 100, "
+ "maximum: 100. (TOO_MANY_SIMULTANEOUS_QUERIES) (version 24.8.1.1 (official build))",
+ ],
+ )
+ def test_matches_too_many_queries(self, message):
+ assert _is_too_many_queries(message)
+
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Code: 241. DB::Exception: Memory limit exceeded",
+ "HTTPDriver for https://host:8443 returned response code 429",
+ "Code: 516. DB::Exception: Authentication failed",
+ ],
+ )
+ def test_does_not_match_other_codes(self, message):
+ assert not _is_too_many_queries(message)
+
+
class TestGetClientTransientRetry:
"""`_get_client` retries a transient connection drop during connect in-process."""
@@ -869,6 +901,24 @@ class TestGetClientTransientRetry:
assert mock_get_client.call_count == 3
mock_sleep.assert_has_calls([call(2), call(4)])
+ def test_retries_connect_time_too_many_queries_then_succeeds(self):
+ # The client-construction probe itself can be rejected when the source server is
+ # already at its concurrent-query limit; we retry it with the same backoff as a 429.
+ client = MagicMock()
+ too_many_queries = OperationalError(
+ "Code: 202. DB::Exception: Too many simultaneous queries for all users. Current: 500, "
+ "maximum: 500. (TOO_MANY_SIMULTANEOUS_QUERIES)"
+ )
+ with (
+ patch.object(ch_module.time, "sleep") as mock_sleep,
+ patch.object(
+ ch_module, "get_client", side_effect=[too_many_queries, too_many_queries, client]
+ ) as mock_get_client,
+ ):
+ assert self._connect() is client
+ assert mock_get_client.call_count == 3
+ mock_sleep.assert_has_calls([call(2), call(4)])
+
def test_does_not_retry_deterministic_failure(self):
cert_error = ClickHouseError("certificate verify failed")
with (