: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(intercom): ride out 429 rate limits on substream fetches (#68832)
Tom Owersbb425fdbae46
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.pyindex c6adf43bab2b..baf56424f38c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/intercom.py@@ -251,16 +251,75 @@ def _resolve_intercom_url(path_or_url: str) -> str:return path_or_url if path_or_url.startswith("http") else f"{INTERCOM_API_BASE}{path_or_url}"+def _is_rate_limited(exc: HTTPError) -> bool:+ """Intercom rate-limits per workspace and returns `429` once the window is+ exhausted. It's transient — the counter resets on a short rolling window —+ so retrying after a wait clears it. Match on the status, not the URL."""+ resp = exc.response+ return resp is not None and resp.status_code == 429+++def _rate_limit_backoff_seconds(resp: Response, default: float) -> float:+ """Honor Intercom's `Retry-After` (seconds) on a 429 when present, else fall+ back to `default`. Intercom sends `Retry-After` on some 429s and always sends+ `X-RateLimit-Reset`, but a fixed window-sized fallback rides out the bucket+ regardless, so we key off the simpler signal."""+ raw = resp.headers.get("Retry-After")+ if raw is None:+ return default+ try:+ return max(float(raw), 0.0)+ except (TypeError, ValueError):+ return default+++# Intercom's default limit is 1000 requests/minute, metered in ~10s buckets, so a+# burst of per-row substream fetches (one GET per company/conversation) can exhaust+# one bucket and get 429ed. The shared transport retry lists 429 but backs off at+# most ~2s across its attempts — shorter than the bucket window — so a rate-limited+# burst surfaces and Temporal re-walks the whole activity. Wait out a bucket inline+# and retry, capped so sustained pressure still surfaces instead of looping forever.+_RATE_LIMIT_BACKOFF_SECONDS = 10.0+_RATE_LIMIT_MAX_RETRIES = 3+++def _request_with_rate_limit_retry(do_request: Callable[[], Response]) -> dict[str, Any]:+ """Run an Intercom request, riding out a transient 429 rate limit inline.++ `do_request` performs the call and raises `HTTPError` on a non-2xx. On a 429+ we back off (honoring `Retry-After` when Intercom sends it) and retry the same+ request, which is safe: every Intercom call routed through here is a read."""+ for attempt in range(_RATE_LIMIT_MAX_RETRIES + 1):+ try:+ return do_request().json()+ except HTTPError as exc:+ resp = exc.response+ if _is_rate_limited(exc) and resp is not None and attempt < _RATE_LIMIT_MAX_RETRIES:+ wait = _rate_limit_backoff_seconds(resp, _RATE_LIMIT_BACKOFF_SECONDS)+ logger.warning("intercom_rate_limited_retry", attempt=attempt + 1, backoff_seconds=wait)+ time.sleep(wait)+ continue+ raise+ # Unreachable: the final attempt either returns or re-raises above.+ raise AssertionError("unreachable")++def _intercom_get(session: Session, path_or_url: str, params: dict[str, Any] | None = None) -> dict[str, Any]:- response = session.get(_resolve_intercom_url(path_or_url), params=params, timeout=30)- response.raise_for_status()- return response.json()+ def do() -> Response:+ response = session.get(_resolve_intercom_url(path_or_url), params=params, timeout=30)+ response.raise_for_status()+ return response++ return _request_with_rate_limit_retry(do)def _intercom_post(session: Session, path_or_url: str, body: dict[str, Any]) -> dict[str, Any]:- response = session.post(_resolve_intercom_url(path_or_url), json=body, timeout=30)- response.raise_for_status()- return response.json()+ def do() -> Response:+ response = session.post(_resolve_intercom_url(path_or_url), json=body, timeout=30)+ response.raise_for_status()+ return response++ return _request_with_rate_limit_retry(do)def _iter_conversations(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.pyindex 888aa23eef10..85b57334aca1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/intercom/tests/test_intercom.py@@ -23,10 +23,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.intercom.i_company_segments_generator,_conversation_parts_generator,_drain_company_ids,+ _intercom_get,+ _is_rate_limited,_is_scroll_exists,_is_server_error,_iter_companies,_make_intercom_session,+ _rate_limit_backoff_seconds,get_resource,intercom_source,validate_credentials,@@ -580,6 +583,68 @@ class TestCompaniesScrollServerError:assert mock_session.get.call_count == intercom_module._SCROLL_SERVER_ERROR_MAX_RETRIES + 2+class TestRateLimitRetry:+ @pytest.mark.parametrize(+ "status_code,expected",+ [+ (429, True),+ (400, False),+ (404, False),+ (500, False),+ (200, False),+ ],+ )+ def test_is_rate_limited(self, status_code: int, expected: bool):+ assert _is_rate_limited(_http_error(None, status_code=status_code, text="boom")) is expected++ def test_backoff_honors_retry_after_header(self):+ resp = _make_response(None, status_code=429, text="Too Many Requests")+ resp.headers["Retry-After"] = "7"+ assert _rate_limit_backoff_seconds(resp, default=10.0) == 7.0++ @pytest.mark.parametrize("raw", [None, "not-a-number"])+ def test_backoff_falls_back_without_usable_retry_after(self, raw: str | None):+ resp = _make_response(None, status_code=429, text="Too Many Requests")+ if raw is not None:+ resp.headers["Retry-After"] = raw+ assert _rate_limit_backoff_seconds(resp, default=10.0) == 10.0++ def test_company_segments_retries_rate_limited_segment_fetch(self):+ # The observed failure: a burst of per-company `/companies/{id}/segments`+ # fetches trips Intercom's rate limit and 429s. Riding out the window inline+ # lets the walk continue instead of failing the whole sync. Scroll is drained+ # first (two GETs), then the segment fetch 429s once and succeeds on retry.+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response({"data": [{"id": "co1"}], "scroll_param": "s1"}),+ _make_response({"data": []}),+ _make_response(None, status_code=429, text="Too Many Requests"),+ _make_response({"data": [{"id": "seg1"}]}),+ ]++ with mock.patch.object(intercom_module.time, "sleep") as sleep:+ segments = list(_company_segments_generator(mock_session))++ assert [s["id"] for s in segments] == ["seg1"]+ assert segments[0]["company_id"] == "co1"+ sleep.assert_called_once_with(intercom_module._RATE_LIMIT_BACKOFF_SECONDS)++ def test_intercom_get_reraises_rate_limit_after_max_retries(self):+ # A persistent 429 must surface after the bounded retries rather than+ # looping forever, so Temporal can retry the activity.+ mock_session = mock.MagicMock()+ mock_session.get.side_effect = [+ _make_response(None, status_code=429, text="Too Many Requests")+ for _ in range(intercom_module._RATE_LIMIT_MAX_RETRIES + 1)+ ]++ with mock.patch.object(intercom_module.time, "sleep"):+ with pytest.raises(HTTPError):+ _intercom_get(mock_session, "/companies/co1/segments")++ assert mock_session.get.call_count == intercom_module._RATE_LIMIT_MAX_RETRIES + 1++class TestSubstreamSessionRetries:def test_idempotent_search_posts_are_retryable(self):# The substream walk reaches `/conversations/search` and `/companies/list`