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): honor Retry-After on token-refresh rate limits (#64726)

Tom Owers4aa37bc6c11f
diff --git a/posthog/temporal/data_imports/sources/hubspot/auth.py b/posthog/temporal/data_imports/sources/hubspot/auth.py
index fdff30f094de..f49a3a7c3087 100644
--- a/posthog/temporal/data_imports/sources/hubspot/auth.py
+++ b/posthog/temporal/data_imports/sources/hubspot/auth.py
@@ -2,17 +2,46 @@ from django.conf import settings
import requests
import structlog
-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
logger = structlog.get_logger(__name__)
+# Cap how long a single Retry-After can stall the token refresh, so a misbehaving
+# header can't pin the activity open.
+MAX_RETRY_AFTER_SECONDS = 60
+# Stateless backoff used when a 429 carries no Retry-After hint (or for 5xx).
+_FALLBACK_WAIT = wait_exponential_jitter(initial=1, max=30)
+
class HubspotRetryableError(Exception):
"""Transient HubSpot API failure (429 rate limit or 5xx) that should be retried with backoff."""
- pass
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ # Seconds HubSpot asked us to wait (from a 429 Retry-After), if any.
+ self.retry_after = retry_after
+
+
+def _parse_retry_after(res: requests.Response) -> float | None:
+ """HubSpot sends Retry-After as delta-seconds on 429s; ignore other (non-numeric) forms."""
+ raw = res.headers.get("Retry-After")
+ if raw is None:
+ return None
+ try:
+ seconds = float(raw)
+ except (TypeError, ValueError):
+ return None
+ return max(0.0, seconds)
+
+
+def _wait_strategy(retry_state: RetryCallState) -> float:
+ """Honor a 429's Retry-After when present, else fall back to jittered backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome is not None else None
+ if isinstance(exc, HubspotRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_AFTER_SECONDS)
+ return _FALLBACK_WAIT(retry_state)
def _error_message_from_response(res: requests.Response) -> str:
@@ -30,7 +59,7 @@ def _error_message_from_response(res: requests.Response) -> str:
# 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),
+ wait=_wait_strategy,
reraise=True,
)
def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = None) -> str:
@@ -50,7 +79,8 @@ def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = Non
# 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)
+ retry_after = _parse_retry_after(res) if res.status_code == 429 else None
+ raise HubspotRetryableError(err_message, retry_after=retry_after)
raise Exception(err_message)
access_token = res.json()["access_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.py
index a4ede04fbf27..048807ccc405 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
@@ -3,13 +3,22 @@ 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
+from posthog.temporal.data_imports.sources.hubspot.auth import (
+ MAX_RETRY_AFTER_SECONDS,
+ HubspotRetryableError,
+ _parse_retry_after,
+ _wait_strategy,
+ hubspot_refresh_access_token,
+)
-def _make_response(status: int, payload: dict[str, Any] | None = None) -> MagicMock:
+def _make_response(
+ status: int, payload: dict[str, Any] | None = None, headers: dict[str, str] | None = None
+) -> MagicMock:
response = MagicMock()
response.status_code = status
response.json.return_value = payload or {}
+ response.headers = headers or {}
return response
@@ -65,6 +74,7 @@ def test_transient_status_with_non_json_body_still_retryable() -> None:
response.status_code = 429
response.json.side_effect = ValueError("not json")
response.text = "<html>rate limited</html>"
+ response.headers = {}
with _patch_post(response):
with pytest.raises(HubspotRetryableError, match="rate limited"):
hubspot_refresh_access_token("refresh-token")
@@ -126,3 +136,46 @@ def test_non_transient_status_is_not_retried() -> None:
hubspot_refresh_access_token("refresh-token")
assert not isinstance(exc_info.value, HubspotRetryableError)
assert session.post.call_count == 1
+
+
+ "headers,expected",
+ [
+ ({"Retry-After": "7"}, 7.0),
+ ({"Retry-After": "0"}, 0.0),
+ ({"Retry-After": "-3"}, 0.0),
+ ({}, None),
+ ({"Retry-After": "not-a-number"}, None),
+ ({"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"}, None),
+ ],
+)
+def test_parse_retry_after(headers: dict[str, str], expected: float | None) -> None:
+ assert _parse_retry_after(_make_response(429, headers=headers)) == expected
+
+
+def test_429_retry_after_carried_on_exception_and_capped_by_wait_strategy() -> None:
+ session = MagicMock()
+ session.post.return_value = _make_response(
+ 429,
+ {"message": "You have reached your rate limit."},
+ headers={"Retry-After": str(MAX_RETRY_AFTER_SECONDS + 30)},
+ )
+ with patch(
+ "posthog.temporal.data_imports.sources.hubspot.auth.make_tracked_session",
+ return_value=session,
+ ):
+ with pytest.raises(HubspotRetryableError) as exc_info:
+ hubspot_refresh_access_token("refresh-token")
+
+ assert exc_info.value.retry_after == MAX_RETRY_AFTER_SECONDS + 30
+ # An oversized Retry-After is clamped so a single header can't pin the activity open.
+ state = MagicMock()
+ state.outcome.exception.return_value = exc_info.value
+ assert _wait_strategy(state) == MAX_RETRY_AFTER_SECONDS
+
+
+def test_wait_strategy_falls_back_to_backoff_without_retry_after() -> None:
+ state = MagicMock()
+ state.outcome.exception.return_value = HubspotRetryableError("rate limited", retry_after=None)
+ state.attempt_number = 1
+ assert _wait_strategy(state) >= 0