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(google_analytics): retry transient 5xx runReport errors inline (#64831)

Tom Owersd149f648cab3
diff --git a/posthog/temporal/data_imports/sources/google_analytics/google_analytics.py b/posthog/temporal/data_imports/sources/google_analytics/google_analytics.py
index f472d2fbc662..977fd493e68d 100644
--- a/posthog/temporal/data_imports/sources/google_analytics/google_analytics.py
+++ b/posthog/temporal/data_imports/sources/google_analytics/google_analytics.py
@@ -40,11 +40,12 @@ LOOKBACK_DAYS = 2
CHUNK_DAYS = 30
PAGE_LIMIT = 50000 # runReport allows up to 250k rows/request; keep payloads modest
-# The Data API reports quota exhaustion (property tokens, concurrent requests)
-# as HTTP 429 RESOURCE_EXHAUSTED. These are transient — back off and retry
-# inline, then fall back to a Temporal activity retry via the resumable state.
-QUOTA_MAX_RETRIES = 5
-QUOTA_BACKOFF_BASE_SECONDS = 5.0
+# Shared runReport retry policy for transient failures: 429 RESOURCE_EXHAUSTED
+# quota exhaustion (property tokens, concurrent requests) and 5xx server errors.
+# Both are transient — back off and retry inline, then fall back to a Temporal
+# activity retry via the resumable state.
+RUNREPORT_MAX_RETRIES = 5
+RUNREPORT_BACKOFF_BASE_SECONDS = 5.0
_INTEGER_METRIC_TYPES = frozenset({"TYPE_INTEGER"})
@@ -111,15 +112,21 @@ def _is_quota_error(response: requests.Response) -> bool:
return response.status_code == 429
-def _quota_backoff_seconds(response: requests.Response, attempt: int) -> float:
- """Seconds to wait before retrying a quota error: honor `Retry-After`, else exponential."""
+def _is_retryable_server_error(response: requests.Response) -> bool:
+ """5xx responses (e.g. 503 Service Unavailable) are transient backend errors —
+ back off and retry inline rather than failing the chunk."""
+ return 500 <= response.status_code < 600
+
+
+def _runreport_backoff_seconds(response: requests.Response, attempt: int) -> float:
+ """Seconds to wait before retrying a transient error: honor `Retry-After`, else exponential."""
retry_after = response.headers.get("Retry-After")
if retry_after is not None:
try:
return float(retry_after)
except ValueError:
pass
- return QUOTA_BACKOFF_BASE_SECONDS * (2**attempt)
+ return RUNREPORT_BACKOFF_BASE_SECONDS * (2**attempt)
def _run_report(
@@ -144,7 +151,7 @@ def _run_report(
}
url = f"{GA4_API_BASE}/properties/{pid}:runReport"
- for attempt in range(QUOTA_MAX_RETRIES + 1):
+ for attempt in range(RUNREPORT_MAX_RETRIES + 1):
response = session.post(url, json=body)
if response.ok:
return response.json()
@@ -157,18 +164,22 @@ def _run_report(
body=response.text,
)
- if not _is_quota_error(response):
+ is_quota = _is_quota_error(response)
+ if not is_quota and not _is_retryable_server_error(response):
# Permission / bad-request errors are fatal — let the HTTPError bubble up so
# `get_non_retryable_errors` can match "403 Client Error" / "401 Client Error".
response.raise_for_status()
- if attempt == QUOTA_MAX_RETRIES:
- raise GoogleAnalyticsQuotaExceededError(
- f"Data API quota for property '{pid}' still exhausted after {QUOTA_MAX_RETRIES} retries"
- )
+ if attempt == RUNREPORT_MAX_RETRIES:
+ if is_quota:
+ raise GoogleAnalyticsQuotaExceededError(
+ f"Data API quota for property '{pid}' still exhausted after {RUNREPORT_MAX_RETRIES} retries"
+ )
+ # A transient 5xx that never cleared — surface the HTTPError so Temporal retries the activity.
+ response.raise_for_status()
- wait = _quota_backoff_seconds(response, attempt)
- logger.warning("GA4 quota exceeded, backing off", property_id=pid, attempt=attempt, wait_seconds=wait)
+ wait = _runreport_backoff_seconds(response, attempt)
+ logger.warning("GA4 runReport failed, backing off", property_id=pid, attempt=attempt, wait_seconds=wait)
time.sleep(wait)
# Unreachable: the loop either returns, raises for status, or raises the quota error.
diff --git a/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py b/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py
index cf533f8de1d0..46ecf7725a96 100644
--- a/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py
+++ b/posthog/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py
@@ -13,19 +13,20 @@ from posthog.temporal.data_imports.sources.google_analytics.google_analytics imp
CHUNK_DAYS,
HISTORY_DAYS,
LOOKBACK_DAYS,
- QUOTA_MAX_RETRIES,
+ RUNREPORT_MAX_RETRIES,
GoogleAnalyticsQuotaExceededError,
GoogleAnalyticsResumeConfig,
_convert_metric_value,
_credentials,
_initial_start_date,
_is_quota_error,
+ _is_retryable_server_error,
_iter_chunks,
_parse_ga4_date,
- _quota_backoff_seconds,
_resolve_window,
_rows_to_dicts,
_run_report,
+ _runreport_backoff_seconds,
google_analytics_source,
normalize_property_id,
)
@@ -232,14 +233,30 @@ def test_is_quota_error(status_code, expected):
assert _is_quota_error(_fake_response(status_code)) is expected
+ "status_code,expected",
+ [
+ (500, True),
+ (502, True),
+ (503, True),
+ (504, True),
+ (429, False),
+ (403, False),
+ (200, False),
+ ],
+)
+def test_is_retryable_server_error(status_code, expected):
+ assert _is_retryable_server_error(_fake_response(status_code)) is expected
+
+
def test_quota_backoff_honors_retry_after():
response = _fake_response(429, headers={"Retry-After": "17"})
- assert _quota_backoff_seconds(response, attempt=0) == 17.0
+ assert _runreport_backoff_seconds(response, attempt=0) == 17.0
def test_quota_backoff_falls_back_to_exponential():
response = _fake_response(429, headers={"Retry-After": "soon"})
- assert _quota_backoff_seconds(response, attempt=2) == ga.QUOTA_BACKOFF_BASE_SECONDS * 4
+ assert _runreport_backoff_seconds(response, attempt=2) == ga.RUNREPORT_BACKOFF_BASE_SECONDS * 4
def test_run_report_returns_payload_on_success():
@@ -307,7 +324,7 @@ def test_run_report_raises_after_exhausting_quota_retries(monkeypatch):
offset=0,
)
- assert session.post.call_count == QUOTA_MAX_RETRIES + 1
+ assert session.post.call_count == RUNREPORT_MAX_RETRIES + 1
@pytest.mark.parametrize("status_code", [400, 401, 403, 404])
@@ -329,6 +346,49 @@ def test_run_report_raises_http_error_for_non_quota_failures(status_code):
assert session.post.call_count == 1
+def test_run_report_retries_server_errors_then_succeeds(monkeypatch):
+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)
+ payload = {"rows": [], "rowCount": 0}
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _fake_response(503),
+ _fake_response(503),
+ _fake_response(200, payload),
+ ]
+
+ result = _run_report(
+ session=session,
+ property_id="123",
+ start_date="2026-04-01",
+ end_date="2026-04-30",
+ dimensions=["date"],
+ metrics=["totalUsers"],
+ offset=0,
+ )
+
+ assert result == payload
+ assert session.post.call_count == 3
+
+
+def test_run_report_raises_http_error_after_exhausting_server_error_retries(monkeypatch):
+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)
+ session = mock.MagicMock()
+ session.post.return_value = _fake_response(503)
+
+ with pytest.raises(requests.HTTPError):
+ _run_report(
+ session=session,
+ property_id="123",
+ start_date="2026-04-01",
+ end_date="2026-04-30",
+ dimensions=["date"],
+ metrics=["totalUsers"],
+ offset=0,
+ )
+
+ assert session.post.call_count == RUNREPORT_MAX_RETRIES + 1
+
+
def _report_payload(dates: list[str], users: list[int], row_count: int | None = None) -> dict:
return {
"dimensionHeaders": [{"name": "date"}],