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-modeling): retry rate-limited teams in batch reconcile (#75908)

Jovan Sakovic75c2b2ff6845
diff --git a/products/data_modeling/backend/management/commands/batch_reconcile_teams.py b/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
index 3af687c06cfb..0fd72fcf3a81 100644
--- a/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
+++ b/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
@@ -1,4 +1,5 @@
import json
+import time
import dataclasses
from datetime import timedelta
from pathlib import Path
@@ -7,6 +8,7 @@ from django.core.management.base import BaseCommand, CommandError
import structlog
from asgiref.sync import async_to_sync
+from temporalio.service import RPCError, RPCStatusCode
from posthog.models.team import Team
from posthog.temporal.common.client import async_connect
@@ -27,6 +29,9 @@ logger = structlog.get_logger(__name__)
REPORT_MARKER = "=== BATCH RECONCILE REPORT JSON ==="
+RATE_LIMIT_RETRIES = 3
+RATE_LIMIT_BASE_WAIT_SECONDS = 10
+
class Anomaly(Exception):
"""The team's state diverged from what the plan predicted; halts the batch."""
@@ -82,7 +87,7 @@ class Command(BaseCommand):
record: dict = {"team_id": team_id, "status": "planned", "dags": [], "anomalies": []}
report["teams"].append(record)
try:
- self._process_team(team_id, record, apply=apply)
+ self._process_team_with_retry(team_id, record, apply=apply)
if apply:
record["status"] = "applied"
self.stdout.write(f"team {team_id}: {record['status']}")
@@ -108,6 +113,23 @@ class Command(BaseCommand):
self.stdout.write(REPORT_MARKER)
self.stdout.write(payload)
+ def _process_team_with_retry(self, team_id: int, record: dict, *, apply: bool) -> None:
+ """Retry a rate-limited team instead of halting the batch: both phases are
+ idempotent per team (plan is read-only; re-applying converges on the same
+ tier set), so on RESOURCE_EXHAUSTED the whole team is safely re-run after
+ a backoff. Any other error propagates to the per-team handler."""
+ for attempt in range(RATE_LIMIT_RETRIES + 1):
+ try:
+ self._process_team(team_id, record, apply=apply)
+ return
+ except RPCError as err:
+ if err.status != RPCStatusCode.RESOURCE_EXHAUSTED or attempt == RATE_LIMIT_RETRIES:
+ raise
+ wait = RATE_LIMIT_BASE_WAIT_SECONDS * (2**attempt)
+ self.stderr.write(f"team {team_id}: temporal rate limited, retrying in {wait}s")
+ record["dags"].clear()
+ time.sleep(wait)
+
def _process_team(self, team_id: int, record: dict, *, apply: bool) -> None:
team = Team.objects.filter(id=team_id).first()
if team is None:
diff --git a/products/data_modeling/backend/test/test_batch_reconcile_teams.py b/products/data_modeling/backend/test/test_batch_reconcile_teams.py
index bc6e99408f94..bdfed70c636f 100644
--- a/products/data_modeling/backend/test/test_batch_reconcile_teams.py
+++ b/products/data_modeling/backend/test/test_batch_reconcile_teams.py
@@ -8,6 +8,8 @@ from unittest import mock
from django.core.management import call_command
+from temporalio.service import RPCError, RPCStatusCode
+
from posthog.models.team import Team
from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
@@ -136,6 +138,33 @@ class TestBatchReconcileTeams(BaseTest):
assert [t["node_id"] for t in invalid] == [str(parent.id)]
assert invalid[0]["consumer_ceiling"] == int(timedelta(hours=1).total_seconds())
+ def test_rate_limited_team_retries_instead_of_halting(self):
+ # a temporal namespace rate limit mid-batch must back off and retry the team,
+ # not halt the whole batch (halted a real 200-team production run)
+ dag, _node = self._legacy_dag(self.team)
+ listing = _temporal_listing([str(dag.id)])
+ rate_limit = RPCError("namespace rate limit exceeded", RPCStatusCode.RESOURCE_EXHAUSTED, b"")
+
+ out = StringIO()
+ with (
+ mock.patch(f"{BATCH}.tiered_schedules_enabled", return_value=True),
+ mock.patch(f"{BATCH}.time.sleep") as sleep,
+ mock.patch(f"{RECONCILE}.sync_connect"),
+ mock.patch(f"{RECONCILE}.delete_schedule"),
+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(side_effect=[rate_limit, listing])),
+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()),
+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),
+ mock.patch(f"{BATCH}.async_connect", new=mock.AsyncMock()),
+ mock.patch(f"{BATCH}.a_schedule_exists", new=mock.AsyncMock(return_value=False)),
+ ):
+ call_command("batch_reconcile_teams", "--team-ids", str(self.team.pk), stdout=out, stderr=StringIO())
+ report = json.loads(out.getvalue().split(REPORT_MARKER, 1)[1])
+
+ assert report["halted"] is False
+ assert report["teams"][0]["status"] == "planned"
+ assert len(report["teams"][0]["dags"]) == 1
+ sleep.assert_called_once_with(10)
+
def test_plan_only_writes_nothing(self):
dag, node = self._legacy_dag(self.team)