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(tiktok-ads): retry in-body rate limits mid-pagination (#82775)

Javier Bahamondes14c62a3443c4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py
index 5a871312804f..8d3d34d19e93 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/config_setup.py
@@ -337,24 +337,49 @@ def _find_resolved_params(endpoint_config: Endpoint) -> list[ResolvedParam]:
]
+_UNPARSED = object()
+
+
+def _json_field_value(body: object, path: str) -> object:
+ current = body
+ for key in path.split("."):
+ if not isinstance(current, dict):
+ return None
+ current = current.get(key)
+ return current
+
+
def _handle_response_actions(response: Response, actions: list[ResponseAction]) -> Optional[ResponseAction]:
content = response.text
+ # Parsed at most once per response, and only when an action actually matches on the body.
+ parsed_body: object = _UNPARSED
for action in actions:
- status_code = action.get("status_code")
- content_substr = action.get("content")
if action.get("action") is None:
continue
- if status_code is not None and content_substr is not None:
- if response.status_code == status_code and content_substr in content:
- return action
- elif status_code is not None:
- if response.status_code == status_code:
- return action
- elif content_substr is not None:
- if content_substr in content:
- return action
+ criteria: list[bool] = []
+
+ status_code = action.get("status_code")
+ if status_code is not None:
+ criteria.append(response.status_code == status_code)
+
+ content_substr = action.get("content")
+ if content_substr is not None:
+ criteria.append(content_substr in content)
+
+ json_field = action.get("json_field")
+ if json_field is not None:
+ if parsed_body is _UNPARSED:
+ try:
+ parsed_body = response.json()
+ except ValueError:
+ parsed_body = None
+ criteria.append(_json_field_value(parsed_body, json_field) in (action.get("json_values") or []))
+
+ # An action with no criteria at all would otherwise match every response.
+ if criteria and all(criteria):
+ return action
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py
index 331d28eef34c..f229b11d15d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_response_action_classification.py
@@ -121,3 +121,45 @@ class TestResponseActionClassification:
client = RESTClient(base_url="https://api.example.com", max_retry_attempts=1)
with pytest.raises(HTTPError):
list(client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator(), hooks=hooks))
+
+ @patch("tenacity.nap.time.sleep")
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_json_field_action_matches_body_value_only(self, MockSession, _sleep) -> None:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock()
+ mock_session.send.side_effect = [
+ _make_response({"code": 40100, "message": "too many requests"}),
+ # A row that merely contains the same number must not be classified as an error —
+ # what substring matching on the serialized body would get wrong.
+ _make_response({"code": 0, "results": [{"id": 40100}]}),
+ ]
+ hooks = create_response_hooks([{"json_field": "code", "json_values": [40100], "action": "retry"}])
+
+ client = RESTClient(base_url="https://api.example.com")
+ pages = list(
+ client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator(), hooks=hooks)
+ )
+
+ assert pages == [[{"id": 40100}]]
+ assert mock_session.send.call_count == 2
+
+ @patch("tenacity.nap.time.sleep")
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_json_field_action_reads_a_nested_path(self, MockSession, _sleep) -> None:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.return_value = MagicMock()
+ mock_session.send.side_effect = [
+ _make_response({"error": {"type": "rate_limit"}}),
+ _make_response({"results": [{"id": 1}]}),
+ ]
+ hooks = create_response_hooks([{"json_field": "error.type", "json_values": ["rate_limit"], "action": "retry"}])
+
+ client = RESTClient(base_url="https://api.example.com")
+ pages = list(
+ client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator(), hooks=hooks)
+ )
+
+ assert pages == [[{"id": 1}]]
+ assert mock_session.send.call_count == 2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
index 90a715018a7b..6368cd854b6c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py
@@ -231,6 +231,13 @@ class ResolvedParam:
class ResponseAction(TypedDict, total=False):
status_code: Optional[int | str]
content: Optional[str]
+ # Match on a value inside the parsed JSON body rather than on raw text. ``json_field`` is a
+ # dotted path from the body root (e.g. ``"code"``, ``"error.type"``) and the action matches when
+ # the value there is one of ``json_values``. For an API that answers HTTP 200 and carries the
+ # outcome in the body: substring matching on the serialized body would depend on the API's
+ # whitespace and on the value not appearing elsewhere in the payload.
+ json_field: Optional[str]
+ json_values: Optional[list[Any]]
# One of:
# - "ignore" — treat the matched response as a valid empty page and stop pagination.
# - "retry" — raise a retryable error so the request is re-issued (for an HTTP-200 body-level
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads.py
index 620bafc73a9b..b303f0aec342 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads.py
@@ -10,6 +10,9 @@ from unittest.mock import MagicMock, Mock, patch
from parameterized import parameterized
from requests import Response
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.tiktok_ads import (
TikTokAdsResumeConfig,
get_tiktok_resource,
@@ -603,3 +606,66 @@ class TestTikTokAdsReportChunkResumeBehavior:
assert saved.page == 2
assert saved.chunk_start_date == chunk0_start
assert saved.chunk_end_date == chunk0_end
+
+
+class TestTikTokAdsTransientErrorRetry:
+ """TikTok signals rate limits with HTTP 200 + a body `code`, so the request has to be
+ reissued from inside the rest client — the paginator can't re-request a page."""
+
+ def setup_method(self):
+ self.advertiser_id = "123456789"
+
+ def _run_campaigns(self, responses: list[Response]) -> tuple[list[Any], MagicMock]:
+ with (
+ patch("tenacity.nap.time.sleep"),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession,
+ ):
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = responses
+
+ response = tiktok_ads_source(
+ advertiser_id=self.advertiser_id,
+ endpoint="campaigns",
+ team_id=123,
+ job_id="test_job",
+ access_token="test_access_token",
+ db_incremental_field_last_value=None,
+ resumable_source_manager=_make_manager(can_resume=False),
+ should_use_incremental_field=False,
+ )
+ rows = list(cast(Iterable[Any], response.items()))
+ return rows, mock_session
+
+ def test_qps_limit_mid_pagination_is_reissued(self):
+ responses = [
+ _page_response(page=1, total_pages=2, items=[{"campaign_id": "c1"}]),
+ _make_response({"code": 40100, "message": "App reaches the QPS limit 10, current QPS is 11."}),
+ _page_response(page=2, total_pages=2, items=[{"campaign_id": "c2"}]),
+ ]
+
+ rows, mock_session = self._run_campaigns(responses)
+
+ assert mock_session.send.call_count == 3
+ assert [row["campaign_id"] for row in rows] == ["c1", "c2"]
+
+ def test_persistent_qps_limit_surfaces_transient_message(self):
+ responses = [
+ _make_response({"code": 40100, "message": "App reaches the QPS limit 10, current QPS is 11."})
+ ] * 20
+
+ with pytest.raises(RESTClientRetryableError, match="rate-limiting"):
+ self._run_campaigns(responses)
+
+ def test_non_retryable_code_is_not_reissued(self):
+ responses = [
+ _make_response(
+ {"code": 40001, "message": "advertiser does not grant you /file/video/ad/search/:GET permission"}
+ )
+ ]
+
+ with pytest.raises(ValueError, match="non-retryable"):
+ self._run_campaigns(responses)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
index eae6934d3cc2..e0a9cb305181 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/tiktok_ads.py
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads
EndpointType,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import (
+ TIKTOK_RETRY_RESPONSE_ACTIONS,
TikTokAdsAPIError,
TikTokAdsAuth,
TikTokAdsPaginator,
@@ -86,6 +87,7 @@ def get_tiktok_resource(
}
endpoint["params"] = params
+ endpoint["response_actions"] = TIKTOK_RETRY_RESPONSE_ACTIONS
resource["endpoint"] = endpoint
if should_use_incremental_field and config.incremental_fields:
@@ -137,6 +139,9 @@ def _iter_chunk(
"client": {
"base_url": BASE_URL,
"auth": TikTokAdsAuth(access_token),
+ # The QPS ceiling is per app, so every concurrent schema competes for the same budget.
+ # A few extra attempts (backoff caps at 60s) ride out that contention.
+ "max_retries": 8,
},
"resource_defaults": {
"write_disposition": "replace",
@@ -147,10 +152,9 @@ def _iter_chunk(
# NOTE: ``rest_api_resource`` returns a lazy iterable; actual HTTP
# requests happen when the caller consumes it in ``process_resources``.
# The retry below therefore only guards the (fast, rare-to-fail)
- # resource-construction step — mid-pagination TikTok errors propagate
- # out and are not retried here. Per-request retries would need to live
- # inside the paginator or rest_client. Kept as-is to preserve existing
- # behaviour.
+ # resource-construction step. Mid-pagination retries live one level down,
+ # in the rest client: ``TIKTOK_RETRY_RESPONSE_ACTIONS`` classifies TikTok's
+ # HTTP-200 error envelope so a transient code reissues the request there.
resource = make_sync_retryable_with_exponential_backoff(
lambda: rest_api_resource(
chunk_config,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
index fadea69f1307..74bd208eab04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
@@ -13,6 +13,7 @@ from requests.exceptions import HTTPError, RequestException, Timeout
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.settings import (
BASE_URL,
MAX_TIKTOK_DAYS_FOR_REPORT_ENDPOINTS,
@@ -85,6 +86,39 @@ def list_advertisers(access_token: str) -> list[dict]:
return (body.get("data") or {}).get("list") or []
+# https://business-api.tiktok.com/portal/docs?rid=xmtaqatxqj8&id=1737172488964097
+TIKTOK_RETRYABLE_ERROR_CODES = [
+ 40016, # Requests made too frequently
+ 40100, # Requests made too frequently
+ 40101, # Requests made too frequently
+ 40102, # Requests made too frequently for a certain field value.
+ 40200, # Task error
+ 40201, # Task is not ready
+ 40202, # Write or update entity conflict
+ 40700, # Internal service validation error
+ 50000, # System error
+ 50002, # Error processing request on TikTok side. Please see error message for details.
+ 51001, # Internal service timeout. Transient TikTok-side error; safe to retry.
+ 51002, # Internal service error. Transient TikTok-side error; TikTok's own message asks to retry later.
+ 51039, # Internal service timeout. Transient TikTok-side error; safe to retry.
+ 51305, # Satellite service error
+ 60001, # The system is in maintenance.
+]
+
+# TikTok answers HTTP 200 for these, so the rest client's own 429/5xx check never fires. Matching
+# the body `code` inside the response hook reissues the request from within the client's retry loop;
+# without it a rate limit hit mid-pagination escapes to the paginator, which cannot re-request, and
+# fails the whole schema. The QPS ceiling is per app and shared across every concurrent sync, so
+# hitting it is routine rather than exceptional.
+TIKTOK_RETRY_RESPONSE_ACTIONS: list[ResponseAction] = [
+ {
+ "json_field": "code",
+ "json_values": TIKTOK_RETRYABLE_ERROR_CODES,
+ "action": "retry",
+ "message": TIKTOK_TRANSIENT_ERROR_MESSAGE,
+ }
+]
+
# Prefix for the ValueError the paginator raises on client error codes outside the retryable set.
# 40001 is a generic bucket covering both a deleted advertiser and per-endpoint permission denials,
# so callers have to discriminate on wording rather than on the code. Retrying never succeeds, so
@@ -483,26 +517,11 @@ class TikTokAdsPaginator(BasePaginator):
response_status=response.status_code,
)
- # https://business-api.tiktok.com/portal/docs?rid=xmtaqatxqj8&id=1737172488964097
- retryable_codes = [
- 40016, # Requests made too frequently
- 40100, # Requests made too frequently
- 40101, # Requests made too frequently
- 40102, # Requests made too frequently for a certain field value.
- 40200, # Task error
- 40201, # Task is not ready
- 40202, # Write or update entity conflict
- 40700, # Internal service validation error
- 50000, # System error
- 50002, # Error processing request on TikTok side. Please see error message for details.
- 51001, # Internal service timeout. Transient TikTok-side error; safe to retry.
- 51002, # Internal service error. Transient TikTok-side error; TikTok's own message asks to retry later.
- 51039, # Internal service timeout. Transient TikTok-side error; safe to retry.
- 51305, # Satellite service error
- 60001, # The system is in maintenance.
- ]
-
- if api_code in retryable_codes:
+ # Endpoints carrying TIKTOK_RETRY_RESPONSE_ACTIONS never reach this branch with a
+ # retryable code: the response hook reissues the request, and raises its own error
+ # once the retry budget is spent. This stays as the fallback for endpoints that
+ # don't declare the actions.
+ if api_code in TIKTOK_RETRYABLE_ERROR_CODES:
raise TikTokAdsAPIError(
f"TikTok API error: {error_message} (code: {api_code})", api_code=api_code, response=response
)