: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(hubspot): back off and retry token refresh on rate limit (#64178)
Tom Owersae42f531d793
diff --git a/posthog/temporal/data_imports/sources/hubspot/auth.py b/posthog/temporal/data_imports/sources/hubspot/auth.pyindex fdaa670234c6..fdff30f094de 100644--- a/posthog/temporal/data_imports/sources/hubspot/auth.py+++ b/posthog/temporal/data_imports/sources/hubspot/auth.py@@ -2,6 +2,7 @@ from django.conf import settingsimport requestsimport structlog+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom posthog.temporal.data_imports.sources.common.http import make_tracked_session@@ -22,6 +23,16 @@ def _error_message_from_response(res: requests.Response) -> str:return res.text+@retry(+ # A 429/5xx from HubSpot's OAuth token endpoint is transient. The data-fetch paths already+ # back off and retry on HubspotRetryableError; this refresh is also reached at source-setup+ # time (and from helpers.fetch_data), where no surrounding retry exists — so back off here too+ # instead of failing the whole sync on a momentary rate limit.+ retry=retry_if_exception_type((HubspotRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = None) -> str:res = make_tracked_session().post("https://api.hubapi.com/oauth/v1/token",diff --git a/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_auth.py b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_auth.pyindex cb755abd291e..c14a8bdd2ae6 100644--- a/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_auth.py+++ b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_auth.py@@ -22,6 +22,13 @@ def _patch_post(response: MagicMock) -> Any:)[email protected](autouse=True)+def _no_backoff_sleep() -> Any:+ # hubspot_refresh_access_token backs off on transient errors; skip the real waits in tests.+ with patch("time.sleep"):+ yield++@pytest.mark.parametrize("status,message",[@@ -76,3 +83,32 @@ def test_transient_status_with_message_less_body_still_retryable() -> None:def test_success_returns_access_token() -> None:with _patch_post(_make_response(200, {"access_token": "new-token"})):assert hubspot_refresh_access_token("refresh-token") == "new-token"+++def test_transient_status_is_retried_then_succeeds() -> None:+ # A momentary rate limit on the token endpoint should back off and retry rather than+ # fail the whole sync; once HubSpot stops returning 429 the refresh succeeds.+ session = MagicMock()+ session.post.side_effect = [+ _make_response(429, {"message": "You have reached your rate limit."}),+ _make_response(429, {"message": "You have reached your rate limit."}),+ _make_response(200, {"access_token": "new-token"}),+ ]+ with patch(+ "posthog.temporal.data_imports.sources.hubspot.auth.make_tracked_session",+ return_value=session,+ ):+ assert hubspot_refresh_access_token("refresh-token") == "new-token"+ assert session.post.call_count == 3+++def test_transient_status_reraises_after_exhausting_retries() -> None:+ session = MagicMock()+ session.post.return_value = _make_response(429, {"message": "You have reached your rate limit."})+ with patch(+ "posthog.temporal.data_imports.sources.hubspot.auth.make_tracked_session",+ return_value=session,+ ):+ with pytest.raises(HubspotRetryableError, match="You have reached your rate limit."):+ hubspot_refresh_access_token("refresh-token")+ assert session.post.call_count == 5