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(linkedin_ads): back off and retry transient DB errors when fetching integration (#66465)

Tom Owers30498c8c6694
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
index 668f7812fc35..256c6cb62458 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
@@ -1,9 +1,10 @@
+import time
import typing
import datetime as dt
import collections.abc
from dataclasses import dataclass
-from django.db import close_old_connections
+from django.db import OperationalError, close_old_connections
import pyarrow as pa
import structlog
@@ -109,15 +110,42 @@ def get_schemas() -> dict[str, LinkedinAdsSchema]:
return schemas
+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))
+
+
+_MAX_INTEGRATION_FETCH_ATTEMPTS = 4
+
+
+def _get_integration(integration_id: int, team_id: int) -> Integration:
+ """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, 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. ``Integration.DoesNotExist``
+ is left to propagate.
+ """
+ attempt = 0
+ while True:
+ close_old_connections()
+ 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 linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> LinkedinAdsClient:
"""Initialize a LinkedIn Ads client with provided config."""
- # Temporal activities run in a thread pool where Django DB connections can go
- # stale between uses (Postgres closes the connection server-side). This is
- # invoked lazily from inside `get_rows`, so the connection has often been idle
- # for minutes by the time we reach it — drop any stale connection first, else
- # the read surfaces as `OperationalError: the connection is closed`.
- close_old_connections()
- integration = Integration.objects.get(id=config.linkedin_ads_integration_id, team_id=team_id)
+ integration = _get_integration(config.linkedin_ads_integration_id, team_id)
# LinkedIn access tokens expire (~60 days). Refresh a stale-but-refreshable token here so it gets
# renewed instead of 401ing into a forced re-authorization. `access_token_expired` is a no-op when
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
index 333a27614638..721726bf1cad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
@@ -6,10 +6,12 @@ from functools import partial
import pytest
from unittest import mock
+from django.db import OperationalError
+
import pyarrow as pa
from parameterized import parameterized
-from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfig
@@ -24,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_a
_convert_timestamp_to_date,
_extract_type_and_id_from_urn,
_flatten_linkedin_record,
+ _get_integration,
linkedin_ads_client,
linkedin_ads_source,
)
@@ -397,6 +400,81 @@ class TestLinkedinAdsClientFunction:
assert calls == ["close_old_connections", "Integration.objects.get"]
+_INTEGRATION_GET_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.linkedin_ads.Integration.objects.get"
+)
+_CLOSE_CONNECTIONS_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.linkedin_ads.close_old_connections"
+)
+_SLEEP_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.linkedin_ads.time.sleep"
+
+
+class TestGetIntegrationDbResilience:
+ def test_retries_on_dropped_connection_then_succeeds(self):
+ 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,
+ mock.patch(_SLEEP_PATH),
+ ):
+ result = _get_integration(integration_id=1, team_id=2)
+
+ assert result is integration
+ assert get.call_count == 2
+ # Evicted up front, then again after the failed query marked the connection unusable.
+ assert close.call_count == 2
+
+ def test_rides_out_pool_wait_timeout_then_succeeds(self):
+ integration = object()
+ 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),
+ 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)
+
+ # Bounded attempts: it gives up rather than looping forever, leaving Temporal to retry the activity.
+ 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())
+
+ with mock.patch(_INTEGRATION_GET_PATH, get), mock.patch(_CLOSE_CONNECTIONS_PATH), mock.patch(_SLEEP_PATH):
+ with pytest.raises(Integration.DoesNotExist):
+ _get_integration(integration_id=1, team_id=2)
+
+ # A deleted integration row is non-retryable — don't mask it as a transient drop.
+ assert get.call_count == 1
+
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.linkedin_ads.OauthIntegration"
)