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): stop sync gracefully on daily rate limit (#64608)

Tom Owersba24710af7a3
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
index 1a603a38e3ae..fb8b728f3f6b 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
@@ -18,7 +18,7 @@ from posthog.temporal.data_imports.sources.generated_configs import LinkedinAdsS
from products.data_warehouse.backend.types import IncrementalFieldType
-from .client import LinkedinAdsClient, LinkedinAdsResource
+from .client import LinkedinAdsClient, LinkedinAdsDailyRateLimitError, LinkedinAdsResource
from .schemas import FLOAT_FIELDS, RESOURCE_SCHEMAS, URN_COLUMNS, VIRTUAL_COLUMN_URN_MAPPING
module_logger = structlog.get_logger(__name__)
@@ -193,21 +193,30 @@ def linkedin_ads_source(
batcher = Batcher(logger=logger)
pending_next_page_token: str | None = None
- for page, next_page_token in data_pages:
- # None signals an unflattenable PK (malformed creative URN) — drop the row.
- flattened_records = [
- flat for record in page if (flat := _flatten_linkedin_record(record, schema)) is not None
- ]
- for record in flattened_records:
- batcher.batch(record)
- if batcher.should_yield():
- yield batcher.get_table()
- if pending_next_page_token is not None:
- resumable_source_manager.save_state(LinkedInAdsResumeConfig(page_token=pending_next_page_token))
- pending_next_page_token = None
-
- if next_page_token is not None:
- pending_next_page_token = next_page_token
+ try:
+ for page, next_page_token in data_pages:
+ # None signals an unflattenable PK (malformed creative URN) — drop the row.
+ flattened_records = [
+ flat for record in page if (flat := _flatten_linkedin_record(record, schema)) is not None
+ ]
+ for record in flattened_records:
+ batcher.batch(record)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if pending_next_page_token is not None:
+ resumable_source_manager.save_state(
+ LinkedInAdsResumeConfig(page_token=pending_next_page_token)
+ )
+ pending_next_page_token = None
+
+ if next_page_token is not None:
+ pending_next_page_token = next_page_token
+ except LinkedinAdsDailyRateLimitError:
+ # The per-member/app daily call budget only resets at midnight UTC, so there's no more
+ # data to fetch today. Stop here rather than failing the job: progress so far is durable
+ # (resume token for entity finders, incremental field value for analytics) and the next
+ # scheduled sync continues from where we left off.
+ logger.info(f"LinkedInAds: daily rate limit reached, stopping {resource_name} early for this run")
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
index e7bc3c9d9f6f..101032f8ed79 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
@@ -10,6 +10,7 @@ import pyarrow as pa
from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from posthog.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfig
+from posthog.temporal.data_imports.sources.linkedin_ads.client import LinkedinAdsDailyRateLimitError
from posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads import (
INITIAL_ANALYTICS_LOOKBACK_DAYS,
LinkedInAdsResumeConfig,
@@ -603,6 +604,78 @@ class TestLinkedinAdsSource:
# Final page of a resume has no next token → no save.
manager.save_state.assert_not_called()
+ @mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.Batcher")
+ def test_daily_rate_limit_stops_gracefully_and_flushes_batched_rows(self, mock_batcher_cls, mock_client_func):
+ """A daily rate limit raised mid-stream must not fail the job. We stop fetching, flush the
+ rows already batched, and keep the most recent durable resume token so the next scheduled
+ sync continues from there."""
+ mock_batcher_cls.side_effect = _small_batcher_factory(chunk_size=2)
+
+ def pages_then_rate_limit():
+ yield ([{"id": "p1-a"}, {"id": "p1-b"}], "token-2") # fills buffer, flush, pending=None
+ yield ([{"id": "p2-a"}, {"id": "p2-b"}], "token-3") # fills buffer, flush, advances to token-2
+ yield ([{"id": "p3-a"}], "token-4") # one record left buffered
+ raise LinkedinAdsDailyRateLimitError('LinkedIn daily rate limit reached (429): {"status":429}')
+
+ mock_client = mock.MagicMock()
+ mock_client.get_data_by_resource.return_value = pages_then_rate_limit()
+ mock_client_func.return_value = mock_client
+
+ config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")
+ manager = _make_resume_manager(can_resume=False)
+
+ result = linkedin_ads_source(
+ config=config,
+ resource_name="campaigns",
+ team_id=789,
+ resumable_source_manager=manager,
+ logger=mock.MagicMock(),
+ )
+
+ items = result.items()
+ assert isinstance(items, Iterable)
+ rows = list(items) # must not raise
+ assert all(isinstance(r, pa.Table) for r in rows)
+ # Two mid-stream flushes of 2 rows, then the final incomplete-chunk flush of the
+ # single buffered p3-a row.
+ assert [r.num_rows for r in rows] == [2, 2, 1]
+
+ # Only token-2 is durably saved: it's committed once page 2's flush proves page 1's rows are
+ # written. Page 3 holds a single record that never triggers its own mid-stream flush, so
+ # token-3 stays pending and the final incomplete-chunk flush deliberately skips save_state.
+ # Resume from token-2 re-fetches the rest — already-written rows are deduped by primary key.
+ assert manager.save_state.call_args_list == [
+ mock.call(LinkedInAdsResumeConfig(page_token="token-2")),
+ ]
+
+ def test_daily_rate_limit_on_first_page_yields_nothing_without_error(self, mock_client_func):
+ """Hitting the daily limit before any data is fetched stops cleanly with no rows and no state."""
+
+ def rate_limit_immediately():
+ yield from () # makes this a generator that yields nothing before raising
+ raise LinkedinAdsDailyRateLimitError('LinkedIn daily rate limit reached (429): {"status":429}')
+
+ mock_client = mock.MagicMock()
+ mock_client.get_data_by_resource.return_value = rate_limit_immediately()
+ mock_client_func.return_value = mock_client
+
+ config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")
+ manager = _make_resume_manager(can_resume=False)
+
+ result = linkedin_ads_source(
+ config=config,
+ resource_name="campaigns",
+ team_id=789,
+ resumable_source_manager=manager,
+ logger=mock.MagicMock(),
+ )
+
+ items = result.items()
+ assert isinstance(items, Iterable)
+ rows = list(items)
+ assert rows == []
+ manager.save_state.assert_not_called()
+
def test_empty_first_page_does_not_save_state(self, mock_client_func):
"""Empty first page (no next token): no yields, no save_state."""
mock_client = mock.MagicMock()