: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(data-warehouse): retry Google Search Console quota errors (#61938)
Javier Bahamondes1050dad2a10e
diff --git a/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py b/posthog/temporal/data_imports/sources/google_search_console/google_search_console.pyindex f76e67eb6395..4bc9df4b59df 100644--- a/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py+++ b/posthog/temporal/data_imports/sources/google_search_console/google_search_console.py@@ -1,4 +1,6 @@+import timeimport datetime as dt+import threadingimport dataclassesimport collections.abcfrom typing import Any@@ -6,6 +8,8 @@ from urllib.parse import quotefrom django.conf import settings+import requests+import structlogfrom google.auth.transport.requests import AuthorizedSessionfrom google.oauth2.credentials import Credentials as OAuthCredentials@@ -17,6 +21,8 @@ from posthog.temporal.data_imports.sources.common.resumable import ResumableSourfrom posthog.temporal.data_imports.sources.generated_configs import GoogleSearchConsoleSourceConfigfrom posthog.temporal.data_imports.sources.google_search_console.settings import SEARCH_ANALYTICS_SCHEMAS+logger = structlog.get_logger(__name__)+GSC_API_BASE = "https://searchconsole.googleapis.com/webmasters/v3"# Two stacked Google-side limits affect Search Analytics result completeness:@@ -48,6 +54,48 @@ ROW_LIMIT = 25000HISTORY_DAYS = 16 * 30 # Google retains ~16 months of Search Analytics dataFRESHNESS_LAG_DAYS = 3 # GSC publishes data with a 2-3 day lag+# Search Analytics is rate-limited at 1,200 QPM per site and per user, plus a+# per-second (QPS) burst cap. Paginating day-by-day across ~16 months of history+# fires requests back-to-back and trips the QPS cap, which Google reports as an+# HTTP 403 (not 429) with domain `usageLimits`. These are transient — back off+# and retry rather than failing the whole job.+# Quotas: https://developers.google.com/webmaster-tools/limits#qps-quota+QUOTA_ERROR_REASONS = frozenset({"quotaExceeded", "rateLimitExceeded", "userRateLimitExceeded"})+# dailyLimitExceeded resets at midnight, so let Temporal retry the activity instead of blocking inline.+DAILY_QUOTA_REASONS = frozenset({"dailyLimitExceeded"})+QUOTA_MAX_RETRIES = 5+QUOTA_BACKOFF_BASE_SECONDS = 2.0 # exponential: ~2, 4, 8, 16, 32s — QPS windows reset within seconds++# Proactive client-side throttle to stay under the per-site QPS burst cap before+# Google rejects us. Spaces consecutive requests to the same property; the limit+# is 1,200 QPM (20 QPS) but we leave headroom for the undocumented per-second+# burst cap. Per-process only — across workers the reactive backoff above and+# Temporal's activity retry handle the remainder.+MAX_REQUESTS_PER_SECOND_PER_SITE = 5.0+_MIN_REQUEST_INTERVAL_SECONDS = 1.0 / MAX_REQUESTS_PER_SECOND_PER_SITE+_throttle_lock = threading.Lock()+_next_request_at: dict[str, float] = {}+++def _throttle(site_url: str) -> None:+ """Block until this site's next request slot, spacing calls under the QPS cap."""+ with _throttle_lock:+ now = time.monotonic()+ scheduled = max(now, _next_request_at.get(site_url, 0.0))+ _next_request_at[site_url] = scheduled + _MIN_REQUEST_INTERVAL_SECONDS+ wait = scheduled - now+ if wait > 0:+ time.sleep(wait)+++class GoogleSearchConsoleQuotaExceededError(Exception):+ """Raised when Search Analytics quota stays exhausted after in-line retries.++ Deliberately NOT matched by `get_non_retryable_errors` so Temporal retries+ the activity later (the resumable source picks up from the last saved date),+ which is the right recovery for the longer 10-minute / daily load quotas.+ """+@dataclasses.dataclassclass GoogleSearchConsoleResumeConfig:@@ -82,6 +130,46 @@ def list_sites(session: AuthorizedSession) -> list[dict[str, Any]]:return response.json().get("siteEntry", [])+def _is_quota_error(response: requests.Response) -> bool:+ """Whether a failed response is a transient rate-limit/quota error worth retrying.++ Google reports Search Analytics QPS/QPM exhaustion as a 403 with+ `error.errors[].domain == "usageLimits"` (not a 429), which is why the+ generic 403-is-fatal handling misfires. A genuine permission failure uses+ domain `global` with reason `forbidden`/`insufficientPermissions`.+ """+ if response.status_code == 429:+ return True+ if response.status_code != 403:+ return False+ try:+ errors = response.json().get("error", {}).get("errors", [])+ except (ValueError, AttributeError, TypeError):+ return False+ return any(e.get("domain") == "usageLimits" or e.get("reason") in QUOTA_ERROR_REASONS for e in errors)+++def _is_daily_quota_error(response: requests.Response) -> bool:+ if response.status_code != 403:+ return False+ try:+ errors = response.json().get("error", {}).get("errors", [])+ except (ValueError, AttributeError, TypeError):+ return False+ return any(e.get("reason") in DAILY_QUOTA_REASONS for e in errors)+++def _quota_backoff_seconds(response: requests.Response, attempt: int) -> float:+ """Seconds to wait before retrying a quota 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)++def _query_search_analytics(session: AuthorizedSession,site_url: str,@@ -99,12 +187,44 @@ def _query_search_analytics("startRow": start_row,"dataState": "final",}- response = session.post(- f"{GSC_API_BASE}/sites/{quote(site_url, safe='')}/searchAnalytics/query",- json=body,- )- response.raise_for_status()- return response.json().get("rows", [])+ url = f"{GSC_API_BASE}/sites/{quote(site_url, safe='')}/searchAnalytics/query"++ for attempt in range(QUOTA_MAX_RETRIES + 1):+ _throttle(site_url)+ response = session.post(url, json=body)+ if response.ok:+ return response.json().get("rows", [])++ # Surface Google's real reason (e.g. usageLimits/quotaExceeded vs forbidden) —+ # raise_for_status() discards the body where that distinction lives.+ logger.warning(+ "GSC searchAnalytics.query failed",+ site_url=site_url,+ status_code=response.status_code,+ body=response.text,+ )++ if _is_daily_quota_error(response):+ raise GoogleSearchConsoleQuotaExceededError(+ f"Search Analytics daily quota for '{site_url}' exhausted; retrying at the activity level"+ )++ if not _is_quota_error(response):+ # Permission / other 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 GoogleSearchConsoleQuotaExceededError(+ f"Search Analytics quota for '{site_url}' still exhausted after {QUOTA_MAX_RETRIES} retries"+ )++ wait = _quota_backoff_seconds(response, attempt)+ logger.warning("GSC quota exceeded, backing off", site_url=site_url, attempt=attempt, wait_seconds=wait)+ time.sleep(wait)++ # Unreachable: the loop either returns, raises for status, or raises the quota error.+ raise GoogleSearchConsoleQuotaExceededError(f"Search Analytics quota for '{site_url}' exhausted")def _row_to_dict(row: dict[str, Any], dimensions: list[str], iter_date: dt.date | None = None) -> dict[str, Any]:diff --git a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.pyindex 63d9779ad17f..4b9c5a0d5adc 100644--- a/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py+++ b/posthog/temporal/data_imports/sources/google_search_console/tests/test_google_search_console.py@@ -3,13 +3,22 @@ import datetime as dtimport pytestfrom unittest import mock+import requests+from posthog.temporal.data_imports.sources.generated_configs import GoogleSearchConsoleSourceConfig+from posthog.temporal.data_imports.sources.google_search_console import google_search_console as gscfrom posthog.temporal.data_imports.sources.google_search_console.google_search_console import (FRESHNESS_LAG_DAYS,HISTORY_DAYS,+ QUOTA_MAX_RETRIES,+ GoogleSearchConsoleQuotaExceededError,GoogleSearchConsoleResumeConfig,_initial_start_date,+ _is_daily_quota_error,+ _is_quota_error,_iter_dates,+ _query_search_analytics,+ _quota_backoff_seconds,_resolve_window,_row_to_dict,google_search_console_source,@@ -254,3 +263,140 @@ def test_unknown_resource_name_raises():team_id=1,resumable_source_manager=mock.MagicMock(),)+++def _fake_response(status_code: int, json_body: dict | None = None, headers: dict | None = None):+ resp = mock.MagicMock(spec=requests.Response)+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.headers = headers or {}+ resp.text = "" if json_body is None else str(json_body)+ resp.json.return_value = json_body if json_body is not None else {}++ def raise_for_status():+ if not resp.ok:+ raise requests.HTTPError(f"{status_code} Client Error: Forbidden for url: https://example", response=resp)++ resp.raise_for_status.side_effect = raise_for_status+ return resp+++_QUOTA_BODY = {"error": {"code": 403, "errors": [{"domain": "usageLimits", "reason": "quotaExceeded"}]}}+_PERMISSION_BODY = {"error": {"code": 403, "errors": [{"domain": "global", "reason": "forbidden"}]}}+_DAILY_QUOTA_BODY = {"error": {"code": 403, "errors": [{"domain": "usageLimits", "reason": "dailyLimitExceeded"}]}}+++ "response,expected",+ [+ (_fake_response(200, {"rows": []}), False),+ (_fake_response(429), True),+ (_fake_response(403, _QUOTA_BODY), True),+ (_fake_response(403, {"error": {"errors": [{"reason": "rateLimitExceeded"}]}}), True),+ (_fake_response(403, _PERMISSION_BODY), False),+ (_fake_response(403, {}), False),+ (_fake_response(403, {"error": None}), False),+ (_fake_response(403, {"error": "Forbidden"}), False),+ (_fake_response(401), False),+ ],+)+def test_is_quota_error(response, expected):+ assert _is_quota_error(response) is expected+++ "response,expected",+ [+ (_fake_response(403, _DAILY_QUOTA_BODY), True),+ (_fake_response(403, _QUOTA_BODY), False),+ (_fake_response(403, {"error": None}), False),+ (_fake_response(403, {"error": "Forbidden"}), False),+ (_fake_response(429), False),+ (_fake_response(200, {"rows": []}), False),+ ],+)+def test_is_daily_quota_error(response, expected):+ assert _is_daily_quota_error(response) is expected+++def test_quota_backoff_prefers_retry_after_header():+ resp = _fake_response(403, _QUOTA_BODY, headers={"Retry-After": "30"})+ assert _quota_backoff_seconds(resp, attempt=0) == 30.0+++def test_quota_backoff_falls_back_to_exponential():+ resp = _fake_response(403, _QUOTA_BODY)+ assert _quota_backoff_seconds(resp, attempt=0) == 2.0+ assert _quota_backoff_seconds(resp, attempt=2) == 8.0+++def test_query_retries_quota_then_succeeds(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.side_effect = [+ _fake_response(403, _QUOTA_BODY),+ _fake_response(403, _QUOTA_BODY),+ _fake_response(200, {"rows": [{"keys": ["2026-04-15"], "clicks": 1}]}),+ ]++ rows = _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ assert rows == [{"keys": ["2026-04-15"], "clicks": 1}]+ assert session.post.call_count == 3+++def test_query_raises_quota_error_after_max_retries(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.return_value = _fake_response(403, _QUOTA_BODY)++ with pytest.raises(GoogleSearchConsoleQuotaExceededError):+ _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ # Initial attempt + QUOTA_MAX_RETRIES retries.+ assert session.post.call_count == QUOTA_MAX_RETRIES + 1+++def test_query_daily_quota_raises_without_retry(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.return_value = _fake_response(403, _DAILY_QUOTA_BODY)++ with pytest.raises(GoogleSearchConsoleQuotaExceededError):+ _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ assert session.post.call_count == 1+++def test_query_permission_error_is_not_retried(monkeypatch):+ monkeypatch.setattr(gsc.time, "sleep", lambda _s: None)+ monkeypatch.setattr(gsc, "_throttle", lambda _site: None)++ session = mock.MagicMock()+ session.post.return_value = _fake_response(403, _PERMISSION_BODY)++ with pytest.raises(requests.HTTPError, match="403 Client Error"):+ _query_search_analytics(session, "sc-domain:example.com", "2026-04-15", "2026-04-15", ["date"], 0)++ # Fatal on the first response — no retries.+ assert session.post.call_count == 1+++def test_throttle_spaces_requests_per_site(monkeypatch):+ gsc._next_request_at.clear()+ fake_now = {"t": 100.0}+ sleeps: list[float] = []+ monkeypatch.setattr(gsc.time, "monotonic", lambda: fake_now["t"])+ monkeypatch.setattr(gsc.time, "sleep", lambda s: sleeps.append(s))++ # First call for a site doesn't wait; the next is spaced by the min interval.+ gsc._throttle("sc-domain:example.com")+ gsc._throttle("sc-domain:example.com")++ assert sleeps == [pytest.approx(gsc._MIN_REQUEST_INTERVAL_SECONDS)]