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(hubspot): retry token-refresh rate limits instead of failing sync (#63732)

Tom Owers0477ce021afd
diff --git a/posthog/temporal/data_imports/sources/hubspot/auth.py b/posthog/temporal/data_imports/sources/hubspot/auth.py
index 66081af46ff0..fdaa670234c6 100644
--- a/posthog/temporal/data_imports/sources/hubspot/auth.py
+++ b/posthog/temporal/data_imports/sources/hubspot/auth.py
@@ -1,5 +1,6 @@
from django.conf import settings
+import requests
import structlog
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
@@ -7,6 +8,20 @@ from posthog.temporal.data_imports.sources.common.http import make_tracked_sessi
logger = structlog.get_logger(__name__)
+class HubspotRetryableError(Exception):
+ """Transient HubSpot API failure (429 rate limit or 5xx) that should be retried with backoff."""
+
+ pass
+
+
+def _error_message_from_response(res: requests.Response) -> str:
+ """Best-effort extraction of HubSpot's error message, tolerant of non-JSON or message-less bodies."""
+ try:
+ return res.json()["message"]
+ except Exception:
+ return res.text
+
+
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",
@@ -19,7 +34,12 @@ def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = Non
)
if res.status_code != 200:
- err_message = res.json()["message"]
+ err_message = _error_message_from_response(res)
+ # A 429 (rate limit) or 5xx from the OAuth token endpoint is transient. Surface it as a
+ # retryable error so the calling fetch loop backs off and retries instead of failing the
+ # whole sync on a momentary rate limit.
+ if res.status_code == 429 or res.status_code >= 500:
+ raise HubspotRetryableError(err_message)
raise Exception(err_message)
access_token = res.json()["access_token"]
diff --git a/posthog/temporal/data_imports/sources/hubspot/hubspot.py b/posthog/temporal/data_imports/sources/hubspot/hubspot.py
index 7bcd699de105..a678369257fe 100644
--- a/posthog/temporal/data_imports/sources/hubspot/hubspot.py
+++ b/posthog/temporal/data_imports/sources/hubspot/hubspot.py
@@ -28,7 +28,7 @@ from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from posthog.temporal.data_imports.sources.hubspot.auth import hubspot_refresh_access_token
+from posthog.temporal.data_imports.sources.hubspot.auth import HubspotRetryableError, hubspot_refresh_access_token
from posthog.temporal.data_imports.sources.hubspot.helpers import BASE_URL, _get_headers, _get_property_names
from posthog.temporal.data_imports.sources.hubspot.settings import (
ASSOCIATIONS_BATCH_SIZE,
@@ -48,10 +48,6 @@ SEARCH_PROPERTIES_LIMIT = 250
WINDOW_SIZE_MS = SEARCH_WINDOW_DAYS * 24 * 60 * 60 * 1000
-class HubspotRetryableError(Exception):
- pass
-
-
class HubspotPathologicalWindowError(Exception):
"""Raised when a single cursor-ms value has >SEARCH_RESULT_CAP records and the window
cannot be sub-divided further. Extremely unlikely in practice for HubSpot CRM data."""
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.py
new file mode 100644
index 000000000000..cb755abd291e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/hubspot/test/test_hubspot_auth.py
@@ -0,0 +1,78 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.temporal.data_imports.sources.hubspot.auth import HubspotRetryableError, hubspot_refresh_access_token
+
+
+def _make_response(status: int, payload: dict[str, Any] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.json.return_value = payload or {}
+ return response
+
+
+def _patch_post(response: MagicMock) -> Any:
+ session = MagicMock()
+ session.post.return_value = response
+ return patch(
+ "posthog.temporal.data_imports.sources.hubspot.auth.make_tracked_session",
+ return_value=session,
+ )
+
+
+ "status,message",
+ [
+ (429, "You have reached your rate limit."),
+ (500, "Internal server error"),
+ (502, "Bad gateway"),
+ (503, "Service unavailable"),
+ ],
+)
+def test_transient_status_raises_retryable_error(status: int, message: str) -> None:
+ with _patch_post(_make_response(status, {"message": message})):
+ with pytest.raises(HubspotRetryableError, match=message):
+ hubspot_refresh_access_token("refresh-token")
+
+
+ "status,message",
+ [
+ (400, "missing or invalid refresh token"),
+ (401, "unauthorized"),
+ (403, "forbidden"),
+ ],
+)
+def test_non_transient_status_raises_plain_exception(status: int, message: str) -> None:
+ with _patch_post(_make_response(status, {"message": message})):
+ with pytest.raises(Exception) as exc_info:
+ hubspot_refresh_access_token("refresh-token")
+ assert not isinstance(exc_info.value, HubspotRetryableError)
+ assert message in str(exc_info.value)
+
+
+def test_transient_status_with_non_json_body_still_retryable() -> None:
+ response = MagicMock()
+ response.status_code = 429
+ response.json.side_effect = ValueError("not json")
+ response.text = "<html>rate limited</html>"
+ with _patch_post(response):
+ with pytest.raises(HubspotRetryableError, match="rate limited"):
+ hubspot_refresh_access_token("refresh-token")
+
+
+def test_transient_status_with_message_less_body_still_retryable() -> None:
+ response = MagicMock()
+ response.status_code = 503
+ response.json.return_value = {"error": "unavailable"}
+ response.text = "service unavailable"
+ with _patch_post(response):
+ with pytest.raises(HubspotRetryableError, match="service unavailable"):
+ hubspot_refresh_access_token("refresh-token")
+
+
+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"