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(experiments): jitter the capacity retry delay for metric recalculation (#113036)

Rodrigo Iloro17df7767738b
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.md
index 95fd64c81245..a8de3d3fa01b 100644
--- a/products/experiments/backend/temporal/ARCHITECTURE.md
+++ b/products/experiments/backend/temporal/ARCHITECTURE.md
@@ -226,7 +226,7 @@ The split is intentional: Grafana tells you about the worker process, PostHog te
Retries live in Temporal's `RetryPolicy` on the calc activity, not in the workflow. The policy is exponential: `initial_interval=5s`, `backoff_coefficient=2.0`, `maximum_interval=60s`, `maximum_attempts=MAX_METRIC_ATTEMPTS` (currently 8). So a metric backs off 5s, 10s, 20s, 40s, 60s, 60s, 60s across its retries, then the eighth attempt is final. `asyncio.gather(..., return_exceptions=True)` lets healthy metrics finish while a failing one retries; a retrying metric never blocks the others, because each activity retries on its own worker slot rather than holding a shared queue slot.
- A permanent failure fails fast rather than burning the retry budget. `NON_RETRYABLE_ERROR_TYPES` (`out_of_memory`, `byte_limit`, `validation_error`) plus `ValueError` are raised non-retryable, so the metric is terminal on the first trip. A different bucket, the per-org ClickHouse concurrency limiter and the cluster at-capacity guard, is retried on a fixed 60s delay (`CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS`) via `ApplicationError(next_retry_delay=...)`, out-of-band from the exponential schedule, because that error means "come back later", not "this query is wrong".
+ A permanent failure fails fast rather than burning the retry budget. `NON_RETRYABLE_ERROR_TYPES` (`out_of_memory`, `byte_limit`, `validation_error`) plus `ValueError` are raised non-retryable, so the metric is terminal on the first trip. A different bucket, the per-org ClickHouse concurrency limiter and the cluster at-capacity guard, is retried after a random delay between 30s and 90s (`CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS` and `CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS`) via `ApplicationError(next_retry_delay=...)`, out-of-band from the exponential schedule, because that error means "come back later", not "this query is wrong". The random delay spreads out metrics that bounced in the same burst, so their retries do not arrive together and hit the same full concurrency limit again.
- **`is_final_attempt` is derived inside the activity.** Because Temporal now owns retries, the activity reads its own attempt count from `activity.info().attempt` and compares it against `MAX_METRIC_ATTEMPTS` (the same constant the workflow's `RetryPolicy` is built from, so both sides agree on which attempt is last). The activity persists a transient failure (FAILED row + `metric_errors`) only on the final attempt, so a metric still being retried stays in its loading/dim state on the frontend instead of flashing an error that may yet resolve. Non-final transient state is tracked separately in the `metric_retries` column for the UI.
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index ee15d87ae5b1..ecf127cf016d 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -35,10 +35,12 @@ METRICS_RECALCULATION_WORKFLOW_NAME = "experiment-metrics-recalculation-workflow
# Max attempts per metric before it's marked failed on the recalculation workflow.
MAX_METRIC_ATTEMPTS = 8
-# Retry delay for a calc attempt that bounced off the per-org ClickHouse concurrency limiter or the cluster's
-# at-capacity guard, applied via ApplicationError(next_retry_delay=...) instead of the retry policy's 5s
-# exponential schedule.
-CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS = 60
+# Retry delay window for a calc attempt that bounced off the per-org ClickHouse concurrency limiter or the
+# cluster's at-capacity guard, applied via ApplicationError(next_retry_delay=...) instead of the retry policy's
+# 5s exponential schedule. Each bounce picks a random delay in the window, so metrics that bounced in the same
+# burst do not retry at the same moment and hit the same full limit again.
+CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS = 30
+CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS = 90
RECALCULATION_RETRY_INITIAL_INTERVAL_SECONDS = 5
RECALCULATION_RETRY_BACKOFF_COEFFICIENT = 2.0
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index acf607309667..ac4fcc0b6d2d 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -5,6 +5,7 @@ module holds the DB-touching ``_*_sync`` implementations plus the pure helpers t
"""
import time
+import random
import dataclasses
from datetime import datetime, timedelta
from typing import Any
@@ -46,7 +47,8 @@ from products.experiments.backend.models.experiment import (
ExperimentMetricsRecalculation,
)
from products.experiments.backend.temporal.models import (
- CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
+ CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS,
+ CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS,
MAX_METRIC_ATTEMPTS,
METRIC_CALC_MAX_EXECUTION_TIME_SECONDS,
NON_RETRYABLE_ERROR_TYPES,
@@ -437,6 +439,10 @@ def _estimated_retry_delay_seconds(attempt: int) -> float:
)
+def _concurrency_limit_retry_delay_seconds() -> float:
+ return random.uniform(CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS, CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS)
+
+
_RETRY_SAFE_MESSAGES: dict[str, str] = {
"rate_limited": "The query was deferred because the cluster is at capacity.",
"timeout": "The query timed out.",
@@ -877,6 +883,7 @@ def _calculate_experiment_metric_for_recalculation_sync(
except (ConcurrencyLimitExceeded, ClickHouseAtCapacity) as e:
message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]
+ retry_delay_seconds = _concurrency_limit_retry_delay_seconds()
if is_final_attempt:
record_terminal_error(message, classify_experiment_query_error(e), retriable=True)
logger.warning(
@@ -898,7 +905,7 @@ def _calculate_experiment_metric_for_recalculation_sync(
attempt,
error_type,
safe_message,
- CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
+ retry_delay_seconds,
)
_capture_experiment_metric_event(
experiment,
@@ -912,14 +919,14 @@ def _calculate_experiment_metric_for_recalculation_sync(
"error_message": safe_message,
"attempt": attempt,
"max_attempts": MAX_METRIC_ATTEMPTS,
- "next_retry_delay_seconds": CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
+ "next_retry_delay_seconds": round(retry_delay_seconds, 1),
},
trigger=state.trigger,
)
raise ApplicationError(
message,
type=type(e).__name__,
- next_retry_delay=timedelta(seconds=CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS),
+ next_retry_delay=timedelta(seconds=retry_delay_seconds),
) from e
except Exception as e:
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 7a37a91b3d15..2b461a1456e6 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -30,7 +30,6 @@ from products.experiments.backend.models.experiment import (
ExperimentToSavedMetric,
)
from products.experiments.backend.temporal.models import (
- CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
MAX_METRIC_ATTEMPTS,
MetricRecalculationResult,
RecalculationProgressUpdate,
@@ -755,7 +754,7 @@ class TestCalculateActivity(BaseTest):
"backpressure",
ConcurrencyLimitExceeded("quota"),
"rate_limited",
- 60,
+ 47.5,
"The query was deferred because the cluster is at capacity.",
),
(
@@ -769,14 +768,17 @@ class TestCalculateActivity(BaseTest):
)
@time_machine.travel("2026-05-29T13:00:00Z", tick=False)
def test_transient_attempt_records_retry_state_and_success_clears_it(
- self, name: str, exc: Exception, expected_error_type: str, expected_delay_seconds: int, expected_message: str
+ self, name: str, exc: Exception, expected_error_type: str, expected_delay_seconds: float, expected_message: str
):
# The retry entry is what the UI shows between attempts; without it the metric looks stuck. It must
# carry the attempt counters and a next_retry_at estimate, and vanish once the metric resolves.
exp = self._experiment(flag_key=f"calc-retry-{name}", metrics=[_mean_metric("m1")])
recalc = self._recalc(exp, metric_uuids=["m1"])
- with patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:
+ with (
+ patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner,
+ patch("products.experiments.backend.temporal.recalculation_logic.random.uniform", return_value=47.5),
+ ):
mock_runner.return_value.run.side_effect = exc
with pytest.raises((type(exc), ApplicationError)):
_calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=2)
@@ -862,13 +864,14 @@ class TestCalculateActivity(BaseTest):
with (
patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner,
patch("products.experiments.backend.temporal.recalculation_logic.capture_exception") as mock_capture,
+ patch("products.experiments.backend.temporal.recalculation_logic.random.uniform", return_value=47.5),
):
mock_runner.return_value.run.side_effect = exc
with pytest.raises(ApplicationError) as exc_info:
_calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False)
assert exc_info.value.type == type(exc).__name__
- assert exc_info.value.next_retry_delay == timedelta(seconds=CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS)
+ assert exc_info.value.next_retry_delay == timedelta(seconds=47.5)
mock_capture.assert_not_called()
recalc.refresh_from_db()
assert recalc.metric_errors == {}
@@ -1588,7 +1591,7 @@ class TestRecalculationAnalytics(BaseTest):
"backpressure",
ConcurrencyLimitExceeded("quota"),
"rate_limited",
- 60,
+ 47.5,
"The query was deferred because the cluster is at capacity.",
),
(
@@ -1605,7 +1608,7 @@ class TestRecalculationAnalytics(BaseTest):
name: str,
exc: Exception,
expected_error_type: str,
- expected_delay_seconds: int,
+ expected_delay_seconds: float,
expected_message: str,
):
# A non-final attempt re-raises for Temporal to retry. It emits 'experiment metric retry' (not
@@ -1616,9 +1619,10 @@ class TestRecalculationAnalytics(BaseTest):
recalc = self._recalc(exp, metric_uuids=["m1"])
with _record_captures() as captured:
- with patch(
- "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"
- ) as mock_runner:
+ with (
+ patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner,
+ patch("products.experiments.backend.temporal.recalculation_logic.random.uniform", return_value=47.5),
+ ):
mock_runner.return_value.run.side_effect = exc
with pytest.raises((type(exc), ApplicationError)):
_calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=2)