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): let large GA4 properties shorten the initial sync window (#115833)

posthog[bot]fb02a0577f77
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py
index 183f6e6ffb50..ec7e30484e38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleanalytics.py
@@ -8,4 +8,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
class GoogleAnalyticsSourceConfig(config.Config):
property_id: str
google_analytics_integration_id: int = config.value(converter=config.str_to_int)
+ history_days: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)
custom_reports: str | None = None
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 6e858982413b..00638ede0e7c 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
@@ -12,6 +12,7 @@ from google.auth.exceptions import RefreshError
from google.auth.transport.requests import AuthorizedSession
from google.oauth2.credentials import Credentials as OAuthCredentials
+from posthog.dataclasses import frozen
from posthog.models.integration import Integration
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
@@ -32,8 +33,9 @@ GA4_API_BASE = "https://analyticsdata.googleapis.com/v1beta"
# GA4 standard properties retain aggregate report data well beyond event-level
# retention, so a 2-year initial backfill is safe and matches what other GA4
-# connectors default to.
-HISTORY_DAYS = 730
+# connectors default to. Users with large properties can set a shorter window
+# when the backfill uses up the property's Data API token quota.
+DEFAULT_HISTORY_DAYS = 730
# GA4 can re-state a day's aggregates for up to ~48h after the day ends
# (processing latency), so incremental syncs re-fetch a small window before the
@@ -269,9 +271,12 @@ def _run_report(
if attempt == RUNREPORT_MAX_RETRIES:
if is_quota:
+ logger.warning("ga4_runreport_quota_exhausted", property_id=pid)
raise GoogleAnalyticsQuotaExceededError(
- f"Data API quota for property '{pid}' still exhausted after "
- f"{RUNREPORT_MAX_RETRIES} retries (retryable)"
+ f"Google Analytics Data API quota for property '{pid}' is used up. PostHog will retry "
+ "when the quota refills. If this keeps happening, set a lower 'Days of history to sync "
+ "initially' value on the source, or remove high-cardinality dimensions from your custom "
+ "reports (retryable)"
)
# A transient 5xx that never cleared — surface the HTTPError so Temporal retries the activity.
response.raise_for_status()
@@ -322,16 +327,26 @@ def _today() -> dt.date:
return dt.date.today()
-def _initial_start_date(today: dt.date) -> dt.date:
- return today - dt.timedelta(days=HISTORY_DAYS)
+def _initial_start_date(today: dt.date, history_days: int | None = None) -> dt.date:
+ if history_days is None or history_days < 1:
+ history_days = DEFAULT_HISTORY_DAYS
+ return today - dt.timedelta(days=history_days)
-def _resolve_window(today: dt.date, db_incremental_field_last_value: Any) -> tuple[dt.date, dt.date]:
+@frozen
+class _SyncWindow:
+ start: dt.date
+ end: dt.date
+
+
+def _resolve_window(
+ today: dt.date, db_incremental_field_last_value: Any, history_days: int | None = None
+) -> _SyncWindow:
# End at yesterday: today's aggregates are still accruing and would land as
# permanently stale rows for schemas whose primary key is just `date`.
end_date = today - dt.timedelta(days=1)
if db_incremental_field_last_value is None:
- return _initial_start_date(today), end_date
+ return _SyncWindow(start=_initial_start_date(today, history_days), end=end_date)
if isinstance(db_incremental_field_last_value, dt.datetime):
last = db_incremental_field_last_value.date()
@@ -340,8 +355,8 @@ def _resolve_window(today: dt.date, db_incremental_field_last_value: Any) -> tup
else:
last = dt.date.fromisoformat(str(db_incremental_field_last_value)[:10])
- start = max(last - dt.timedelta(days=LOOKBACK_DAYS), _initial_start_date(today))
- return start, end_date
+ start = max(last - dt.timedelta(days=LOOKBACK_DAYS), _initial_start_date(today, history_days))
+ return _SyncWindow(start=start, end=end_date)
def _iter_chunks(start: dt.date, end: dt.date) -> collections.abc.Iterator[tuple[dt.date, dt.date]]:
@@ -373,10 +388,13 @@ def google_analytics_source(
def get_rows() -> collections.abc.Iterator[list[dict[str, Any]]]:
today = _today()
- start_date, end_date = _resolve_window(
+ window = _resolve_window(
today,
db_incremental_field_last_value if should_use_incremental_field else None,
+ config.history_days,
)
+ start_date = window.start
+ end_date = window.end
resume_chunk_start: str | None = None
resume_offset = 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py
index 56667e20e788..678c28c5425d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/source.py
@@ -335,6 +335,19 @@ class GoogleAnalyticsSource(ResumableSource[GoogleAnalyticsSourceConfig, GoogleA
),
secret=False,
),
+ SourceFieldInputConfig(
+ name="history_days",
+ label="Days of history to sync initially (optional)",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder="730",
+ caption=(
+ "How far back the first sync of each report goes. The default is 730 days. "
+ "If a large property runs out of Google Analytics API quota, set a lower "
+ "value, for example 90 or 365."
+ ),
+ secret=False,
+ ),
],
),
)
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 eff0df84f37f..a8858aa88cbe 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
@@ -53,10 +53,10 @@ TODAY = dt.date(2026, 4, 30)
],
)
def test_resolve_window_start(last_value, expected_start):
- start, end = _resolve_window(TODAY, last_value)
- assert start == expected_start
+ window = _resolve_window(TODAY, last_value)
+ assert window.start == expected_start
# Today's aggregates are still accruing — the window always ends at yesterday.
- assert end == TODAY - dt.timedelta(days=1)
+ assert window.end == TODAY - dt.timedelta(days=1)
@pytest.mark.parametrize(
@@ -389,9 +389,12 @@ def _patch_session(monkeypatch):
)
-def _config(custom_reports: str | None = None) -> GoogleAnalyticsSourceConfig:
+def _config(custom_reports: str | None = None, history_days: int | None = None) -> GoogleAnalyticsSourceConfig:
return GoogleAnalyticsSourceConfig(
- property_id="123456789", google_analytics_integration_id=1, custom_reports=custom_reports
+ property_id="123456789",
+ google_analytics_integration_id=1,
+ custom_reports=custom_reports,
+ history_days=history_days,
)
@@ -432,6 +435,42 @@ def test_source_paginates_within_chunk_and_saves_offsets(monkeypatch):
assert [(s.chunk_start, s.offset) for s in saved_states] == [("2026-04-23", 2), ("2026-04-30", 0)]
+ "history_days,expected_first_start",
+ [
+ (None, "2024-04-30"),
+ (0, "2024-04-30"),
+ (90, "2026-01-30"),
+ ],
+)
+def test_source_initial_sync_starts_at_configured_history_window(monkeypatch, history_days, expected_first_start):
+ monkeypatch.setattr(ga, "_today", lambda: TODAY)
+ _patch_session(monkeypatch)
+
+ requested_starts: list[str] = []
+
+ def fake_run_report(session, property_id, start_date, end_date, dimensions, metrics, offset, limit=50000):
+ requested_starts.append(start_date)
+ return {}
+
+ monkeypatch.setattr(ga, "_run_report", fake_run_report)
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ response = google_analytics_source(
+ config=_config(history_days=history_days),
+ resource_name="website_overview",
+ team_id=1,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ assert requested_starts[0] == expected_first_start
+
+
def test_source_resume_past_end_date_yields_nothing(monkeypatch):
fake_today = dt.date(2026, 4, 30)
monkeypatch.setattr(ga, "_today", lambda: fake_today)