: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(stripe): retry rate-limit errors via the SDK's built-in backoff (#63805)
Tom Owers02a77302cf87
diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.pyindex cd04eb963c51..b06a6bffb59b 100644--- a/posthog/temporal/data_imports/sources/stripe/stripe.py+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py@@ -1,7 +1,7 @@import osimport reimport dataclasses-from collections.abc import Callable+from collections.abc import Callable, Mappingfrom typing import Any, Literal, Optional, Union, cast, get_args, get_type_hintsimport orjson@@ -54,10 +54,38 @@ LOGGER = get_logger(__name__)DEFAULT_LIMIT = 100+class _RateLimitRetryingRequestsClient(RequestsClient):+ """Stripe's SDK retries 409/5xx (and whatever ``Stripe-Should-Retry`` advises) but never+ retries 429s on its own — ``_should_retry`` excludes them. A rate limit during a large sync,+ most often while ``auto_paging_iter`` lazily fetches the next page, therefore propagates+ straight out of ``get_rows`` and fails the whole import activity.++ Opt 429 into the SDK's existing ``Retry-After``-aware exponential backoff so transient rate+ limits are absorbed in-process (bounded by ``max_network_retries``) instead of crashing the+ run. Our Stripe reads are list/GET calls, so retrying them is idempotent."""++ def _should_retry(+ self,+ response: Optional[tuple[Any, int, Optional[Mapping[str, str]]]],+ api_connection_error: Optional[stripe_lib.APIConnectionError],+ num_retries: int,+ max_network_retries: Optional[int],+ ) -> bool:+ if super()._should_retry(response, api_connection_error, num_retries, max_network_retries):+ return True+ # The base logic already enforced the retry budget and declined; the only retryable case+ # it leaves on the table is a 429, which the SDK omits but which is safe to retry here.+ if num_retries >= (max_network_retries or 0):+ return False+ return response is not None and response[1] == 429++def _tracked_stripe_http_client() -> RequestsClient:"""Wrap a tracked `requests.Session` in Stripe's `RequestsClient` so every- Stripe SDK call participates in our HTTP logging, metrics, and sample capture."""- return RequestsClient(session=make_tracked_session())+ Stripe SDK call participates in our HTTP logging, metrics, and sample capture.++ Uses a subclass that additionally retries 429 rate limits via the SDK's built-in backoff."""+ return _RateLimitRetryingRequestsClient(session=make_tracked_session())def _clean_stripe_error_message(msg: str) -> str:diff --git a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.pyindex e0b6c7b242d1..b3c10e308a58 100644--- a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py+++ b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py@@ -1,4 +1,5 @@import uuid+from collections.abc import Mappingfrom urllib.parse import parse_qs, urlparseimport pytest@@ -29,6 +30,7 @@ from posthog.temporal.data_imports.sources.stripe.stripe import (_build_resources,_call_stripe,_clean_stripe_error_message,+ _tracked_stripe_http_client,check_endpoint_permissions,get_rows,validate_credentials,@@ -637,6 +639,32 @@ def test_call_stripe_passes_through_successful_result():assert _call_stripe(lambda x: x + 1, 41) == 42+ [+ # (status_code, num_retries, max_network_retries, expected)+ # 429 is now retried while budget remains — the SDK omits this on its own.+ ("rate_limit_retried", 429, 0, 2, True),+ # ...but stops once the retry budget is exhausted, so we don't loop forever.+ ("rate_limit_budget_exhausted", 429, 2, 2, False),+ # 5xx keeps the SDK's built-in retry behavior.+ ("server_error_still_retried", 503, 0, 2, True),+ # Non-retryable 4xx (e.g. a bad request) must NOT be retried.+ ("bad_request_not_retried", 400, 0, 2, False),+ ]+)+def test_stripe_http_client_retries_rate_limits(_name, status_code, num_retries, max_network_retries, expected):+ """Stripe's SDK never retries 429s, so a transient rate limit during pagination would crash+ the import activity. Our client opts 429 into the SDK's Retry-After-aware backoff while+ preserving the base behavior for 5xx and leaving non-retryable 4xx alone."""+ client = _tracked_stripe_http_client()+ response: tuple[bytes, int, Mapping[str, str]] = (b"", status_code, {})++ assert (+ client._should_retry(response, None, num_retries=num_retries, max_network_retries=max_network_retries)+ is expected+ )++def test_validate_credentials_nested_resources_have_registered_parents():"""Invariant: every StripeNestedResource's `parent_name` must point at a key that isalso registered as a top-level StripeResource in _build_resources. validate_credentials