: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(luma): wait out the rate-limit window before a sync fails (#116131)
posthog[bot]ec2566d9636e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.pyindex 4053cc2b8e85..f9598164eb93 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/luma.py@@ -4,10 +4,11 @@ from typing import Any, Optionalimport requestsfrom structlog.types import FilteringBoundLogger-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_jitterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.retry_limits import max_retry_after_secondsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.luma.settings import (EVENTS_PATH,@@ -26,7 +27,9 @@ DEFAULT_PROBE_PATH = EVENTS_PATHclass LumaRetryableError(Exception):- pass+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after@dataclasses.dataclass(frozen=True)@@ -42,10 +45,32 @@ def _headers(api_key: str) -> dict[str, str]:return {"x-luma-api-key": api_key, "Accept": "application/json"}+def _retry_after_seconds(response: requests.Response) -> float | None:+ try:+ seconds = float(response.headers.get("Retry-After", ""))+ except ValueError:+ return None+ if not 0 < seconds < float("inf"):+ return None+ return min(seconds, max_retry_after_seconds())+++_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=30)+++def _retry_wait(retry_state: RetryCallState) -> float:+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, LumaRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return _EXPONENTIAL_WAIT(retry_state)+++# Luma holds a rate-limited key for one minute, so the waits must add up to more than that.+# Eight attempts wait about 1+2+4+8+16+30+30 = 91 seconds in total.@retry(retry=retry_if_exception_type((LumaRetryableError, requests.ReadTimeout, requests.ConnectionError)),- stop=stop_after_attempt(5),- wait=wait_exponential_jitter(initial=1, max=30),+ stop=stop_after_attempt(8),+ wait=_retry_wait,reraise=True,)def _fetch_page(@@ -67,7 +92,10 @@ def _fetch_page(# Luma returns 429 on rate-limit overage with a one-minute back-off window.if response.status_code == 429 or response.status_code >= 500:- raise LumaRetryableError(f"Luma API error (retryable): status={response.status_code}, path={path}")+ raise LumaRetryableError(+ f"Luma API error (retryable): status={response.status_code}, path={path}",+ retry_after=_retry_after_seconds(response),+ )if not response.ok:logger.error(f"Luma API error: status={response.status_code}, body={response.text}, path={path}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.pyindex 197a229b745b..2011914659bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/source.py@@ -72,6 +72,14 @@ You can create an API key under **Settings → Developer** in [Luma](https://lumreturn CANONICAL_DESCRIPTIONS+ def get_retry_exhausted_errors(self) -> dict[str, str]:+ return {+ "Luma API error (retryable): status=429": (+ "Luma's API rate limit ran out before this sync finished. "+ "Set this table to sync less often, such as every 6 hours, so each run stays within the limit."+ ),+ }+def get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error: Unauthorized for url: https://public-api.luma.com": "Your Luma API key is invalid or has been revoked. Generate a new key under Settings → Developer in Luma, then reconnect.",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.py b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.pyindex 59777cf8e0e5..e4b919809f34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/luma/tests/test_luma.py@@ -6,6 +6,7 @@ from unittest.mock import MagicMockimport requestsfrom parameterized import parameterized+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (ScriptedResponse,SourceDriver,@@ -167,6 +168,42 @@ class TestFetchPage:with pytest.raises(LumaRetryableError):_fetch_page_unwrapped(session, EVENTS_PATH, None, MagicMock())+ @parameterized.expand(+ [+ ("honors_retry_after", {"Retry-After": "45"}, 1, [45.0]),+ ("outlasts_one_minute_window", {}, 7, None),+ ]+ )+ def test_rate_limit_retries_wait_out_the_window(+ self, _name: str, headers: dict[str, str], rate_limited_calls: int, expected_waits: list[float] | None+ ) -> None:+ rate_limited = MagicMock(status_code=429, headers=headers)+ ok = self._session_returning(200).get.return_value+ session = MagicMock()+ session.get.side_effect = [rate_limited] * rate_limited_calls + [ok]+ waits: list[float] = []++ luma._fetch_page.retry_with(sleep=waits.append)(session, EVENTS_PATH, None, MagicMock()) # type: ignore[attr-defined]++ assert session.get.call_count == rate_limited_calls + 1+ if expected_waits is not None:+ assert waits == expected_waits+ else:+ assert sum(waits) > 60++ def test_exhausted_rate_limit_stays_retryable_with_sync_frequency_guidance(self) -> None:+ with pytest.raises(LumaRetryableError) as exc_info:+ _fetch_page_unwrapped(self._session_returning(429), EVENTS_PATH, None, MagicMock())+ observed_error = str(exc_info.value)+ source = LumaSource()+ assert not error_message_matches(observed_error, source.get_non_retryable_errors().keys())+ messages = [+ message+ for pattern, message in source.get_retry_exhausted_errors().items()+ if error_message_matches(observed_error, [pattern])+ ]+ assert messages and "sync less often" in messages[0]+@parameterized.expand([("bad_request", 400), ("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:session = self._session_returning(status)