: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(google_ads): back off and retry transient DB pool timeouts when fetching integration (#66446)
Tom Owersd0d6a4f5a132
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.pyindex 727fdf5505cb..d5a8c1637de8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py@@ -75,6 +75,11 @@ def _ensure_grpc_receive_limit() -> None:options.append((_GRPC_MAX_RECEIVE_MESSAGE_LENGTH_KEY, GRPC_MAX_RECEIVE_MESSAGE_LENGTH))+def _backoff_sleep(attempt: int) -> None:+ """Sleep before the next retry: linear growth capped at 30s (2s, 4s, 6s, ...)."""+ time.sleep(min(2 * attempt, 30))++# ``GoogleAdsClient`` performs an OAuth token refresh at construction, reaching Google's token# endpoint over the network. Two failure shapes on that hop are transient and usually clear on a# short backoff: a connection-level hiccup (e.g. a proxy timeout) surfaces as@@ -126,26 +131,35 @@ def _load_client_with_transient_retry(attempt += 1if attempt >= max_attempts or not _is_transient_client_init_error(e):raise- time.sleep(min(2 * attempt, 30))+ _backoff_sleep(attempt)+++_MAX_INTEGRATION_FETCH_ATTEMPTS = 4def _get_integration(integration_id: int, team_id: int) -> Integration:- """Fetch the OAuth ``Integration`` row, retrying once if the DB connection was dropped.+ """Fetch the OAuth ``Integration`` row, retrying a transient DB failure with backoff.Temporal activities run in a long-lived worker that never goes through Django's request- cycle, so a pooled Postgres connection can be closed server-side while it sits idle.- ``close_old_connections()`` evicts connections already known to be stale, but one can still- die in the window before the query runs and surface as a transient ``OperationalError``- ("server closed the connection unexpectedly"). The failed query marks the connection- unusable, so a second eviction drops it and the retry runs on a fresh connection. This read- is idempotent, so it is safe to repeat. ``Integration.DoesNotExist`` is left to propagate.+ cycle, so a pooled Postgres connection can be closed server-side while it sits idle, or the+ connection pooler can reject the query with a wait timeout when the pool is saturated. Both+ surface as a transient ``OperationalError`` and both clear once a healthy connection is used.+ ``close_old_connections()`` evicts connections already known to be stale (and, after a failed+ query marks one unusable, drops it), so each attempt runs on a fresh connection; the short+ backoff also gives a saturated pool time to drain rather than retrying straight back into the+ same wait timeout. This read is idempotent, so it is safe to repeat. Mirrors the backoff shape+ of the client-init and search retries. ``Integration.DoesNotExist`` is left to propagate."""- close_old_connections()- try:- return Integration.objects.get(id=integration_id, team_id=team_id)- except OperationalError:+ attempt = 0+ while True:close_old_connections()- return Integration.objects.get(id=integration_id, team_id=team_id)+ try:+ return Integration.objects.get(id=integration_id, team_id=team_id)+ except OperationalError:+ attempt += 1+ if attempt >= _MAX_INTEGRATION_FETCH_ATTEMPTS:+ raise+ _backoff_sleep(attempt)def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> GoogleAdsClient:@@ -568,7 +582,7 @@ def _call_with_transient_retry(attempt += 1if attempt >= max_attempts or not _is_transient_grpc_error(e):raise- time.sleep(min(2 * attempt, 30))+ _backoff_sleep(attempt)def _search_with_transient_retry(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.pyindex 2dc76504f14b..923b3d88d98f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/tests/test_google_ads_source.py@@ -866,7 +866,11 @@ class TestGetIntegrationDbResilience:integration = object()get = mock.Mock(side_effect=[OperationalError("server closed the connection unexpectedly"), integration])- with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH) as close:+ with (+ mock.patch(_INTEGRATION_GET_PATH, get),+ mock.patch(_CLOSE_CONNECTIONS_PATH) as close,+ mock.patch(_SLEEP_PATH),+ ):result = _get_integration(integration_id=1, team_id=2)assert result is integration@@ -874,15 +878,46 @@ class TestGetIntegrationDbResilience:# Evicted up front, then again after the failed query marked the connection unusable.assert close.call_count == 2- def test_reraises_when_retry_also_fails(self):- get = mock.Mock(side_effect=OperationalError("server closed the connection unexpectedly"))+ def test_rides_out_pool_wait_timeout_then_succeeds(self):+ integration = object()+ # A saturated connection pooler rejects the query with a wait timeout (surfaced as an+ # OperationalError); the previous immediate single retry hit the same saturation, so we+ # back off and retry a few times before giving up.+ get = mock.Mock(+ side_effect=[+ OperationalError("query_wait_timeout"),+ OperationalError("query_wait_timeout"),+ integration,+ ]+ )- with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH):+ with (+ mock.patch(_INTEGRATION_GET_PATH, get),+ mock.patch(_CLOSE_CONNECTIONS_PATH),+ mock.patch(_SLEEP_PATH) as sleep,+ ):+ result = _get_integration(integration_id=1, team_id=2)++ assert result is integration+ assert get.call_count == 3+ # Backoff grows per attempt per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.+ assert sleep.call_args_list == [mock.call(2), mock.call(4)]++ def test_reraises_after_exhausting_attempts(self):+ get = mock.Mock(side_effect=OperationalError("query_wait_timeout"))++ with (+ mock.patch(_INTEGRATION_GET_PATH, get),+ mock.patch(_CLOSE_CONNECTIONS_PATH),+ mock.patch(_SLEEP_PATH) as sleep,+ ):with pytest.raises(OperationalError):_get_integration(integration_id=1, team_id=2)- # One retry only — the second failure propagates so Temporal still retries the activity.- assert get.call_count == 2+ # Bounded attempts: it gives up rather than looping forever, leaving Temporal to retry.+ assert get.call_count == 4+ # Backed off between each attempt (2s, 4s, 6s) but not after the final attempt that re-raises.+ assert sleep.call_args_list == [mock.call(2), mock.call(4), mock.call(6)]def test_missing_integration_is_not_retried(self):get = mock.Mock(side_effect=Integration.DoesNotExist())