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(data-warehouse): retry Shopify token endpoint 5xx locally (#69645)

Tom Owersda1190b909da
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py
index b7c6394376ee..0a8748d68711 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py
@@ -309,12 +309,18 @@ def normalize_store_id(raw: str) -> str:
# connect/read timeout) surfaces from `post` as requests ConnectionError/Timeout — SSLError
# is a ConnectionError. A connection dropped mid-response surfaces as ChunkedEncodingError,
# which is a RequestException rather than a ConnectionError, so it must be listed explicitly.
- # The adapter's own urllib3 retries back off for only ~1.5s, too short to ride out a
- # multi-second blip. Minting a token is idempotent, so reissue with backoff rather than failing
- # the whole import. 4xx/5xx are raised as plain Exceptions below and so are untouched here —
- # auth failures still fail fast.
+ # A 429/5xx returns a completed response and is raised as ShopifyRetryableError below, so it
+ # is listed here too. The adapter's own urllib3 retries back off for only ~1.5s, too short to
+ # ride out a multi-second blip. Minting a token is idempotent, so reissue with backoff rather
+ # than failing the whole import. 4xx auth failures are raised as plain Exceptions and so are
+ # untouched here — they still fail fast.
retry=retry_if_exception_type(
- (requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.ChunkedEncodingError)
+ (
+ ShopifyRetryableError,
+ requests.exceptions.ConnectionError,
+ requests.exceptions.Timeout,
+ requests.exceptions.ChunkedEncodingError,
+ )
),
stop=stop_after_attempt(5),
wait=_shopify_backoff,
@@ -332,10 +338,13 @@ def _get_shopify_access_token(shopify_store_id: str, shopify_client_id: str, sho
if not access_res.ok:
# A 4xx means the app credentials are invalid/revoked (e.g. the app was
# uninstalled) — re-auth is the only fix, so surface a non-retryable message.
- # 429 (rate limit) and 5xx are transient and stay retryable via the generic message.
if 400 <= access_res.status_code < 500 and access_res.status_code != 429:
raise Exception(f"{SHOPIFY_ACCESS_TOKEN_AUTH_ERROR} (HTTP {access_res.status_code})")
- raise Exception(f"Failed to retrieve Shopify access token: {access_res}")
+ # 429 (rate limit) and 5xx (e.g. a 502 Bad Gateway from Shopify's edge) are transient —
+ # retry locally with backoff instead of failing the import, mirroring the GraphQL path.
+ raise ShopifyRetryableError(
+ f"Failed to retrieve Shopify access token: {access_res.status_code} {access_res.reason}"
+ )
return access_res.json()["access_token"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py
index 06308cd2b39e..fef4a3950bde 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_access_token.py
@@ -5,15 +5,17 @@ from requests.exceptions import ChunkedEncodingError, SSLError
from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shopify import (
SHOPIFY_ACCESS_TOKEN_AUTH_ERROR,
+ ShopifyRetryableError,
_get_shopify_access_token,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.source import ShopifySource
-def _mock_response(status_code: int, ok: bool, json_data: dict | None = None) -> mock.MagicMock:
+def _mock_response(status_code: int, ok: bool, json_data: dict | None = None, reason: str = "") -> mock.MagicMock:
response = mock.MagicMock()
response.status_code = status_code
response.ok = ok
+ response.reason = reason
response.json.return_value = json_data or {}
return response
@@ -43,12 +45,20 @@ def test_get_access_token_4xx_is_non_retryable(status_code):
)
[email protected]("status_code", [429, 500, 502, 503])
-def test_get_access_token_transient_stays_retryable(status_code):
- with _patched_token_call(_mock_response(status_code, ok=False)):
- with pytest.raises(Exception) as exc_info:
+ "status_code,reason",
+ [(429, "Too Many Requests"), (500, "Internal Server Error"), (502, "Bad Gateway"), (503, "Service Unavailable")],
+)
[email protected]("tenacity.nap.time.sleep")
+def test_get_access_token_transient_retries_then_reraises(_mock_sleep, status_code, reason):
+ # A 429/5xx on the token endpoint (e.g. the 502 Bad Gateway seen in production) is transient,
+ # so it must retry locally with backoff and, if it never recovers, reraise a retryable error
+ # rather than a non-retryable one.
+ post = mock.MagicMock(return_value=_mock_response(status_code, ok=False, reason=reason))
+ with _patched_token_post(post):
+ with pytest.raises(ShopifyRetryableError) as exc_info:
_get_shopify_access_token("store", "client-id", "client-secret")
-
+ assert post.call_count == 5
error_message = str(exc_info.value)
patterns = ShopifySource().get_non_retryable_errors()
assert not any(pattern in error_message for pattern in patterns), (
@@ -56,6 +66,20 @@ def test_get_access_token_transient_stays_retryable(status_code):
)
[email protected]("tenacity.nap.time.sleep")
+def test_get_access_token_retries_5xx_then_succeeds(_mock_sleep):
+ # A transient 502 followed by a healthy response should mint the token, not fail the import.
+ post = mock.MagicMock(
+ side_effect=[
+ _mock_response(502, ok=False, reason="Bad Gateway"),
+ _mock_response(200, ok=True, json_data={"access_token": "tok"}),
+ ]
+ )
+ with _patched_token_post(post):
+ assert _get_shopify_access_token("store", "client-id", "client-secret") == "tok"
+ assert post.call_count == 2
+
+
def test_get_access_token_success_returns_token():
with _patched_token_call(_mock_response(200, ok=True, json_data={"access_token": "tok"})):
assert _get_shopify_access_token("store", "client-id", "client-secret") == "tok"