: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(clickhouse): retry 429 rate limit during connect inline (#71735)
Tom Owerse1fece5e88ac
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.pyindex 80843482b08f..a36150d3b82b 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@@ -135,12 +135,21 @@ def _is_transient_connect_drop(error_message: str) -> bool:# slow down. A 429 is explicitly "retry later", so a brief backed-off re-attempt# often clears a short rate-limit burst; if it doesn't, the failing Temporal# activity stays retryable and recovers later. We match only 429 — other 4xx-# response codes are deterministic (e.g. 404 stays non-retryable).+# response codes are deterministic (e.g. 404 stays non-retryable). Matching the+# stable status phrase keeps the volatile per-request URL out of the comparison._TRANSIENT_RATE_LIMIT_SUBSTRING = "returned response code 429"+# Backoff base between connect retries after a 429. Longer than the connect-drop+# retry (which just re-dials) to give the rate limit room to clear.+_RATE_LIMIT_BACKOFF_BASE_SECONDS = 2+++def _is_rate_limited(error_message: str) -> bool:+ return _TRANSIENT_RATE_LIMIT_SUBSTRING in error_message+def _is_retryable_connect_error(error_message: str) -> bool:- return _is_transient_connect_drop(error_message) or _TRANSIENT_RATE_LIMIT_SUBSTRING in error_message+ return _is_transient_connect_drop(error_message) or _is_rate_limited(error_message)def _apply_session_settings(client: ClickHouseClient, settings: dict[str, Any]) -> None:@@ -209,13 +218,18 @@ def _get_client(attempt += 1message = 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 attemptstructlog.get_logger().warning("Transient ClickHouse connect error; retrying",attempt=attempt,max_attempts=_MAX_CONNECT_ATTEMPTS,+ wait_seconds=wait,exc_info=e,)- time.sleep(attempt)+ time.sleep(wait)continueraise ClickHouseConnectionError(message) from ediff --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.pyindex 4f4f6c56fd6a..67f94cc0bb8b 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@@ -2,7 +2,7 @@ from collections.abc import AsyncIterableimport pytestfrom posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchimport pyarrow as pafrom clickhouse_connect.driver.exceptions import ClickHouseError, OperationalError, ProgrammingError@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse_get_incremental_row_count,_get_partition_settings,_has_duplicate_primary_keys,+ _is_rate_limited,_is_transient_connect_drop,_parse_mv_target,_project_columns,@@ -716,6 +717,30 @@ class TestIsTransientConnectDrop:assert not _is_transient_connect_drop(message)+class TestIsRateLimited:+ @pytest.mark.parametrize(+ "message",+ [+ "HTTPDriver for https://host:8443 returned response code 429",+ "Error ... HTTPDriver for https://host:443 returned response code 429 executing HTTP request",+ ],+ )+ def test_matches_429(self, message):+ assert _is_rate_limited(message)++ @pytest.mark.parametrize(+ "message",+ [+ # Other response codes have their own handling and must not match 429.+ "HTTPDriver for https://host:8443 returned response code 404",+ "HTTPDriver for https://host:8443 returned response code 502",+ "Code: 516. DB::Exception: Authentication failed",+ ],+ )+ def test_does_not_match_other_codes(self, message):+ assert not _is_rate_limited(message)++class TestGetClientTransientRetry:"""`_get_client` retries a transient connection drop during connect in-process."""@@ -756,15 +781,18 @@ class TestGetClientTransientRetry:self._connect()assert mock_get_client.call_count == _MAX_CONNECT_ATTEMPTS- def test_retries_rate_limit_then_succeeds(self):+ def test_rate_limit_backs_off_exponentially(self):+ # A 429 backs off exponentially (base 2) to give the rate limit room to+ # clear, unlike a connect drop which just re-dials on a short linear wait.client = MagicMock()rate_limited = OperationalError("HTTPDriver for https://host:8443 returned response code 429")with (- patch.object(ch_module.time, "sleep"),- patch.object(ch_module, "get_client", side_effect=[rate_limited, client]) as mock_get_client,+ patch.object(ch_module.time, "sleep") as mock_sleep,+ patch.object(ch_module, "get_client", side_effect=[rate_limited, rate_limited, client]) as mock_get_client,):assert self._connect() is client- assert mock_get_client.call_count == 2+ 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")