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(warehouse-sources): treat an exhausted Sentry 429 as retryable (#92677)

posthog[bot]65d2f88f5ad3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
index 81b055b74f9e..b1757932922a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
@@ -15,11 +15,15 @@ from dateutil import parser as dateutil_parser
from requests import Request, Response
from requests.exceptions import HTTPError, JSONDecodeError, RequestException
from tenacity import RetryCallState, retry, retry_if_exception_type, retry_if_result, stop_after_attempt
+from urllib3.util.retry import Retry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
coerce_datetime_to_utc,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import (
+ CLOUDFLARE_TRANSIENT_STATUSES,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
@@ -54,7 +58,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.set
_MAX_PAGES_PER_PARENT = 100
_REQUEST_TIMEOUT = 30
_MAX_RETRIES = 3
-_RETRYABLE_STATUS_CODES = (429, 500, 502, 503, 504)
+# Statuses tenacity retries as the single retry layer. Mirrors the adapter policy it replaces
+# (DEFAULT_RETRY) so disabling that policy on `_request_with_retry` keeps the Cloudflare 52x
+# coverage the adapter provided.
+_RETRYABLE_STATUS_CODES = (429, 500, 502, 503, 504, *CLOUDFLARE_TRANSIENT_STATUSES)
+# Upper bound on a server-provided 429 wait, so a misreported Retry-After or reset header cannot
+# park a worker. Matches the shared REST client's MAX_RETRY_AFTER_SECONDS.
+_MAX_RETRY_AFTER_SECONDS = 300.0
# Safety bound for how many issues the issue_tag_values fan-out will skip while
# fast-forwarding to a saved checkpoint issue. If the checkpoint issue was
# deleted between runs, we'd otherwise skip every remaining issue and yield
@@ -270,34 +280,62 @@ class SentryPaginator(BasePaginator):
# Low-level HTTP helpers (used only by issue_tag_values custom fan-out)
# ---------------------------------------------------------------------------
+# Raised when Sentry keeps rate-limiting our requests (HTTP 429) until the request-level retry
+# budget runs out. The source classifies this as retryable (see `SentrySource.get_retryable_errors`)
+# so Temporal retries the whole activity and the next sync picks up the self-recovering limit. The
+# wording never interpolates the org, URL, or response body, so it stays safe for error tracking —
+# a raw `raise_for_status()` HTTPError would leak the org slug in its URL.
+SENTRY_RATE_LIMITED_MESSAGE = (
+ "Sentry rate-limited PostHog's API requests (HTTP 429) and the limit did not clear within the "
+ "retry window. This is temporary and the next scheduled sync retries automatically."
+)
+
+
+class SentryRateLimitedError(Exception):
+ """Sentry kept returning 429 until the request-level retry budget ran out."""
+
def _is_retryable_response(response: Response) -> bool:
return response.status_code in _RETRYABLE_STATUS_CODES
-def _retry_wait_seconds(state: RetryCallState) -> float:
- fallback_wait = min(2 ** (state.attempt_number - 1), 30)
- if state.outcome is None or state.outcome.failed:
- return float(fallback_wait)
+def _rate_limit_wait_from_headers(response: Response) -> float | None:
+ """Seconds to wait before a 429 retry, read from Sentry's rate-limit headers.
- response = state.outcome.result()
- if response.status_code != 429:
- return float(fallback_wait)
+ `Retry-After` is the HTTP-standard delta in seconds and takes priority, so a custom-iterator
+ endpoint waits the same as every other Sentry endpoint, which syncs through the shared REST
+ client's Retry-After-first parser. `X-Sentry-Rate-Limit-Reset` is a UNIX epoch second and is
+ the fallback. The wait is capped so a misreported header cannot park a worker. None means
+ neither header gives a positive wait, so the caller uses exponential backoff.
+ """
+ retry_after = response.headers.get("Retry-After")
+ if retry_after and retry_after.strip().isdigit():
+ return min(float(retry_after.strip()), _MAX_RETRY_AFTER_SECONDS)
reset_header = response.headers.get("X-Sentry-Rate-Limit-Reset")
- if not reset_header:
- return float(fallback_wait)
+ if reset_header:
+ try:
+ reset_epoch = int(reset_header)
+ except ValueError:
+ return None
+ wait_until_reset = reset_epoch - int(datetime.now(UTC).timestamp())
+ if wait_until_reset > 0:
+ return min(float(wait_until_reset), _MAX_RETRY_AFTER_SECONDS)
- try:
- reset_epoch = int(reset_header)
- except ValueError:
- return float(fallback_wait)
+ return None
+
+
+def _retry_wait_seconds(state: RetryCallState) -> float:
+ fallback_wait = float(min(2 ** (state.attempt_number - 1), 30))
+ if state.outcome is None or state.outcome.failed:
+ return fallback_wait
- wait_until_reset = reset_epoch - int(datetime.now(UTC).timestamp())
- if wait_until_reset <= 0:
- return float(fallback_wait)
+ response = state.outcome.result()
+ if response.status_code != 429:
+ return fallback_wait
- return float(wait_until_reset)
+ header_wait = _rate_limit_wait_from_headers(response)
+ return header_wait if header_wait is not None else fallback_wait
def _raise_on_failed_retry(state: RetryCallState) -> Response:
@@ -308,7 +346,17 @@ def _raise_on_failed_retry(state: RetryCallState) -> Response:
if exc is None:
raise RuntimeError("Unexpected request retry state")
raise exc
- return state.outcome.result()
+ response = state.outcome.result()
+ if response.status_code == 429:
+ # The rate limit did not clear within our retry budget. Raise a credential-safe error the
+ # source treats as retryable instead of returning the 429 to the caller, whose
+ # `raise_for_status()` would surface an HTTPError with the org slug in its URL.
+ raise SentryRateLimitedError(SENTRY_RATE_LIMITED_MESSAGE)
+ # A persistent 5xx is returned unchanged, not raised here: several callers read the status to
+ # skip a single (issue, tag) or endpoint slice and keep the sync going (see
+ # `_skip_issue_on_tags_server_error` and the issue_tag_values values loop), which needs the
+ # response in hand.
+ return response
@retry(
@@ -323,7 +371,11 @@ def _request_with_retry(
params: dict[str, Any] | None,
timeout: int = _REQUEST_TIMEOUT,
) -> Response:
- return make_tracked_session().get(url, headers=headers, params=params, timeout=timeout)
+ # The tenacity policy above is the single retry authority for these requests. Disable the
+ # session adapter's own retry policy (DEFAULT_RETRY) so a 429 or 5xx is not retried again
+ # beneath each tenacity attempt, which would multiply both the request count and the
+ # Retry-After sleeps against an endpoint that is already throttling us.
+ return make_tracked_session(retry=Retry(total=0)).get(url, headers=headers, params=params, timeout=timeout)
def _iter_endpoint_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py
index 8b2738346696..8f842c26742f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py
@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sentry import SentrySourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry import (
+ SENTRY_RATE_LIMITED_MESSAGE,
STATS_SUMMARY_REJECTED_MESSAGE,
SentryResumeConfig,
_normalize_organization_slug,
@@ -138,12 +139,12 @@ class SentrySource(ResumableSource[SentrySourceConfig, SentryResumeConfig]):
# urllib3 level; once that budget is exhausted, urllib3 re-raises with the stable "Max
# retries exceeded with url" prefix regardless of the underlying cause.
#
- # HTTP 429s are retried by tenacity (respecting X-Sentry-Rate-Limit-Reset); when that
- # budget is exhausted, `raise_for_status()` raises `HTTPError: 429 Client Error: Too Many
- # Requests`, which does NOT contain the "Max retries exceeded" phrase. Match the stable
- # status-line prefix so persistent rate-limiting lets Temporal retry instead of being
- # reported to error tracking as a bug.
- return {"Max retries exceeded with url", "429 Client Error"}
+ # A 429 that outlives tenacity's budget surfaces two ways. The `issue_tag_values` fan-out
+ # raises SENTRY_RATE_LIMITED_MESSAGE, a credential-safe string that keeps the org slug out
+ # of error tracking; every other path still reaches `raise_for_status()`, which raises
+ # `HTTPError: 429 Client Error: Too Many Requests`. Match both so persistent rate-limiting
+ # lets Temporal retry instead of being reported to error tracking as a bug.
+ return {"Max retries exceeded with url", SENTRY_RATE_LIMITED_MESSAGE, "429 Client Error"}
def get_required_parent_schemas(self, schema_name: str) -> list[str]:
# issue_tag_values fans out over issues through its custom two-level iterator, so it
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py
index e87551c49de3..35ecc2b96274 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py
@@ -15,7 +15,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sentry import SentrySourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry import (
+ _MAX_RETRY_AFTER_SECONDS,
SentryPaginator,
+ SentryRateLimitedError,
SentryResumeConfig,
SentryStatsSummaryRejectedError,
_custom_endpoint_rows,
@@ -23,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sen
_normalize_api_base_url,
_normalize_organization_slug,
_parse_next_link,
+ _raise_on_failed_retry,
_retention_bounded_start_param,
_retry_wait_seconds,
_start_param_for_sentry,
@@ -1346,8 +1349,17 @@ class TestHelpers:
assert _retry_wait_seconds(state) == 4.0
+ @parameterized.expand(
+ [
+ # A positive reset delta becomes the wait.
+ ("uses_reset_delta", 9, 9.0),
+ # The reset header is an absolute epoch, so clock skew or a proxy can inflate it into the
+ # far future. Bound it so it cannot park the shared source-iterator thread.
+ ("caps_far_future_reset", 100000, _MAX_RETRY_AFTER_SECONDS),
+ ]
+ )
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.datetime")
- def test_retry_wait_uses_rate_limit_reset_header_for_429(self, mock_datetime) -> None:
+ def test_retry_wait_uses_rate_limit_reset_header_for_429(self, _name, reset_delta, expected, mock_datetime) -> None:
now = datetime(2026, 3, 6, 12, 0, 0, tzinfo=UTC)
mock_datetime.now.return_value = now
@@ -1357,10 +1369,65 @@ class TestHelpers:
state.outcome.failed = False
state.outcome.result.return_value = Mock(
status_code=429,
- headers={"X-Sentry-Rate-Limit-Reset": str(int(now.timestamp()) + 9)},
+ headers={"X-Sentry-Rate-Limit-Reset": str(int(now.timestamp()) + reset_delta)},
)
- assert _retry_wait_seconds(state) == 9.0
+ assert _retry_wait_seconds(state) == expected
+
+ @parameterized.expand(
+ [
+ # Both headers present: Retry-After wins, matching the shared REST client's ordering for
+ # Sentry, so a custom-iterator endpoint waits the same as every other endpoint.
+ ("prefers_retry_after", {"Retry-After": "12", "X-Sentry-Rate-Limit-Reset": "9999999999"}, 12.0),
+ # A misreported delay is bounded so it cannot park the worker.
+ ("caps_delay", {"Retry-After": "100000"}, _MAX_RETRY_AFTER_SECONDS),
+ ]
+ )
+ def test_retry_wait_from_retry_after_header(self, _name, headers, expected) -> None:
+ state = Mock()
+ state.attempt_number = 1
+ state.outcome = Mock()
+ state.outcome.failed = False
+ state.outcome.result.return_value = Mock(status_code=429, headers=headers)
+
+ assert _retry_wait_seconds(state) == expected
+
+ def test_retry_wait_uses_retry_after_header_when_reset_absent(self) -> None:
+ # The exponential fallback tops out around 7 seconds across the whole budget, so a longer
+ # wait must come from the header Sentry actually sends when it omits the reset epoch.
+ state = Mock()
+ state.attempt_number = 1
+ state.outcome = Mock()
+ state.outcome.failed = False
+ state.outcome.result.return_value = Mock(status_code=429, headers={"Retry-After": "42"})
+
+ assert _retry_wait_seconds(state) == 42.0
+
+ def test_exhausted_429_raises_org_safe_retryable_error(self) -> None:
+ # A persistent 429 that outlasts the retry budget must not reach the caller's
+ # raise_for_status(), whose HTTPError URL carries the org slug. The dedicated error keeps
+ # the slug out and is the one the source classifies as retryable rather than unexpected.
+ state = Mock()
+ state.outcome = Mock()
+ state.outcome.failed = False
+ state.outcome.result.return_value = Mock(status_code=429, headers={})
+
+ with pytest.raises(SentryRateLimitedError) as exc_info:
+ _raise_on_failed_retry(state)
+
+ assert error_message_matches(str(exc_info.value), SentrySource().get_retryable_errors())
+ assert not error_message_matches(str(exc_info.value), SentrySource().get_non_retryable_errors())
+
+ def test_exhausted_5xx_still_returns_response(self) -> None:
+ # 5xx callers depend on raise_for_status() so their per-endpoint skip handlers can run;
+ # only 429 is short-circuited into the retryable error.
+ response = Mock(status_code=503, headers={})
+ state = Mock()
+ state.outcome = Mock()
+ state.outcome.failed = False
+ state.outcome.result.return_value = response
+
+ assert _raise_on_failed_retry(state) is response
class TestSentryRetentionWindow: