: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(data-warehouse): stop etsy syncs burning the app's daily api quota (#104171)
Tom Owers24da3947f732
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.pyindex 85cc00396fe6..4a23b405cd04 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/etsy.py@@ -37,11 +37,46 @@ NO_SHOP_ERROR = ()INVALID_SHOP_ID_ERROR = "The Etsy shop ID must be a positive number. Leave it blank to use the token's own shop."+# Etsy meters each app's own API key, as a per-second allowance and then a sliding 24-hour quota.+# When a refusal carries this header, a zero says the day's quota is gone rather than a burst.+REMAINING_TODAY_HEADER = "x-remaining-today"++# Stable sentinels the source classifies on. Keep them in step with `EtsySource`.+DAILY_QUOTA_EXHAUSTED_ERROR = "Etsy daily request quota exhausted"+RATE_LIMITED_ERROR = "Etsy rate limit reached"++DAILY_QUOTA_EXHAUSTED_MESSAGE = (+ "Your Etsy app has used its whole 24 hour request quota, so this sync stopped early. The quota frees up again "+ "over the next 24 hours and the next sync carries on from here. If it keeps happening, ask Etsy to raise your "+ "app's daily limit or sync this source less often."+)+RATE_LIMITED_MESSAGE = (+ "Etsy is rate limiting your app's requests, so this sync stopped early. The next sync carries on from here. "+ "If it keeps happening, ask Etsy to raise your app's rate limit."+)+RATE_LIMITED_VALIDATION_MESSAGE = (+ "Etsy is rate limiting your app, so we could not check these credentials. Try again in a few minutes."+)+class EtsyAPIError(Exception):"""An Etsy request failed in a way the caller cannot recover from."""+class EtsyRateLimitError(EtsyAPIError):+ """Etsy refused the request because the app is out of requests."""+++def _remaining_today(response: Response) -> Optional[int]:+ raw = response.headers.get(REMAINING_TODAY_HEADER)+ if raw is None:+ return None+ try:+ return int(raw)+ except ValueError:+ return None++def _validate_shop_id(shop_id: str) -> str:"""Etsy shop IDs are positive integers. Reject anything else before it reaches the URL."""if not shop_id.isdigit() or int(shop_id) <= 0:@@ -78,6 +113,8 @@ class EtsyClient:self._refresh_token = refresh_tokenself._logger = loggerself._access_token: Optional[str] = None+ self._shop_opened_at: Optional[int] = None+ self._shop_opened_at_resolved = Falseself._session = make_tracked_session(headers={"x-api-key": f"{api_key}:{shared_secret}", "Accept": "application/json"},redact_values=(api_key, shared_secret, refresh_token),@@ -119,6 +156,14 @@ class EtsyClient:self._access_token = self._mint_token()response = self._send(path, params)+ if response.status_code == 429:+ # The tracked session already retried this while honoring Etsy's retry-after, so what+ # reaches here is a limit no backoff inside the run can clear. Raising now also stops+ # the walk from spending the rest of the quota on requests that can only be refused.+ raise EtsyRateLimitError(+ DAILY_QUOTA_EXHAUSTED_ERROR if _remaining_today(response) == 0 else RATE_LIMITED_ERROR+ )+if response.status_code >= 300:self._logger.error(f"Etsy API error: status={response.status_code}, path={path}, body={response.text[:500]}"@@ -142,6 +187,23 @@ class EtsyClient:raise EtsyAPIError(NO_SHOP_ERROR)return str(shop_id)+ def shop_opened_at(self, shop_id: str) -> Optional[int]:+ """Epoch second the shop opened, or None when Etsy reports no usable value.++ Nothing a shop owns predates the shop, so a walk with no cursor starts here rather than at+ Etsy's launch year. Every window in between can only come back empty, and each one spends a+ request against the app's daily quota, which is what a sync runs out of before it finishes.+ """+ if not self._shop_opened_at_resolved:+ # getShop needs no OAuth scope, so this stays readable for any token the source accepts.+ opened_at = self.request(f"/shops/{shop_id}").get("created_timestamp")+ try:+ self._shop_opened_at = int(opened_at) if opened_at is not None else None+ except (TypeError, ValueError):+ self._shop_opened_at = None+ self._shop_opened_at_resolved = True+ return self._shop_opened_at+def validate_credentials(api_key: str, shared_secret: str, refresh_token: str, shop_id: Optional[str]@@ -161,6 +223,8 @@ def validate_credentials(# No job logger exists on the create-time probe path, so use the module logger.client = EtsyClient(api_key, shared_secret, refresh_token, structlog.get_logger(__name__))identity = client.request("/users/me")+ except EtsyRateLimitError:+ return False, RATE_LIMITED_VALIDATION_MESSAGEexcept Exception:return False, "Could not authenticate with Etsy. Check your API keystring, shared secret and refresh token."@@ -326,7 +390,8 @@ def get_rows() -> Iterator[list[dict[str, Any]]]:config = ETSY_ENDPOINTS[endpoint]client = EtsyClient(api_key, shared_secret, refresh_token, logger)- path = f"/shops/{client.resolve_shop_id(shop_id)}{config.path}"+ resolved_shop_id = client.resolve_shop_id(shop_id)+ path = f"/shops/{resolved_shop_id}{config.path}"resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None@@ -341,14 +406,24 @@ def get_rows(if window_param is None:yield from _offset_pages(client, path, config, resumable_source_manager, resume, logger)else:+ end = int(time.time())start = _window_start(should_use_incremental_field, db_incremental_field_last_value)+ # A resumed walk carries on from its saved window, so `start` is unused and looking the+ # shop up would only spend a request.+ resuming_window = resume is not None and resume.window_start is not None+ if start == ETSY_HISTORY_START and not resuming_window:+ opened_at = client.shop_opened_at(resolved_shop_id)+ # A missing or clock-skewed opening date falls back to the full range, so a bad+ # value can never shorten the walk.+ if opened_at is not None and ETSY_HISTORY_START < opened_at <= end:+ start = opened_atyield from _windowed_pages(client,path,config,window_param,start,- int(time.time()),+ end,resumable_source_manager,resume,logger,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.pyindex f33240efeedf..229aae32164a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/source.py@@ -19,6 +19,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy import (+ DAILY_QUOTA_EXHAUSTED_ERROR,+ DAILY_QUOTA_EXHAUSTED_MESSAGE,+ RATE_LIMITED_ERROR,+ RATE_LIMITED_MESSAGE,EtsyResumeConfig,etsy_source,validate_credentials as validate_etsy_credentials,@@ -120,8 +124,18 @@ Register a personal app in the [Etsy developer portal](https://www.etsy.com/deve# blip — transient, not a PostHog bug — and Temporal retries the whole activity, so the# sync self-recovers. `raise_for_status` derives these prefixes from the status code alone,# not the vendor's reason text, so they're stable to match on (see mailchimp/impact sources- # for the same pattern).- return {"429 Client Error", "Server Error"}+ # for the same pattern). The token exchange is a POST, which the adapter does not retry, so+ # the bare status prefix stays here alongside the sentinels the reads raise.+ return {"429 Client Error", "Server Error", DAILY_QUOTA_EXHAUSTED_ERROR, RATE_LIMITED_ERROR}++ def get_retry_exhausted_errors(self) -> dict[str, str]:+ # Without these, a rate limit that outlives the retry budget leaves the job holding raw 429+ # text, which names neither whose limit was hit nor when it clears.+ return {+ DAILY_QUOTA_EXHAUSTED_ERROR: DAILY_QUOTA_EXHAUSTED_MESSAGE,+ RATE_LIMITED_ERROR: RATE_LIMITED_MESSAGE,+ "429 Client Error": RATE_LIMITED_MESSAGE,+ }def get_schemas(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.pyindex 454c74b71a0a..a5cf4e02f01d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy.py@@ -14,11 +14,14 @@ from requests import HTTPError, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy import (+ DAILY_QUOTA_EXHAUSTED_ERROR,ETSY_HISTORY_START,MAX_OFFSET,MIN_WINDOW_SECONDS,PAGE_SIZE,+ RATE_LIMITED_ERROR,EtsyAPIError,+ EtsyRateLimitError,EtsyResumeConfig,_window_start,etsy_source,@@ -37,12 +40,19 @@ _REFRESH_TOKEN = "etsy-refresh-token-abcdef123456"_LOGGER = structlog.get_logger(__name__)-def _response(payload: Any, *, status: int = 200, url: str = "https://api.etsy.com/v3/application/shops/1") -> Response:+def _response(+ payload: Any,+ *,+ status: int = 200,+ url: str = "https://api.etsy.com/v3/application/shops/1",+ headers: Optional[dict[str, str]] = None,+) -> Response:response = Response()response.status_code = statusresponse.url = urlresponse.reason = "OK" if status < 400 else "Error"response._content = json.dumps(payload).encode()+ response.headers.update(headers or {})return response@@ -96,6 +106,16 @@ class _FakeSession:return self._post_responses.pop(0)+def _windowed_session(responses: list[Response], *, opened_at: Optional[int] = ETSY_HISTORY_START) -> _FakeSession:+ """A full-history walk asks when the shop opened before it generates any window."""+ return _FakeSession([_response({"shop_id": 1, "created_timestamp": opened_at}), *responses])+++def _walk_calls(session: _FakeSession) -> list[tuple[str, dict[str, Any], dict[str, str]]]:+ """The endpoint's own GETs, without the shop-opening lookup in front of them."""+ return [call for call in session.get_calls if not call[0].endswith("/shops/1")]++class _FakeManager(ResumableSourceManager[EtsyResumeConfig]):def __init__(self, resume: Optional[EtsyResumeConfig] = None) -> None:self._resume = resume@@ -278,12 +298,56 @@ class TestEtsyTransport:assert len(rows) == MAX_OFFSET + PAGE_SIZEassert max(call[1]["offset"] for call in session.get_calls) == MAX_OFFSET+ @parameterized.expand(+ [+ # Etsy meters QPS first and then a sliding 24 hour quota, and only the day's counter+ # comes back on the refusal, so the header is what tells a burst from an empty quota.+ ({"x-remaining-today": "0"}, DAILY_QUOTA_EXHAUSTED_ERROR),+ ({"x-remaining-today": "417"}, RATE_LIMITED_ERROR),+ ({"x-remaining-today": "unparseable"}, RATE_LIMITED_ERROR),+ ({}, RATE_LIMITED_ERROR),+ ]+ )+ def test_rate_limited_response_names_the_limit_it_hit(self, headers: dict[str, str], expected: str) -> None:+ # The tracked session has already retried this while honoring retry-after, so a bare 429+ # reaching the job names neither whose limit was hit nor when it clears.+ session = _FakeSession([_response({"error": "Too Many Requests"}, status=429, headers=headers)])++ with pytest.raises(EtsyRateLimitError, match=expected):+ _collect(session, "shop_sections")++ @time_machine.travel("2020-01-15", tick=False)+ def test_full_history_walk_starts_when_the_shop_opened(self) -> None:+ # Windows before the shop existed can only come back empty, and Etsy charges the app's+ # daily quota for every one of them, which is what a sync runs out of before it finishes.+ opened_at = int(time.time()) - 30 * 24 * 60 * 60+ session = _windowed_session([_page(_rows(1), 1)], opened_at=opened_at)+ _collect(session, "receipts")++ assert session.get_calls[0][0].endswith("/shops/1")+ windows = [(call[1]["min_created"], call[1]["max_created"]) for call in _walk_calls(session)]+ assert windows == [(opened_at, int(time.time()))]++ @parameterized.expand(+ [+ ("etsy reports none", None),+ ("older than etsy", 5),+ ("clock skewed into the future", 4_000_000_000),+ ]+ )+ @time_machine.travel("2005-01-15", tick=False)+ def test_unusable_shop_opening_date_still_walks_all_history(self, _name: str, opened_at: Optional[int]) -> None:+ session = _windowed_session([_page([], 0)], opened_at=opened_at)+ _collect(session, "receipts")++ assert _walk_calls(session)[0][1]["min_created"] == ETSY_HISTORY_START+@time_machine.travel("2005-01-15", tick=False)def test_windowed_endpoint_sends_a_created_window_over_all_history(self) -> None:- session = _FakeSession([_page(_rows(2), 2)])+ session = _windowed_session([_page(_rows(2), 2)])rows, _ = _collect(session, "receipts")- params = session.get_calls[0][1]+ params = _walk_calls(session)[0][1]assert params["min_created"] == ETSY_HISTORY_STARTassert params["max_created"] == int(time.time())assert params["limit"] == PAGE_SIZE@@ -291,10 +355,10 @@ class TestEtsyTransport:@time_machine.travel("2005-07-01", tick=False)def test_windows_advance_until_the_range_is_covered(self) -> None:- session = _FakeSession([_page([], 0) for _ in range(3)])+ session = _windowed_session([_page([], 0) for _ in range(3)])_collect(session, "receipts")- windows = [(call[1]["min_created"], call[1]["max_created"]) for call in session.get_calls]+ windows = [(call[1]["min_created"], call[1]["max_created"]) for call in _walk_calls(session)]assert len(windows) == 3# Contiguous, non-overlapping, and finishing at "now".assert windows[0][0] == ETSY_HISTORY_START@@ -305,12 +369,12 @@ class TestEtsyTransport:@time_machine.travel("2005-01-15", tick=False)def test_oversized_window_is_halved_instead_of_hitting_the_offset_ceiling(self) -> None:# First probe reports more rows than the offset ceiling can reach, so the slice splits.- session = _FakeSession(+ session = _windowed_session([_page(_rows(PAGE_SIZE), MAX_OFFSET + PAGE_SIZE + 1), _page(_rows(1), 1), _page(_rows(1, start=1), 1)])rows, _ = _collect(session, "receipts")- windows = [(call[1]["min_created"], call[1]["max_created"]) for call in session.get_calls]+ windows = [(call[1]["min_created"], call[1]["max_created"]) for call in _walk_calls(session)]outer_start, outer_end = windows[0]assert windows[1][0] == outer_startassert windows[2] == (windows[1][1] + 1, outer_end)@@ -321,26 +385,26 @@ class TestEtsyTransport:def test_window_that_cannot_be_split_further_stops_at_the_offset_ceiling(self) -> None:# A one-hour slice is the floor, so an over-full one reads what it can and moves on.pages = [_page(_rows(PAGE_SIZE), 50_000) for _ in range(MAX_OFFSET // PAGE_SIZE + 1)]- session = _FakeSession(pages)+ session = _windowed_session(pages)rows, _ = _collect(session, "receipts")- window = session.get_calls[0][1]+ window = _walk_calls(session)[0][1]assert window["max_created"] - window["min_created"] < MIN_WINDOW_SECONDSassert len(rows) == MAX_OFFSET + PAGE_SIZE@time_machine.travel("2005-03-01", tick=False)def test_ledger_windows_stay_inside_etsys_31_day_maximum(self) -> None:- session = _FakeSession([_page([], 0) for _ in range(2)])+ session = _windowed_session([_page([], 0) for _ in range(2)])_collect(session, "ledger_entries")- windows = [(call[1]["min_created"], call[1]["max_created"]) for call in session.get_calls]+ windows = [(call[1]["min_created"], call[1]["max_created"]) for call in _walk_calls(session)]assert len(windows) == 2assert max(end - start for start, end in windows) <= 31 * 24 * 60 * 60@time_machine.travel("2005-01-15", tick=False)def test_reviews_split_the_window_rather_than_paging_past_the_first_page(self) -> None:# Offset 100 is the request Etsy rejects; the window has to narrow instead.- session = _FakeSession(+ session = _windowed_session([_page(_rows(PAGE_SIZE, key="transaction_id"), PAGE_SIZE + 1),_page(_rows(1, key="transaction_id"), 1),@@ -349,7 +413,7 @@ class TestEtsyTransport:)rows, _ = _collect(session, "reviews")- assert [call[1]["offset"] for call in session.get_calls] == [0, 0, 0]+ assert [call[1]["offset"] for call in _walk_calls(session)] == [0, 0, 0]assert len(rows) == 2@time_machine.travel("2005-01-15", tick=False)@@ -371,7 +435,7 @@ class TestEtsyTransport:@time_machine.travel("2005-01-15", tick=False)def test_state_is_saved_after_each_batch_and_cleared_when_the_walk_finishes(self) -> None:- session = _FakeSession([_page(_rows(PAGE_SIZE), 150), _page(_rows(50, start=100), 150)])+ session = _windowed_session([_page(_rows(PAGE_SIZE), 150), _page(_rows(50, start=100), 150)])_, manager = _collect(session, "receipts")assert [state.offset for state in manager.saved] == [PAGE_SIZE, 150]@@ -380,7 +444,7 @@ class TestEtsyTransport:@time_machine.travel("2005-01-15", tick=False)def test_transactions_are_expanded_out_of_the_receipts_payload(self) -> None:- session = _FakeSession(+ session = _windowed_session([_page([@@ -394,7 +458,7 @@ class TestEtsyTransport:rows, _ = _collect(session, "transactions")assert rows == [{"transaction_id": 10}, {"transaction_id": 11}]- assert session.get_calls[0][0].endswith("/shops/1/receipts")+ assert _walk_calls(session)[0][0].endswith("/shops/1/receipts")@time_machine.travel("2005-01-15", tick=False)def test_offset_advances_by_parent_rows_not_expanded_children(self) -> None:@@ -404,11 +468,11 @@ class TestEtsyTransport:{"receipt_id": i, "transactions": [{"transaction_id": i * 2}, {"transaction_id": i * 2 + 1}]}for i in range(PAGE_SIZE)]- session = _FakeSession([_page(parents, 150), _page([], 150)])+ session = _windowed_session([_page(parents, 150), _page([], 150)])rows, _ = _collect(session, "transactions")assert len(rows) == PAGE_SIZE * 2- assert session.get_calls[1][1]["offset"] == PAGE_SIZE+ assert _walk_calls(session)[1][1]["offset"] == PAGE_SIZE@parameterized.expand([@@ -439,10 +503,10 @@ class TestEtsyTransport:@time_machine.travel("2005-01-15", tick=False)def test_full_refresh_ignores_a_stale_cursor(self) -> None:- session = _FakeSession([_page([], 0)])+ session = _windowed_session([_page([], 0)])_collect(session, "receipts", should_use_incremental_field=False, db_incremental_field_last_value=999_999_999)- assert session.get_calls[0][1]["min_created"] == ETSY_HISTORY_START+ assert _walk_calls(session)[0][1]["min_created"] == ETSY_HISTORY_START@parameterized.expand([@@ -472,8 +536,18 @@ class TestEtsyValidateCredentials:assert session.get_calls[0][0].endswith("/users/me")- @parameterized.expand([(400,), (401,), (403,), (500,)])- def test_failed_probe_reports_a_message_without_raising(self, status: int) -> None:+ @parameterized.expand(+ [+ (400, "Check your API keystring"),+ (401, "Check your API keystring"),+ (403, "Check your API keystring"),+ (500, "Check your API keystring"),+ # A throttle says nothing about the credentials, so telling the user to check them sends+ # them off rotating keys that are fine.+ (429, "rate limiting your app"),+ ]+ )+ def test_failed_probe_reports_a_message_without_raising(self, status: int, expected_fragment: str) -> None:# Two of each so the 401 re-mint path has something to replay against.session = _FakeSession([_response({}, status=status), _response({}, status=status)], post_responses=[_token(), _token()]@@ -482,7 +556,7 @@ class TestEtsyValidateCredentials:ok, error = validate_credentials(_API_KEY, _SHARED_SECRET, _REFRESH_TOKEN, None)assert ok is False- assert error is not None+ assert error is not None and expected_fragment in errordef test_account_without_a_shop_surfaces_its_own_message(self) -> None:session = _FakeSession([_response({"user_id": 1, "shop_id": None})])@@ -526,7 +600,7 @@ class TestEtsySourceResponse:@time_machine.travel("2005-01-15", tick=False)def test_items_is_lazy_and_streams_rows(self) -> None:- session = _FakeSession([_page(_rows(3), 3)])+ session = _windowed_session([_page(_rows(3), 3)])response = etsy_source(api_key=_API_KEY,shared_secret=_SHARED_SECRET,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.pyindex 46840e45a5de..89942a597c3c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/etsy/tests/test_etsy_source.py@@ -5,6 +5,11 @@ from products.warehouse_sources.backend.facade.source_config import (ReleaseStatus,SourceFieldInputConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.etsy import (+ DAILY_QUOTA_EXHAUSTED_ERROR,+ RATE_LIMITED_ERROR,+)from products.warehouse_sources.backend.temporal.data_imports.sources.etsy.settings import ENDPOINTS, ETSY_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.etsy.source import EtsySource@@ -63,3 +68,17 @@ class TestEtsySourceClass:retryable_errors = EtsySource().get_retryable_errors()assert any(pattern in message for pattern in retryable_errors)++ @parameterized.expand([(DAILY_QUOTA_EXHAUSTED_ERROR,), (RATE_LIMITED_ERROR,)])+ def test_rate_limit_sentinels_stay_retryable_and_carry_a_friendly_message(self, sentinel: str) -> None:+ # The transport raises these strings and the source is the only thing that reads them, so a+ # rename on either side would quietly leave the job showing raw 429 text.+ source = EtsySource()++ assert error_message_matches(sentinel, source.get_retryable_errors())+ message = next(+ value+ for pattern, value in source.get_retry_exhausted_errors().items()+ if error_message_matches(sentinel, [pattern])+ )+ assert "Etsy" in message