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): use a worker pool on the workflow to requeue retries (#66135)

Rodrigo Iloro4bc7587f5dd3
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.md
index f1f645900d8f..3074739c3d6f 100644
--- a/products/experiments/backend/temporal/ARCHITECTURE.md
+++ b/products/experiments/backend/temporal/ARCHITECTURE.md
@@ -46,7 +46,7 @@ sequenceDiagram
Worker->>Workflow: wrap execute (latency + finished counter)
Workflow->>Activity: discover all metrics, stamp query_to once
- Workflow->>Activity: per metric (fan-out, concurrency 10)
+ Workflow->>Activity: per metric (worker pool of 4, 1 attempt each, requeue on transient failure)
Worker->>Activity: wrap execute (latency + success/failure counters)
Activity->>Result: upsert recalc-fingerprinted row
Activity->>DB: merge metric_errors on failure
@@ -118,8 +118,19 @@ The split is intentional: Grafana tells you about the worker process, PostHog te
## Performance notes
-- **Concurrency cap of 4.** The workflow fans out per-metric calc activities under `asyncio.Semaphore(MAX_CONCURRENT_METRICS=4)`. Each activity runs one blocking ClickHouse query; without the cap, a 50-metric experiment would saturate the worker's connection pool and starve other work on the queue. The cap is 4 (not higher) because these offline queries share the org's `app:query:per-org` ClickHouse budget (default 20, halved/quartered under cluster load) with the org's live queries; staying at 4 keeps a single run under the budget even when it drops to 5, avoiding `ClickHouseAtCapacity` throttling.
-- **5-minute per-attempt budget.** `start_to_close_timeout=timedelta(minutes=5)` on the calc activity, with `RetryPolicy(maximum_attempts=5, initial_interval=5s, backoff_coefficient=2.0, maximum_interval=60s)`. The exponential backoff (5s → 10s → 20s → 40s, jittered by Temporal) absorbs transient `ClickHouseAtCapacity`/`ConcurrencyLimitExceeded` throttling so a metric that hits backpressure retries in a later, quieter load window instead of failing the run. We deliberately don't set a heartbeat timeout — the activity has no progress hooks inside the ClickHouse query, so the heartbeat couldn't fire mid-query anyway; `start_to_close_timeout` is the real per-attempt ceiling.
+- **Worker pool of 4, retries owned by the workflow.** The workflow runs `MAX_CONCURRENT_METRICS=4` worker coroutines that drain a shared requeue queue, rather than firing all metrics under a semaphore. The cap is 4 (not higher) because these offline queries share the org's `app:query:per-org` ClickHouse budget (default 20, halved/quartered under cluster load) with the org's live queries; staying at 4 keeps a single run under the budget even when it drops to 5, avoiding `ClickHouseAtCapacity` throttling.
+
+ Crucially, the calc activity runs with `RetryPolicy(maximum_attempts=1)`: the workflow owns retries, not Temporal. Why: a single `execute_activity(..., retry_policy=...)` await does not resolve until the whole retry chain finishes (Temporal handles backoff at the service level and the workflow stays suspended). With the old `asyncio.Semaphore` + `maximum_attempts=5`, a failing metric held its concurrency slot for the entire ~75s backoff chain (5s, 10s, 20s, 40s), starving healthy metrics queued behind it and wrecking perceived load time when several metrics failed. Note this was a _workflow-level_ semaphore problem; Temporal frees the _worker_ activity slot during backoff, so the starvation was self-inflicted by the semaphore, not by Temporal's concurrency.
+
+ Now: each worker pulls a metric, runs one attempt, and frees its slot the moment that attempt returns or raises. A transient failure (the activity raises) requeues the metric at the **back** of the queue with a `not_before` backoff delay, so a waiting metric runs before the failed one's next attempt. A permanent failure (`StatisticError`/`ZeroDivisionError`, returned with `success=False`, never raised) is terminal on the first trip. A metric is marked failed only after `MAX_METRIC_ATTEMPTS=3` trips. This is the standard Temporal "start N, launch more as each completes" pattern (the `splitmerge-selector` shape), with requeue-on-failure layered on top.
+
+ The `_backoff` helper computes `5s * 2^(attempts-1)` capped at 60s (5s, 10s, 20s, 40s, 60s, ...). At the current `MAX_METRIC_ATTEMPTS=3` only the first two legs are ever reached: a metric requeues after attempt 1 (5s) and after attempt 2 (10s), then attempt 3 is final and never requeues. The formula stays generic so raising the cap extends the schedule without code changes.
+
+ The loop is deterministic for replay: all time comes from `temporalio.workflow.now()` and waits use `temporalio.workflow.sleep()`; workers block on `wait_condition` rather than busy-spinning; and the single-threaded asyncio model guarantees no interleaving between dequeue and the in-flight counter bump.
+
+- **`is_final_attempt` is passed by the workflow.** Because the activity runs `maximum_attempts=1`, it can't infer "last try" from `activity.info().attempt` (always 1). The workflow's requeue loop knows the real attempt count and passes `is_final_attempt` as an activity argument. 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.
+
+- **5-minute per-attempt budget.** `start_to_close_timeout=timedelta(minutes=5)` on the calc activity is the real per-attempt ceiling. We deliberately don't set a heartbeat timeout: the activity has no progress hooks inside the ClickHouse query, so the heartbeat couldn't fire mid-query anyway.
- **No saved-metric snapshot.** Each calc activity that processes a saved/shared metric re-queries the M2M through-model to resolve the metric definition. For a 5–10 metric experiment this is fine; for larger experiments the per-call query starts to add up. Tracked as a deferred optimization (snapshot resolved metric dicts on the recalc row at discovery time).
## What this doc doesn't cover
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index 27fe12766d40..0cd56a376a3e 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -13,9 +13,10 @@ ALL_OUTCOMES = (OUTCOME_PASS, OUTCOME_DIVERGENCE, OUTCOME_PATH_FLIP, OUTCOME_ERR
# Cap CanaryMetricResult.detail so a pathological error message can't bloat the Temporal payload.
MAX_CANARY_DETAIL_LENGTH = 1000
-# Max attempts for the per-metric recalculation activity. Shared between the workflow's RetryPolicy and the
-# activity so the activity knows when it's on its final attempt.
-MAX_METRIC_ATTEMPTS = 5
+# Max attempts per metric before it's marked failed. The workflow's requeue loop owns retries (the activity
+# runs with maximum_attempts=1), so this caps how many times a transient failure is requeued. Kept low because
+# each extra attempt adds backoff (5s, 10s, 20s, ...) to the tail of a fully-failing run.
+MAX_METRIC_ATTEMPTS = 3
@dataclasses.dataclass
diff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.py
index bbc74dadf98e..95f49a1d34b2 100644
--- a/products/experiments/backend/temporal/recalculation_activities.py
+++ b/products/experiments/backend/temporal/recalculation_activities.py
@@ -8,7 +8,6 @@ and lets the logic be unit-tested without the activity decorator.
import temporalio.activity
from products.experiments.backend.temporal.models import (
- MAX_METRIC_ATTEMPTS,
ExperimentMetricToRecalculate,
MetricRecalculationResult,
RecalculationProgressUpdate,
@@ -42,6 +41,7 @@ async def calculate_experiment_metric_for_recalculation(
recalculation_id: str,
query_to: str,
metric_type: str = "primary",
+ is_final_attempt: bool = True,
) -> MetricRecalculationResult:
"""Calculate one metric, write its recalc-fingerprinted result to ExperimentMetricResult, and fold the
progress update (counter + error) into the same job atomically. query_to is the run's shared data-window end.
@@ -49,10 +49,12 @@ async def calculate_experiment_metric_for_recalculation(
metric_type is the primary/secondary classification carried from discovery; it's threaded into the per-metric
PostHog event so the capture path doesn't have to re-query the saved-metric M2M to resolve it. Defaults to
"primary" so existing call sites and tests that don't pass it remain valid.
+
+ is_final_attempt is owned by the workflow's requeue loop (the activity runs with maximum_attempts=1, so it
+ can't infer this from activity.info().attempt). On the final attempt a transient failure is persisted rather
+ than re-raised silently, so the row reflects the real outcome once the workflow stops retrying. Defaults to
+ True so callers that don't pass it persist failures eagerly.
"""
- # Temporal attempt is 1-based. On the final attempt, a transient failure must be persisted rather than
- # re-raised, so the row reflects the real outcome once retries are exhausted.
- is_final_attempt = temporalio.activity.info().attempt >= MAX_METRIC_ATTEMPTS
return await _calculate_experiment_metric_for_recalculation_sync(
experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt
)
diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.py
index 8ae4299e02e9..baf2fefe60db 100644
--- a/products/experiments/backend/temporal/recalculation_workflow.py
+++ b/products/experiments/backend/temporal/recalculation_workflow.py
@@ -1,5 +1,7 @@
import asyncio
-from datetime import timedelta
+import dataclasses
+from collections import deque
+from datetime import datetime, timedelta
import temporalio.workflow
from temporalio.common import RetryPolicy
@@ -11,6 +13,7 @@ with temporalio.workflow.unsafe.imports_passed_through():
from products.experiments.backend.temporal.models import (
MAX_METRIC_ATTEMPTS,
ExperimentMetricsRecalculationWorkflowInputs,
+ ExperimentMetricToRecalculate,
RecalculationProgressUpdate,
)
from products.experiments.backend.temporal.recalculation_activities import (
@@ -30,10 +33,11 @@ MAX_CONCURRENT_METRICS = 4
class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
"""Recalculate all metrics for an experiment on demand.
- Each run discovers all metrics, marks the job in_progress (which also pins the single data-window end), fans
- out one calc activity per metric with bounded concurrency, then finalizes the job status. Per-metric progress
- counters and errors are folded into the calc activity itself, so the workflow only writes progress at start
- and finish.
+ Each run discovers all metrics, marks the job in_progress (which also pins the single data-window end), then
+ runs a pool of MAX_CONCURRENT_METRICS workers draining a requeue queue (one activity attempt at a time;
+ transient failures requeue with backoff, the workflow owns retries), and finalizes the job status. Per-metric
+ progress counters and errors are folded into the calc activity itself, so the workflow only writes progress
+ at start and finish.
"""
@staticmethod
@@ -105,32 +109,99 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
temporalio.workflow.logger.info(f"running recalc {recalculation_id} with {len(metrics)} metrics")
- semaphore = asyncio.Semaphore(MAX_CONCURRENT_METRICS)
-
- async def _run_metric(metric):
- async with semaphore:
- return await temporalio.workflow.execute_activity(
- calculate_experiment_metric_for_recalculation,
- args=[metric.experiment_id, metric.metric_uuid, recalculation_id, query_to, metric.metric_type],
- # No heartbeat: the activity's only long-running step is one blocking ClickHouse query
- # with no progress hooks, so start_to_close_timeout is the real per-attempt ceiling.
- start_to_close_timeout=timedelta(minutes=5),
- # Throttle errors (ClickHouseAtCapacity / ConcurrencyLimitExceeded) are transient
- # backpressure: spread retries with exponential backoff so each attempt lands in a
- # different load window. Temporal jitters each interval automatically, so concurrent
- # metrics don't re-stampede in lockstep. Permanent failures don't reach here
- # (StatisticError/ZeroDivisionError are recorded and returned, never raised).
- retry_policy=RetryPolicy(
- maximum_attempts=MAX_METRIC_ATTEMPTS,
- initial_interval=timedelta(seconds=5),
- backoff_coefficient=2.0,
- maximum_interval=timedelta(seconds=60),
- ),
- )
-
- results = await asyncio.gather(*[_run_metric(m) for m in metrics], return_exceptions=True)
- succeeded = sum(1 for r in results if not isinstance(r, BaseException) and r.success)
- failed = len(metrics) - succeeded
+ # Worker pool over a requeue queue. Retries are owned by the workflow, not the activity's retry policy,
+ # so a failing attempt frees its concurrency slot the moment it fails instead of holding it through the
+ # whole backoff chain (which would starve healthy metrics behind it). Each activity runs with
+ # maximum_attempts=1; on a transient failure (the activity raises) the metric is requeued at the BACK
+ # with a not-before delay, so other metrics run before its next attempt. A metric is permanently failed
+ # only after MAX_METRIC_ATTEMPTS trips. Permanent failures (StatisticError/ZeroDivisionError) are
+ # returned with success=False, not raised, so they terminate on the first trip.
+ #
+ # Determinism: all time comes from temporalio.workflow.now() (recorded by Temporal, stable on replay)
+ # and waits use temporalio.workflow.sleep(); no wall-clock, no Math.random, no host state.
+ @dataclasses.dataclass
+ class _QueuedMetric:
+ metric: ExperimentMetricToRecalculate
+ attempts: int # attempts already made (0 on first enqueue)
+ not_before: datetime # earliest workflow time this item may run
+
+ def _backoff(attempts: int) -> timedelta:
+ # Same schedule the old activity retry policy used: 5s, 10s, 20s, 40s, capped at 60s.
+ return timedelta(seconds=min(5.0 * (2.0 ** (attempts - 1)), 60.0))
+
+ start_now = temporalio.workflow.now()
+ queue: deque[_QueuedMetric] = deque(_QueuedMetric(metric=m, attempts=0, not_before=start_now) for m in metrics)
+ succeeded = 0
+ failed = 0
+ in_flight = 0
+
+ # Re-evaluated by Temporal until true: either an item is queued again (a sibling requeued a retry) or
+ # all in-flight work has drained (so this worker can exit). Defined once, not per loop iteration.
+ def _queue_changed() -> bool:
+ return bool(queue) or in_flight == 0
+
+ async def _worker() -> None:
+ nonlocal succeeded, failed, in_flight
+ while queue or in_flight:
+ if not queue:
+ # Work is still running in a sibling worker but nothing is runnable here yet. Wait on the
+ # in-flight work rather than busy-spin; it will requeue or finish, then re-check.
+ await temporalio.workflow.wait_condition(_queue_changed)
+ continue
+
+ item = queue.popleft()
+ wait = (item.not_before - temporalio.workflow.now()).total_seconds()
+ if wait > 0:
+ # Not due yet. Requeue and, if every queued item is also not yet due, sleep until this one
+ # is (bounded by its own not_before) so we neither busy-spin nor oversleep past a due item.
+ queue.append(item)
+ if all((q.not_before - temporalio.workflow.now()).total_seconds() > 0 for q in queue):
+ await temporalio.workflow.sleep(timedelta(seconds=wait))
+ continue
+
+ attempt_number = item.attempts + 1
+ is_final_attempt = attempt_number >= MAX_METRIC_ATTEMPTS
+ in_flight += 1
+ try:
+ result = await temporalio.workflow.execute_activity(
+ calculate_experiment_metric_for_recalculation,
+ args=[
+ item.metric.experiment_id,
+ item.metric.metric_uuid,
+ recalculation_id,
+ query_to,
+ item.metric.metric_type,
+ is_final_attempt,
+ ],
+ # No heartbeat: the activity's only long-running step is one blocking ClickHouse query
+ # with no progress hooks, so start_to_close_timeout is the real per-attempt ceiling.
+ start_to_close_timeout=timedelta(minutes=5),
+ # One attempt per invocation; the workflow owns requeue + backoff (see block comment).
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ except Exception:
+ # Transient failure (the activity raised). Requeue at the back with a backoff delay unless
+ # this was the final attempt — in which case the activity already persisted the failure.
+ if is_final_attempt:
+ failed += 1
+ else:
+ queue.append(
+ _QueuedMetric(
+ metric=item.metric,
+ attempts=attempt_number,
+ not_before=temporalio.workflow.now() + _backoff(attempt_number),
+ )
+ )
+ else:
+ # Returned a result: success, or a permanent failure recorded with success=False.
+ if result.success:
+ succeeded += 1
+ else:
+ failed += 1
+ finally:
+ in_flight -= 1
+
+ await asyncio.gather(*[_worker() for _ in range(MAX_CONCURRENT_METRICS)])
# Any failure marks the run as "failed"; the succeeded/failed counts carry the partial-vs-total nuance
# for consumers that need it (the UI shows "N succeeded, M failed" alongside the status). A status-only
diff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.py
index 503c6505fa69..38802a8728cc 100644
--- a/products/experiments/backend/temporal/test_recalculation_workflow.py
+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py
@@ -12,6 +12,7 @@ from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from products.experiments.backend.temporal.models import (
+ MAX_METRIC_ATTEMPTS,
ExperimentMetricsRecalculationWorkflowInputs,
ExperimentMetricToRecalculate,
MetricRecalculationResult,
@@ -52,6 +53,7 @@ def _make_mock_activities(
recalculation_id: str,
query_to: str,
metric_type: str = "primary",
+ is_final_attempt: bool = True,
) -> MetricRecalculationResult:
calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to, metric_type))
return metric_results.get(metric_uuid, MetricRecalculationResult(metric_uuid=metric_uuid, success=True))
@@ -124,6 +126,79 @@ class TestExperimentMetricsRecalculationWorkflow:
assert progress_updates[-1].status == expected_final_status
assert progress_updates[-1].mark_completed is True
+ async def test_transient_failure_is_requeued_and_retried_until_it_succeeds(self):
+ # A raised activity is a transient failure: the workflow requeues the metric and retries it, freeing
+ # the slot in between. m2 raises on its first two attempts, then succeeds on the third; m1 succeeds
+ # immediately. The run ends fully succeeded, and m2 was invoked three times.
+ metrics = [_metric("m1"), _metric("m2")]
+ attempts: dict[str, int] = {}
+
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return metrics
+
+ @activity.defn(name="update_recalculation_progress")
+ async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:
+ return _START_QUERY_TO if update.mark_started else None
+
+ @activity.defn(name="calculate_experiment_metric_for_recalculation")
+ async def mock_calculate(
+ experiment_id: int,
+ metric_uuid: str,
+ recalculation_id: str,
+ query_to: str,
+ metric_type: str = "primary",
+ is_final_attempt: bool = True,
+ ) -> MetricRecalculationResult:
+ attempts[metric_uuid] = attempts.get(metric_uuid, 0) + 1
+ if metric_uuid == "m2" and attempts[metric_uuid] <= 2:
+ raise RuntimeError("transient blip")
+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
+
+ result = await _run_workflow([mock_discover, mock_update_progress, mock_calculate])
+
+ assert result == {"total": 2, "succeeded": 2, "failed": 0}
+ assert attempts["m1"] == 1
+ assert attempts["m2"] == 3
+
+ async def test_transient_failure_is_marked_failed_after_max_attempts(self):
+ # A metric that raises on every attempt is requeued until MAX_METRIC_ATTEMPTS is exhausted, then
+ # counted as failed (the final attempt persists the failure inside the real activity).
+ metrics = [_metric("m1")]
+ attempts: dict[str, int] = {}
+ # is_final_attempt is the only signal that tells the real activity to persist the failure. Track it
+ # per call so we can assert the workflow flips it to True exactly on the last attempt; otherwise a
+ # run would be counted failed here while the metric row stayed in its loading state forever.
+ is_final_attempt_log: list[bool] = []
+
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return metrics
+
+ @activity.defn(name="update_recalculation_progress")
+ async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:
+ return _START_QUERY_TO if update.mark_started else None
+
+ @activity.defn(name="calculate_experiment_metric_for_recalculation")
+ async def mock_calculate(
+ experiment_id: int,
+ metric_uuid: str,
+ recalculation_id: str,
+ query_to: str,
+ metric_type: str = "primary",
+ is_final_attempt: bool = True,
+ ) -> MetricRecalculationResult:
+ attempts[metric_uuid] = attempts.get(metric_uuid, 0) + 1
+ is_final_attempt_log.append(is_final_attempt)
+ raise RuntimeError("always fails")
+
+ result = await _run_workflow([mock_discover, mock_update_progress, mock_calculate])
+
+ assert result == {"total": 1, "succeeded": 0, "failed": 1}
+ assert attempts["m1"] == MAX_METRIC_ATTEMPTS
+ # Only the final attempt is flagged final; earlier attempts must not be, or they'd persist early.
+ assert is_final_attempt_log == [False] * (MAX_METRIC_ATTEMPTS - 1) + [True]
+
@parameterized.expand(
[
# name, metrics — exercise both the empty-metrics path and the fan-out path.