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 token-refresh errors during report fetch (#83908)

Tom Owers1ad6ada2cf6b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
index d08842d8c345..153761d91fc5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py
@@ -9,6 +9,7 @@ from django.db import OperationalError, close_old_connections
import requests
import structlog
+from google.auth.exceptions import RefreshError
from google.auth.transport.requests import AuthorizedSession
from google.oauth2.credentials import Credentials as OAuthCredentials
@@ -165,6 +166,23 @@ def _runreport_backoff_seconds(response: requests.Response, attempt: int) -> flo
return RUNREPORT_BACKOFF_BASE_SECONDS * (2**attempt)
+def _is_transient_refresh_error(error: RefreshError) -> bool:
+ """Whether an OAuth token-refresh failure is a transient server-side blip worth retrying.
+
+ `AuthorizedSession` refreshes the access token before the Data API request, so a failing
+ token endpoint raises `RefreshError` from `session.post` before any response object exists —
+ the 5xx handling below never sees it. google-auth flags 500/503/504/408/429 (and JSON
+ `server_error`/`temporarily_unavailable`) as retryable, but omits 502 from its retryable
+ status codes, so a Bad Gateway from the token endpoint surfaces as a `RefreshError(retryable=False)`
+ carrying an HTML error page. Treat those as transient too. Permanent failures (`invalid_grant`,
+ `invalid_scope`) stay non-transient so they bubble up to `get_non_retryable_errors`.
+ """
+ if getattr(error, "retryable", False):
+ return True
+ message = str(error)
+ return "502" in message and "Server Error" in message
+
+
def _run_report(
session: AuthorizedSession,
property_id: str,
@@ -188,7 +206,26 @@ def _run_report(
url = f"{GA4_API_BASE}/properties/{pid}:runReport"
for attempt in range(RUNREPORT_MAX_RETRIES + 1):
- response = session.post(url, json=body)
+ try:
+ response = session.post(url, json=body)
+ except RefreshError as e:
+ # A transient 5xx from Google's OAuth token endpoint (notably a 502, which
+ # google-auth doesn't count as retryable) is raised here while AuthorizedSession
+ # refreshes the access token, before any response exists. It clears on its own, so
+ # retry inline like a 5xx; permanent failures (invalid_grant / invalid_scope) bubble
+ # up so `get_non_retryable_errors` can stop the sync.
+ if not _is_transient_refresh_error(e) or attempt == RUNREPORT_MAX_RETRIES:
+ raise
+ wait = RUNREPORT_BACKOFF_BASE_SECONDS * (2**attempt)
+ logger.warning(
+ "GA4 runReport token refresh transient error, backing off",
+ property_id=pid,
+ attempt=attempt,
+ wait_seconds=wait,
+ )
+ time.sleep(wait)
+ continue
+
if response.ok:
return response.json()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py
index e5704bab9ca7..615ab3febc04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/tests/test_google_analytics.py
@@ -8,6 +8,7 @@ from unittest import mock
from django.db import OperationalError
import requests
+from google.auth.exceptions import RefreshError
from posthog.models.integration import Integration
@@ -28,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.google_ana
_initial_start_date,
_is_quota_error,
_is_retryable_server_error,
+ _is_transient_refresh_error,
_iter_chunks,
_parse_ga4_date,
_resolve_window,
@@ -414,6 +416,75 @@ def test_run_report_raises_http_error_for_non_quota_failures(status_code):
assert session.post.call_count == 1
+# A Bad Gateway from Google's OAuth token endpoint arrives as an HTML page, not JSON.
+_HTML_502_BODY = (
+ "<!DOCTYPE html>\n<html lang=en>\n <title>Error 502 (Server Error)!!1</title>\n"
+ " <p><b>502.</b> That's an error.\n <p>The server encountered a temporary error "
+ "and could not complete your request."
+)
+
+
+ "error,expected",
+ [
+ # 502 gateway page: google-auth omits 502 from its retryable status codes, but it's transient.
+ (RefreshError(_HTML_502_BODY), True),
+ # google-auth flags 500/503/504/408/429 (and JSON server errors) retryable itself.
+ (RefreshError("temporarily_unavailable: try again later", retryable=True), True),
+ # Revoked/expired refresh token — permanent, must not be retried inline.
+ (RefreshError("invalid_grant: Token has been expired or revoked."), False),
+ (RefreshError("invalid_scope: Bad Request"), False),
+ ],
+)
+def test_is_transient_refresh_error(error, expected):
+ assert _is_transient_refresh_error(error) is expected
+
+
+def test_run_report_retries_transient_token_refresh_error_then_succeeds(monkeypatch):
+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)
+ payload = {"rows": [], "rowCount": 0}
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ # AuthorizedSession raises RefreshError from post() when the token endpoint 502s mid-refresh.
+ RefreshError(_HTML_502_BODY),
+ _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 == 2
+
+
+def test_run_report_permanent_token_refresh_error_bubbles_without_retry(monkeypatch):
+ monkeypatch.setattr(ga.time, "sleep", lambda _: None)
+ session = mock.MagicMock()
+ session.post.side_effect = RefreshError("invalid_grant: Token has been expired or revoked.")
+
+ # A revoked/expired refresh token never recovers, so it must bubble on the first attempt
+ # (matching get_non_retryable_errors' "invalid_grant") rather than burning the inline budget.
+ with pytest.raises(RefreshError, match="invalid_grant"):
+ _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 == 1
+
+
def test_run_report_retries_server_errors_then_succeeds(monkeypatch):
monkeypatch.setattr(ga.time, "sleep", lambda _: None)
payload = {"rows": [], "rowCount": 0}