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(google_sheets): retry transient 5xx API errors (#63429)

Tom Owersa38e159065fe
diff --git a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
index 90c77aacb32a..037a94e73f51 100644
--- a/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
+++ b/posthog/temporal/data_imports/sources/google_sheets/google_sheets.py
@@ -43,6 +43,12 @@ max_attempts = 10
jitter_in_seconds = 10
sleep_per_attempt_in_seconds = 30
+# Transient Google Sheets API failures worth retrying: 429 (per-minute quota exhausted) plus the
+# 5xx server-side errors Google returns intermittently (e.g. "[500]: Internal error encountered.").
+# Google's API guidance is to retry these with backoff — they are not caused by our request and
+# usually clear on the next attempt, so re-raising immediately turns a blip into a failed sync.
+_RETRYABLE_API_ERROR_CODES = {429, 500, 502, 503, 504}
+
# gspread raises a bare `PermissionError` (with no message) when the Google Sheets
# API returns 403 — see gspread/client.py: `raise PermissionError from ex`.
# `str(PermissionError())` is an empty string, which means the non-retryable error
@@ -54,8 +60,10 @@ _PERMISSION_DENIED_MESSAGE = "Spreadsheet access denied. Please share the spread
@cached(cache)
def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet:
"""Attempt to get a worksheet with linear backoff. Google Sheets has a 300
- request quota per minute. We add a +- 10s jitter to the sleep per attempt so
- that multiple jobs blocked by quota limits dont all retry at the same time"""
+ request quota per minute, and also returns transient 5xx server errors. We
+ retry both (see `_RETRYABLE_API_ERROR_CODES`) and add a +- 10s jitter to the
+ sleep per attempt so that multiple jobs blocked by quota limits dont all retry
+ at the same time"""
def execute():
client = google_sheets_client()
@@ -71,7 +79,7 @@ def _get_worksheet(spreadsheet_url: str, worksheet_id: int) -> gspread.Worksheet
try:
return execute()
except gspread.exceptions.APIError as e:
- if e.code != 429 or attempts >= max_attempts:
+ if e.code not in _RETRYABLE_API_ERROR_CODES or attempts >= max_attempts:
raise
jitter = random.uniform(-jitter_in_seconds, jitter_in_seconds)
diff --git a/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py b/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
index 72a12214a7fb..77079df4539f 100644
--- a/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
+++ b/posthog/temporal/data_imports/sources/google_sheets/tests/test_google_sheets.py
@@ -43,6 +43,71 @@ def test_get_worksheet_backoff():
assert mock_get_worksheet_by_id.call_count == 10
[email protected]("status_code", [429, 500, 502, 503, 504])
+def test_get_worksheet_retries_transient_api_errors(status_code):
+ """Transient API errors (quota 429s and 5xx server errors like
+ "[500]: Internal error encountered.") should be retried with backoff, not
+ re-raised on the first occurrence."""
+ with (
+ mock.patch(
+ "posthog.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client"
+ ) as mock_google_sheets_client,
+ mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"),
+ ):
+ mock_spreadsheet = mock.MagicMock()
+ mock_get_worksheet_by_id = mock.MagicMock()
+
+ mock_response = mock.MagicMock()
+ mock_response.json.return_value = {
+ "error": {
+ "code": status_code,
+ "message": "Internal error encountered.",
+ "status": "INTERNAL",
+ }
+ }
+
+ mock_get_worksheet_by_id.side_effect = gspread.exceptions.APIError(mock_response)
+
+ instance = mock_google_sheets_client.return_value
+ instance.open_by_url.return_value = mock_spreadsheet
+ mock_spreadsheet.get_worksheet_by_id = mock_get_worksheet_by_id
+
+ # Use a unique worksheet id per status code to avoid the module-level TTLCache
+ with pytest.raises(gspread.exceptions.APIError):
+ _get_worksheet("transient-url", status_code)
+
+ assert mock_get_worksheet_by_id.call_count == 10
+
+
+def test_get_worksheet_does_not_retry_non_transient_api_error():
+ """A non-transient API error (e.g. 400) should be raised immediately without
+ burning through the retry budget."""
+ with (
+ mock.patch(
+ "posthog.temporal.data_imports.sources.google_sheets.google_sheets.google_sheets_client"
+ ) as mock_google_sheets_client,
+ mock.patch("posthog.temporal.data_imports.sources.google_sheets.google_sheets.time"),
+ ):
+ mock_spreadsheet = mock.MagicMock()
+ mock_get_worksheet_by_id = mock.MagicMock()
+
+ mock_response = mock.MagicMock()
+ mock_response.json.return_value = {
+ "error": {"code": 400, "message": "Bad request", "status": "INVALID_ARGUMENT"}
+ }
+
+ mock_get_worksheet_by_id.side_effect = gspread.exceptions.APIError(mock_response)
+
+ instance = mock_google_sheets_client.return_value
+ instance.open_by_url.return_value = mock_spreadsheet
+ mock_spreadsheet.get_worksheet_by_id = mock_get_worksheet_by_id
+
+ with pytest.raises(gspread.exceptions.APIError):
+ _get_worksheet("non-transient-url", 400)
+
+ assert mock_get_worksheet_by_id.call_count == 1
+
+
def test_get_worksheet_caching():
with (
mock.patch(