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(cloudflare): honor Retry-After on 429 rate-limit responses (#63447)

Tom Owersce3938a8c32e
diff --git a/posthog/temporal/data_imports/sources/cloudflare/cloudflare.py b/posthog/temporal/data_imports/sources/cloudflare/cloudflare.py
index 5218558ec25b..cc9b9544e007 100644
--- a/posthog/temporal/data_imports/sources/cloudflare/cloudflare.py
+++ b/posthog/temporal/data_imports/sources/cloudflare/cloudflare.py
@@ -4,7 +4,7 @@ from urllib.parse import quote, urlencode
import requests
from 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_jitter
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.sources.cloudflare.settings import CLOUDFLARE_ENDPOINTS
@@ -14,12 +14,41 @@ CLOUDFLARE_BASE_URL = "https://api.cloudflare.com/client/v4"
# Cloudflare list pages cap at 50 by default; most endpoints allow more.
PAGE_SIZE = 50
REQUEST_TIMEOUT_SECONDS = 60
-# 1200 req/5min global API rate limit; 429s carry Retry-After but backoff suffices.
+# 1200 req/5min global API rate limit; a 429 stays rate-limited until the window
+# resets, so we honor the Retry-After header it carries instead of guessing.
MAX_RETRY_ATTEMPTS = 5
+# Cap how long a single Retry-After can stall us, so a misbehaving header can't
+# pin the activity open for the full 5-minute window times every attempt.
+MAX_RETRY_AFTER_SECONDS = 120
+# Stateless backoff used when a retryable error carries no Retry-After hint.
+_FALLBACK_WAIT = wait_exponential_jitter(initial=1, max=60)
class CloudflareRetryableError(Exception):
- pass
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ # Seconds Cloudflare asked us to wait (from a 429 Retry-After), if any.
+ self.retry_after = retry_after
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ """Cloudflare sends Retry-After as delta-seconds on 429s; ignore other forms."""
+ raw = response.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, CloudflareRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, MAX_RETRY_AFTER_SECONDS)
+ return _FALLBACK_WAIT(retry_state)
def _get_session(api_token: str) -> requests.Session:
@@ -49,7 +78,7 @@ def get_rows(
@retry(
retry=retry_if_exception_type((CloudflareRetryableError, requests.ReadTimeout, requests.ConnectionError)),
stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
- wait=wait_exponential_jitter(initial=1, max=60),
+ wait=_wait_strategy,
reraise=True,
)
def fetch(path: str, page: int) -> dict[str, Any]:
@@ -58,7 +87,8 @@ def get_rows(
if response.status_code == 429 or response.status_code >= 500:
raise CloudflareRetryableError(
- f"Cloudflare API error (retryable): status={response.status_code}, url={url}"
+ f"Cloudflare API error (retryable): status={response.status_code}, url={url}",
+ retry_after=_parse_retry_after(response) if response.status_code == 429 else None,
)
if not response.ok:
diff --git a/posthog/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py b/posthog/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py
index 6b3c3d25eeef..640e17ee6301 100644
--- a/posthog/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py
+++ b/posthog/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py
@@ -4,8 +4,14 @@ from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
+from tenacity import Future, RetryCallState
+
from posthog.temporal.data_imports.sources.cloudflare.cloudflare import (
+ MAX_RETRY_AFTER_SECONDS,
PAGE_SIZE,
+ CloudflareRetryableError,
+ _parse_retry_after,
+ _wait_strategy,
cloudflare_source,
get_rows,
validate_credentials,
@@ -26,6 +32,20 @@ def _response(result: list[dict[str, Any]], total_pages: int | None = None, succ
return resp
+def _rate_limited_response(headers: dict[str, str] | None = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = 429
+ resp.ok = False
+ resp.headers = headers or {}
+ return resp
+
+
+def _retry_state(exc: BaseException) -> RetryCallState:
+ state = RetryCallState(retry_object=mock.MagicMock(), fn=None, args=(), kwargs={})
+ state.outcome = Future.construct(1, exc, has_exception=True)
+ return state
+
+
class TestValidateCredentials:
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_valid_on_verify_success(self, mock_session):
@@ -110,6 +130,47 @@ class TestGetRows:
assert list(get_rows("token", "zones", mock.MagicMock())) == []
+class TestRetryAfterHandling:
+ @pytest.mark.parametrize(
+ "headers, expected",
+ [
+ ({"Retry-After": "30"}, 30.0),
+ ({"Retry-After": "0"}, 0.0),
+ ({"Retry-After": "12.5"}, 12.5),
+ ({}, None),
+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None),
+ ({"Retry-After": "soon"}, None),
+ ],
+ )
+ def test_parse_retry_after(self, headers, expected):
+ assert _parse_retry_after(_rate_limited_response(headers)) == expected
+
+ def test_wait_strategy_honors_retry_after(self):
+ exc = CloudflareRetryableError("rate limited", retry_after=45.0)
+ assert _wait_strategy(_retry_state(exc)) == 45.0
+
+ def test_wait_strategy_caps_retry_after(self):
+ exc = CloudflareRetryableError("rate limited", retry_after=10_000.0)
+ assert _wait_strategy(_retry_state(exc)) == MAX_RETRY_AFTER_SECONDS
+
+ def test_wait_strategy_falls_back_to_backoff_without_retry_after(self):
+ exc = CloudflareRetryableError("server error", retry_after=None)
+ # Jittered exponential backoff for the first attempt stays small and bounded.
+ assert 0 < _wait_strategy(_retry_state(exc)) <= 60
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_429_carries_retry_after_into_exception(self, mock_session):
+ # Retry-After of 0 keeps the test fast while still exercising the honored-wait path.
+ mock_session.return_value.get.return_value = _rate_limited_response({"Retry-After": "0"})
+
+ with pytest.raises(CloudflareRetryableError) as exc_info:
+ list(get_rows("token", "zones", mock.MagicMock()))
+
+ assert exc_info.value.retry_after == 0.0
+ # Exhausts all attempts since every page stays rate-limited.
+ assert mock_session.return_value.get.call_count == 5
+
+
class TestCloudflareSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
def test_response_metadata_per_endpoint(self, endpoint):