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(linear): honor Retry-After on 429 rate limits (#63756)

Tom Owersb89390431a05
diff --git a/posthog/temporal/data_imports/sources/linear/linear.py b/posthog/temporal/data_imports/sources/linear/linear.py
index 948720a716f1..0d942abaea68 100644
--- a/posthog/temporal/data_imports/sources/linear/linear.py
+++ b/posthog/temporal/data_imports/sources/linear/linear.py
@@ -1,8 +1,9 @@
import dataclasses
from typing import Any
+import requests
from structlog.types import FilteringBoundLogger
-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
@@ -14,9 +15,43 @@ from posthog.temporal.data_imports.sources.linear.settings import (
LINEAR_ENDPOINTS,
)
+LINEAR_MAX_RETRY_ATTEMPTS = 5
+# Cap how long a single Retry-After can stall us, so a misbehaving header can't pin the
+# activity open. Kept under the activity heartbeat timeout; longer waits are handled by
+# Temporal rescheduling the whole activity, which resumes from the saved cursor.
+LINEAR_MAX_RETRY_AFTER_SECONDS = 60
+# Stateless backoff used when a 429 carries no usable Retry-After hint.
+_LINEAR_FALLBACK_WAIT = wait_exponential_jitter(initial=1, max=30)
+
class LinearRetryableError(Exception):
- pass
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ # Seconds Linear asked us to wait (from a 429 Retry-After), if any.
+ self.retry_after = retry_after
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ """Linear's edge fronts 429s with a standard Retry-After in delta-seconds; ignore other forms."""
+ raw = response.headers.get("Retry-After")
+ if raw is None:
+ return None
+ try:
+ seconds = float(raw)
+ except (TypeError, ValueError):
+ return None
+ return max(0.0, seconds)
+
+
+def _wait_strategy(retry_state: RetryCallState) -> float:
+ """Honor a 429's Retry-After when present, else fall back to jittered exponential backoff.
+
+ Doing the wait here (rather than time.sleep inside execute) avoids stacking both delays.
+ """
+ exc = retry_state.outcome.exception() if retry_state.outcome is not None else None
+ if isinstance(exc, LinearRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, LINEAR_MAX_RETRY_AFTER_SECONDS)
+ return _LINEAR_FALLBACK_WAIT(retry_state)
@dataclasses.dataclass
@@ -50,8 +85,8 @@ def _make_paginated_request(
@retry(
retry=retry_if_exception_type(LinearRetryableError),
- stop=stop_after_attempt(5),
- wait=wait_exponential_jitter(initial=1, max=30),
+ stop=stop_after_attempt(LINEAR_MAX_RETRY_ATTEMPTS),
+ wait=_wait_strategy,
reraise=True,
)
def execute(variables: dict[str, Any]) -> dict:
@@ -63,9 +98,11 @@ def _make_paginated_request(
# Linear answers HTTP-level rate limits with a 429 and an HTML body (not GraphQL JSON),
# so this must be caught before the JSON parse below. Otherwise response.json() raises a
# JSONDecodeError that escalates to a plain, non-retryable Exception instead of being
- # retried with backoff like the GraphQL-level RATELIMITED case.
+ # retried with backoff like the GraphQL-level RATELIMITED case. The blind exponential
+ # backoff often gives up before Linear's rate-limit window resets, so honor the
+ # Retry-After it sends when present and fall back to the exponential otherwise.
if response.status_code == 429:
- raise LinearRetryableError("Linear: rate limited (429)")
+ raise LinearRetryableError("Linear: rate limited (429)", retry_after=_parse_retry_after(response))
try:
payload = response.json()
diff --git a/posthog/temporal/data_imports/sources/linear/test_linear.py b/posthog/temporal/data_imports/sources/linear/test_linear.py
index 29342d89a233..8ebed31d4e59 100644
--- a/posthog/temporal/data_imports/sources/linear/test_linear.py
+++ b/posthog/temporal/data_imports/sources/linear/test_linear.py
@@ -6,11 +6,15 @@ import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from tenacity import Future, RetryCallState
from posthog.temporal.data_imports.sources.linear.linear import (
+ LINEAR_MAX_RETRY_AFTER_SECONDS,
LinearResumeConfig,
LinearRetryableError,
_make_paginated_request,
+ _parse_retry_after,
+ _wait_strategy,
linear_source,
)
from posthog.temporal.data_imports.sources.linear.source import LinearSource
@@ -31,17 +35,24 @@ def _make_response(nodes: list[dict[str, Any]], has_next_page: bool, end_cursor:
return response
-def _make_rate_limited_response() -> MagicMock:
+def _make_rate_limited_response(headers: dict[str, str] | None = None) -> MagicMock:
"""Mimic Linear's HTTP-level 429: an HTML body that fails JSON parsing."""
response = MagicMock()
response.status_code = 429
response.ok = False
response.reason = "Too Many Requests"
response.text = "<!DOCTYPE html><html><head><title>Rate limited</title></head></html>"
+ response.headers = headers or {}
response.json.side_effect = ValueError("Expecting value: line 1 column 1 (char 0)")
return response
+def _retry_state(exc: BaseException) -> RetryCallState:
+ state = RetryCallState(retry_object=MagicMock(), fn=None, args=(), kwargs={})
+ state.outcome = Future.construct(1, exc, has_exception=True)
+ return state
+
+
def _capture_post_calls(session: MagicMock, responses: list[MagicMock]) -> list[dict[str, Any]]:
"""Configure session.post to record a deep-copied snapshot of variables at each call.
@@ -215,6 +226,57 @@ class TestMakePaginatedRequest:
assert session.post.call_count == 5
+class TestRateLimitBackoff:
+ @parameterized.expand(
+ [
+ ("delta_seconds", {"Retry-After": "30"}, 30.0),
+ ("zero", {"Retry-After": "0"}, 0.0),
+ ("fractional", {"Retry-After": "12.5"}, 12.5),
+ ("missing", {}, None),
+ ("http_date_unsupported", {"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None),
+ ("non_numeric", {"Retry-After": "soon"}, None),
+ ]
+ )
+ def test_parse_retry_after(self, _name: str, headers: dict[str, str], expected: float | None) -> None:
+ assert _parse_retry_after(_make_rate_limited_response(headers)) == expected
+
+ def test_wait_strategy_honors_retry_after(self) -> None:
+ exc = LinearRetryableError("Linear: rate limited (429)", retry_after=45.0)
+ assert _wait_strategy(_retry_state(exc)) == 45.0
+
+ def test_wait_strategy_caps_retry_after(self) -> None:
+ exc = LinearRetryableError("Linear: rate limited (429)", retry_after=10_000.0)
+ assert _wait_strategy(_retry_state(exc)) == LINEAR_MAX_RETRY_AFTER_SECONDS
+
+ def test_wait_strategy_falls_back_to_backoff_without_retry_after(self) -> None:
+ exc = LinearRetryableError("Linear: rate limited (429)")
+ assert 0 < _wait_strategy(_retry_state(exc)) <= 30
+
+ @patch("time.sleep", return_value=None)
+ @patch("posthog.temporal.data_imports.sources.linear.linear.make_tracked_session")
+ def test_429_carries_retry_after_into_exception(self, mock_session_cls: MagicMock, _mock_sleep: MagicMock) -> None:
+ # Retry-After of 0 keeps the test fast while still exercising the honored-wait path.
+ session = MagicMock()
+ session.post.side_effect = [_make_rate_limited_response({"Retry-After": "0"}) for _ in range(5)]
+ mock_session_cls.return_value = session
+
+ manager = _make_resumable_manager()
+ logger = MagicMock()
+
+ with pytest.raises(LinearRetryableError) as exc_info:
+ list(
+ _make_paginated_request(
+ access_token="tok",
+ endpoint_name="issues",
+ logger=logger,
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert exc_info.value.retry_after == 0.0
+ assert session.post.call_count == 5
+
+
class TestLinearSource:
def test_source_response_wires_primary_key_and_items(self) -> None:
manager = _make_resumable_manager()