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(temporalio): retry namespace rate-limit RPCs with backoff (#65334)

Tom Owers654c3738e0b7
diff --git a/posthog/temporal/data_imports/sources/temporalio/temporalio.py b/posthog/temporal/data_imports/sources/temporalio/temporalio.py
index efc8a7409530..0810c0bf57c2 100644
--- a/posthog/temporal/data_imports/sources/temporalio/temporalio.py
+++ b/posthog/temporal/data_imports/sources/temporalio/temporalio.py
@@ -3,14 +3,14 @@ import asyncio
import datetime
import threading
import dataclasses
-from collections.abc import Iterable
+from collections.abc import Awaitable, Callable, Iterable
from enum import StrEnum
from queue import Queue
-from typing import Any, Optional
+from typing import Any, Optional, TypeVar
from structlog.types import FilteringBoundLogger
from temporalio.client import Client
-from temporalio.service import RPCError
+from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.client import connect
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
@@ -53,6 +53,35 @@ class TemporalIOResumeConfig:
next_page_token: str # Base64-encoded bytes for JSON serialization
+T = TypeVar("T")
+
+# Temporal Cloud throttles per-namespace RPCs (RPS / concurrency / overload) with a gRPC
+# RESOURCE_EXHAUSTED status — e.g. "namespace rate limit exceeded". It's transient: a short backoff
+# usually clears the window. Riding it out in-process keeps a brief throttle from failing the whole
+# import activity (which would rebuild the client and restart pagination) and avoids error-tracking
+# noise. Persistent throttling re-raises so Temporal's activity retry still applies.
+_MAX_RATE_LIMIT_ATTEMPTS = 6
+
+
+async def _with_rate_limit_retry(
+ operation: Callable[[], Awaitable[T]],
+ logger: FilteringBoundLogger,
+ *,
+ max_attempts: int = _MAX_RATE_LIMIT_ATTEMPTS,
+) -> T:
+ attempt = 0
+ while True:
+ try:
+ return await operation()
+ except RPCError as e:
+ attempt += 1
+ if attempt >= max_attempts or e.status != RPCStatusCode.RESOURCE_EXHAUSTED:
+ raise
+ backoff = min(2 * attempt, 30)
+ logger.debug("TemporalIO: namespace rate limited", backoff_seconds=backoff, attempt=attempt)
+ await asyncio.sleep(backoff)
+
+
def _async_iter_to_sync(async_iter):
q: Queue[Any] = Queue(maxsize=5000)
sentinel = object()
@@ -177,7 +206,7 @@ async def _get_workflows(
# Save the token that will be used to fetch this page *before* fetching.
# On resume we re-fetch this same page — duplicates are safe thanks to primary keys.
pre_fetch_token = workflows.next_page_token
- await workflows.fetch_next_page()
+ await _with_rate_limit_retry(workflows.fetch_next_page, logger)
page = workflows.current_page
if not page:
break
@@ -228,7 +257,7 @@ async def _get_workflow_histories(
# Save the token that will be used to fetch this page *before* fetching.
# On resume we re-fetch this same page — duplicates are safe thanks to primary keys.
pre_fetch_token = workflows.next_page_token
- await workflows.fetch_next_page()
+ await _with_rate_limit_retry(workflows.fetch_next_page, logger)
page = workflows.current_page
if not page:
break
@@ -244,7 +273,8 @@ async def _get_workflow_histories(
for item in page:
try:
- history = await client.get_workflow_handle(item.id, run_id=item.run_id).fetch_history()
+ handle = client.get_workflow_handle(item.id, run_id=item.run_id)
+ history = await _with_rate_limit_retry(handle.fetch_history, logger)
history_dict = history.to_json_dict()
events = history_dict["events"]
for event in events:
diff --git a/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py b/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py
index feb8c9922afc..4bf37d743cb7 100644
--- a/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py
+++ b/posthog/temporal/data_imports/sources/temporalio/test_temporalio.py
@@ -1,12 +1,21 @@
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, call, patch
from temporalio.client import Client
+from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.codec import EncryptionCodec
from posthog.temporal.data_imports.sources.generated_configs import TemporalIOSourceConfig
from posthog.temporal.data_imports.sources.temporalio.source import TemporalIOSource
-from posthog.temporal.data_imports.sources.temporalio.temporalio import FakeSettings, _get_temporal_client
+from posthog.temporal.data_imports.sources.temporalio.temporalio import (
+ FakeSettings,
+ _get_temporal_client,
+ _with_rate_limit_retry,
+)
+
+
+def _rpc_error(message: str, status: RPCStatusCode) -> RPCError:
+ return RPCError(message, status, b"")
class TestTemporalIOClient:
@@ -93,3 +102,43 @@ class TestTemporalIONonRetryableErrors:
assert not any(pattern in error_message for pattern in non_retryable_errors), (
f"'{error_message}' must not match a non-retryable pattern"
)
+
+
+class TestRateLimitRetry:
+ @patch("posthog.temporal.data_imports.sources.temporalio.temporalio.asyncio.sleep", new_callable=AsyncMock)
+ async def test_rides_out_transient_rate_limit(self, sleep):
+ calls = {"n": 0}
+
+ async def operation():
+ calls["n"] += 1
+ if calls["n"] <= 2:
+ raise _rpc_error("namespace rate limit exceeded", RPCStatusCode.RESOURCE_EXHAUSTED)
+ return "ok"
+
+ result = await _with_rate_limit_retry(operation, MagicMock())
+
+ assert result == "ok"
+ assert calls["n"] == 3
+ # Backoff grows per attempt per `min(2 * attempt, 30)`: 2s after the 1st failure, 4s after the 2nd.
+ assert sleep.await_args_list == [call(2), call(4)]
+
+ @patch("posthog.temporal.data_imports.sources.temporalio.temporalio.asyncio.sleep", new_callable=AsyncMock)
+ async def test_persistent_rate_limit_is_reraised(self, sleep):
+ async def operation():
+ raise _rpc_error("namespace rate limit exceeded", RPCStatusCode.RESOURCE_EXHAUSTED)
+
+ with pytest.raises(RPCError):
+ await _with_rate_limit_retry(operation, MagicMock(), max_attempts=4)
+
+ # Bounded attempts leave Temporal to retry; backs off between attempts but not after the last.
+ assert sleep.await_args_list == [call(2), call(4), call(6)]
+
+ @patch("posthog.temporal.data_imports.sources.temporalio.temporalio.asyncio.sleep", new_callable=AsyncMock)
+ async def test_non_rate_limit_rpc_error_is_not_retried(self, sleep):
+ async def operation():
+ raise _rpc_error("workflow execution not found for", RPCStatusCode.NOT_FOUND)
+
+ with pytest.raises(RPCError):
+ await _with_rate_limit_retry(operation, MagicMock())
+
+ assert sleep.await_count == 0