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.

feat(experiments): gate the metric reload rate limit behind a flag (#113949)

Rodrigo Ilorod570dfe7c507
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 90bdbed4e7ed..466d172e4ce1 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -351,6 +351,7 @@ export const FEATURE_FLAGS = {
EXPERIMENTS_FREEZE_EXPOSURE_AA_TEST: 'experiments-freeze-exposure-aa-test', // owner: @mp-hog #team-experiments multivariate=control,test, dogfood A/A used to validate the freeze-exposure lifecycle action
EXPERIMENTS_LEGACY_DEPRECATION_NOTICE: 'experiments-legacy-deprecation-notice', // owner: @andehen #team-experiments, shows the legacy experiments deprecation banner
EXPERIMENTS_METRICS_RECALCULATION: 'experiments-metrics-recalculation', // owner: @rodrigoi #team-experiments
+ EXPERIMENTS_RECALCULATION_RATE_LIMIT: 'experiment-metric-recalculation-rate-limit', // owner: @rodrigoi #team-experiments, five-minute window between manual metric reloads
EXPERIMENTS_SHOW_SQL: 'experiments-show-sql', // owner: @jurajmajerik #team-experiments
EXPERIMENTS_SYNC_QUERIES: 'experiments-sync-queries', // owner: @andehen #team-experiments
FEATURE_FLAG_CLEANUP_ASSESSMENT: 'feature-flag-cleanup-assessment', // owner: #team-feature-flags, kill switch for the flag-page "Review cleanup with AI" action
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
index 35fa12a36cff..8f5191507760 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -838,42 +838,29 @@ describe('experimentMetricsLogic', () => {
{
name: 'blocks a manual reload inside the window',
latest: completedRecalculation,
- trigger: 'manual',
minutesAgo: 2,
blocked: true,
},
{
name: 'allows a manual reload after the window',
latest: completedRecalculation,
- trigger: 'manual',
minutesAgo: 6,
blocked: false,
},
- {
- name: 'lets a heal through inside the window',
- latest: completedRecalculation,
- trigger: 'heal_latest_run',
- minutesAgo: 2,
- blocked: true,
- },
{
// The fallback is not a run: a fresh timeseries point must not block the first recalculation.
name: 'never blocks on a timeseries fallback',
latest: completeTimeseriesFallbackRecalculation,
- trigger: 'manual',
minutesAgo: 2,
blocked: false,
},
{
name: 'never blocks after a failed run',
latest: partialFailureRecalculation,
- trigger: 'manual',
minutesAgo: 2,
blocked: false,
},
- ] as const)('$name', async ({ latest, trigger, minutesAgo, blocked }) => {
- const posts = !(blocked && trigger === 'manual')
- const createMock = jest.fn(() => [201, pendingRecalculation])
+ ] as const)('$name', async ({ latest, minutesAgo, blocked }) => {
useMocks({
get: {
'/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
@@ -881,20 +868,13 @@ describe('experimentMetricsLogic', () => {
finishedMinutesAgo(latest, minutesAgo),
],
},
- post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
})
mountLogic()
await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
expect(logic.values.isManualRefreshBlocked).toBe(blocked)
-
- await expectLogic(logic, () => {
- logic.actions.triggerRecalculation(trigger)
- }).toFinishAllListeners()
- expect(createMock.mock.calls.length > 0).toBe(posts)
})
it('never blocks a reload in local development', async () => {
- const createMock = jest.fn(() => [201, pendingRecalculation])
useMocks({
get: {
'/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
@@ -902,7 +882,6 @@ describe('experimentMetricsLogic', () => {
finishedMinutesAgo(completedRecalculation, 2),
],
},
- post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
})
// The mount-time preflight load must land first, or it overwrites the dev preflight.
await expectLogic(preflightLogic).toDispatchActions(['loadPreflightSuccess'])
@@ -910,11 +889,6 @@ describe('experimentMetricsLogic', () => {
mountLogic()
await expectLogic(logic).toDispatchActions(['setCurrentRecalculation'])
expect(logic.values.isManualRefreshBlocked).toBe(false)
-
- await expectLogic(logic, () => {
- logic.actions.triggerRecalculation('manual')
- }).toFinishAllListeners()
- expect(createMock).toHaveBeenCalled()
})
it('syncs the window and informs the user when the backend answers 429', async () => {
@@ -951,6 +925,8 @@ describe('experimentMetricsLogic', () => {
expect(lemonToast.info).toHaveBeenCalledWith('Metrics were recalculated less than 5 minutes ago.')
expect(lemonToast.error).not.toHaveBeenCalled()
expect(logic.values.isRecalculating).toBe(false)
+ // The page's flags are off here, so this is what keeps the button honest after the 429.
+ expect(logic.values.backendEnforcesRefreshWindow).toBe(true)
})
it('unblocks the reload button when the window closes, without a new load', async () => {
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index ad478f8dba0e..69db793e0314 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -223,6 +223,7 @@ export interface experimentMetricsLogicValues {
receivedFeatureFlags: boolean // featureFlagLogic
isDev: boolean | undefined // preflightLogic
currentProjectId: number | null // projectLogic
+ backendEnforcesRefreshWindow: boolean
currentRecalculation: RecalculationPayload | null
isManualRefreshBlocked: boolean
isMetricRecalculating: (metricUuid: string | undefined) => boolean
@@ -264,6 +265,9 @@ export interface experimentMetricsLogicActions {
loadLatestRecalculation: () => {
value: true
}
+ markRefreshWindowEnforced: () => {
+ value: true
+ }
pollRecalculation: (recalculationId: string) => {
recalculationId: string
}
@@ -356,6 +360,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
}),
pollRecalculation: (recalculationId: string) => ({ recalculationId }),
recheckRefreshEligibility: true,
+ markRefreshWindowEnforced: true,
setPrimaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
setSecondaryMetricsResults: (results: CachedNewExperimentQueryResponse[]) => ({ results }),
setPrimaryMetricsResultsErrors: (errors: (unknown | null)[]) => ({ errors }),
@@ -382,6 +387,8 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
],
// Bumped when the manual refresh window closes, so isManualRefreshBlocked recomputes without new data.
refreshEligibilityTick: [0, { recheckRefreshEligibility: (state: number) => state + 1 }],
+ // A 429 proves the backend enforces the window, even when this page's cached flags still say otherwise.
+ backendEnforcesRefreshWindow: [false, { markRefreshWindowEnforced: () => true }],
queuedRerun: [
null as ExperimentMetricsRecalculationRequestTriggerEnumApi | null,
{
@@ -484,6 +491,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
],
isManualRefreshBlocked: [
(s) => [s.nextAllowedManualRefresh, s.refreshEligibilityTick, s.isDev],
+ // State for the reload button only. The backend is the gate: it answers 429 inside the window.
// Local development skips the window, as the backend does, so a developer can reload at will.
(nextAllowedManualRefresh: string | null, _tick: number, isDev: boolean | undefined): boolean =>
!isDev && !!nextAllowedManualRefresh && dayjs(nextAllowedManualRefresh).isAfter(dayjs()),
@@ -801,9 +809,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
if (!flagEnabled()) {
return
}
- if (trigger === 'manual' && values.isManualRefreshBlocked) {
- return
- }
/**
* Don't recalculate draft experiments; a config-change edit on a draft shouldn't kick off a
* run. Stopped experiments are allowed — they still need their final results computed.
@@ -947,6 +952,7 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
// Another tab or an agent used the refresh window first. Reload the latest run so the
// button picks up its completed_at and shows when the next refresh is possible.
lemonToast.info(error?.detail || 'Metrics were recalculated less than 5 minutes ago.')
+ actions.markRefreshWindowEnforced()
actions.loadLatestRecalculation()
return
}
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 8da3874144cc..9b88ceffa70b 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -27,6 +27,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.exceptions_capture import capture_exception
from posthog.models.scoping import get_current_team_id, team_scope
from posthog.models.user import User
+from posthog.ph_client import feature_enabled_or_false
from posthog.settings import CLICKHOUSE_CLUSTER
from posthog.temporal.common.client import sync_connect
@@ -57,6 +58,7 @@ _STALE_RECALC_THRESHOLD = timedelta(minutes=30)
# rate limiting manual reloads (including agents).
MIN_USER_RECALCULATION_INTERVAL = timedelta(minutes=5)
+RECALCULATION_RATE_LIMIT_FEATURE_FLAG = "experiment-metric-recalculation-rate-limit"
_RATE_LIMITED_TRIGGERS = frozenset(
{
ExperimentMetricsRecalculation.Trigger.MANUAL,
@@ -309,9 +311,21 @@ def _cancel_superseded_workflows(recalculation_ids: list[str]) -> None:
pass
-def _refresh_window_enforced() -> bool:
+def _refresh_window_enforced(experiment: Experiment) -> bool:
# Local development skips the window so a developer can reload at will. Tests keep it, because they assert it.
- return not settings.DEBUG or settings.TEST
+ if settings.DEBUG and not settings.TEST:
+ return False
+ organization_id = str(experiment.team.organization_id)
+ # Evaluated locally: this sits on the POST path, and a miss would otherwise block the request on a call
+ # to /flags. The flag has to target the organization id sent here, or it reads false for everyone.
+ return feature_enabled_or_false(
+ RECALCULATION_RATE_LIMIT_FEATURE_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
def request_recalculation(experiment: Experiment, user: User | None, trigger: str = "manual") -> dict:
@@ -320,7 +334,8 @@ def request_recalculation(experiment: Experiment, user: User | None, trigger: st
If an active (pending or in_progress) run already exists for this experiment, returns the existing run's
serialized payload with ``is_existing=True`` — the caller should NOT start a new workflow in that case.
A user-driven trigger inside ``MIN_USER_RECALCULATION_INTERVAL`` after the latest completed run finished
- raises ``RecalculationRateLimited``. Otherwise creates a fresh pending row.
+ raises ``RecalculationRateLimited`` when the organization has the rate-limit flag on. Otherwise creates a
+ fresh pending row.
"""
if not experiment.is_launched:
raise ValidationError("Cannot recalculate metrics for experiment that hasn't started")
@@ -351,7 +366,7 @@ def request_recalculation(experiment: Experiment, user: User | None, trigger: st
_recalculation_reuse_counter.inc()
return build_job_payload(existing, is_existing=True)
- if trigger in _RATE_LIMITED_TRIGGERS and _refresh_window_enforced():
+ if trigger in _RATE_LIMITED_TRIGGERS and _refresh_window_enforced(experiment):
# get the latest terminal run and check against the rate limiting rules
# if matched, increment counter and raise so the API answers 429 with Retry-After
latest = _terminal_recalculations(experiment).order_by("-created_at").first()
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.md
index 84fd3624ff36..c86c065f6551 100644
--- a/products/experiments/backend/temporal/ARCHITECTURE.md
+++ b/products/experiments/backend/temporal/ARCHITECTURE.md
@@ -110,7 +110,7 @@ Two safeguards on the POST endpoint:
- **Idempotent reuse.** If an active recalc (pending or in-progress) exists for this experiment and is younger than 30 minutes, the POST returns it instead of creating a new one. Frontend can click Reload twice and get the same `recalculation_id`.
- **Per-experiment lock.** The service runs inside `transaction.atomic()` with `Experiment.objects.select_for_update()` to serialize concurrent POSTs. Without this, two simultaneous clicks would both see no active row, both reach `.create()`, and the second would hit the per-experiment unique constraint and return HTTP 500.
-- **User refresh window.** A `manual` or `agent_mcp` POST within `MIN_USER_RECALCULATION_INTERVAL` (five minutes) after the latest completed run's `completed_at` gets a 429 with a `Retry-After` header (`RecalculationRateLimited`), so a client or an agent knows when the next run is allowed. The window measures from completion, not `query_to`, because a stopped experiment pins `query_to` to `end_date`. A failed latest run never anchors the window, and neither does a `timeseries_sync` run, which may lack metrics the daily workflow does not compute. System triggers (`cold_run`, `heal_latest_run`, `manual_retry`, config changes) are exempt. Local development (`DEBUG` on, outside tests) skips the window, and the frontend mirrors that through the `is_debug` preflight field.
+- **User refresh window.** A `manual` or `agent_mcp` POST within `MIN_USER_RECALCULATION_INTERVAL` (five minutes) after the latest completed run's `completed_at` gets a 429 with a `Retry-After` header (`RecalculationRateLimited`), so a client or an agent knows when the next run is allowed. The window measures from completion, not `query_to`, because a stopped experiment pins `query_to` to `end_date`. A failed latest run never anchors the window, and neither does a `timeseries_sync` run, which may lack metrics the daily workflow does not compute. System triggers (`cold_run`, `heal_latest_run`, `manual_retry`, config changes) are exempt. The `experiment-metric-recalculation-rate-limit` flag, targeted by organization, turns the window on; the backend evaluates it by organization id and the frontend reads the same flag to block the reload button. Local development (`DEBUG` on, outside tests) skips the window, and the frontend mirrors that through the `is_debug` preflight field.
### Activity-aware staleness
diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.py
index 07c74a7490e4..52d3e2a75d7d 100644
--- a/products/experiments/backend/test/test_metrics_recalculation_api.py
+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py
@@ -149,9 +149,10 @@ class TestMetricsRecalculationAPI(APIBaseTest):
assert second.json()["id"] == first.json()["id"]
assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1
+ @mock.patch("products.experiments.backend.recalculation.feature_enabled_or_false", return_value=True)
@mock.patch("products.experiments.backend.recalculation.sync_connect")
@mock.patch("products.experiments.backend.recalculation.asyncio.run")
- def test_post_manual_inside_refresh_window_returns_429_without_a_workflow(self, mock_run, mock_connect):
+ def test_post_manual_inside_refresh_window_returns_429_without_a_workflow(self, mock_run, mock_connect, _mock_flag):
exp = self._launched_experiment()
now = timezone.now()
ExperimentMetricsRecalculation.objects.create(
diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.py
index 4c5e516381a5..d9eeeb9886f1 100644
--- a/products/experiments/backend/test/test_recalculation_service.py
+++ b/products/experiments/backend/test/test_recalculation_service.py
@@ -116,6 +116,7 @@ class TestRecalculationService(BaseTest):
("manual_retry_inside_window_starts_new", "manual_retry", "completed", "manual", 2, True),
]
)
+ @patch("products.experiments.backend.recalculation.feature_enabled_or_false", return_value=True)
def test_request_recalculation_user_refresh_window(
self,
name: str,
@@ -124,6 +125,7 @@ class TestRecalculationService(BaseTest):
latest_trigger: str,
minutes_since_completed: int,
expects_new_run: bool,
+ _mock_flag,
):
exp = self._launched_experiment(flag_key=f"window-{name}")
now = timezone.now()
@@ -152,7 +154,8 @@ class TestRecalculationService(BaseTest):
assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1
@override_settings(DEBUG=True, TEST=False)
- def test_request_recalculation_skips_the_refresh_window_in_local_development(self):
+ @patch("products.experiments.backend.recalculation.feature_enabled_or_false", return_value=True)
+ def test_request_recalculation_skips_the_refresh_window_in_local_development(self, _mock_flag):
exp = self._launched_experiment(flag_key="window-debug")
ExperimentMetricsRecalculation.objects.create(
team=self.team,
@@ -168,6 +171,23 @@ class TestRecalculationService(BaseTest):
assert result["is_existing"] is False
assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 2
+ @patch("products.experiments.backend.recalculation.feature_enabled_or_false", return_value=False)
+ def test_request_recalculation_skips_the_refresh_window_when_the_flag_is_off(self, _mock_flag):
+ exp = self._launched_experiment(flag_key="window-flag-off")
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status="completed",
+ trigger="manual",
+ query_to=timezone.now() - timedelta(days=1),
+ completed_at=timezone.now() - timedelta(minutes=2),
+ )
+
+ result = request_recalculation(exp, self.user, "manual")
+
+ assert result["is_existing"] is False
+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 2
+
def test_request_recalculation_is_idempotent(self):
exp = self._launched_experiment()
first = request_recalculation(exp, self.user, "manual")
diff --git a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx
index 3083b91f5230..8c3014fc9205 100644
--- a/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx
+++ b/products/experiments/frontend/components/ExperimentMetaBar/ExperimentRefreshButton.tsx
@@ -5,6 +5,7 @@ import { LemonButton, lemonToast } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { experimentLogic, previousRefreshAnalytics } from 'scenes/experiments/experimentLogic'
@@ -65,11 +66,14 @@ function RecalculationRefreshButton({ experiment }: { experiment: Experiment }):
queuedRerun,
isManualRefreshBlocked,
nextAllowedManualRefresh,
+ backendEnforcesRefreshWindow,
} = useValues(metricsLogic)
const { triggerRecalculation } = useActions(metricsLogic)
const { currentRefresh } = useValues(experimentLogic)
const { reportExperimentMetricsRefreshed } = useActions(experimentLogic)
const { refreshExperimentResults } = useAsyncActions(experimentLogic)
+ // A page with stale flags learns about the window from a 429, so the backend signal counts too.
+ const showRefreshWindow = useFeatureFlag('EXPERIMENTS_RECALCULATION_RATE_LIMIT') || backendEnforcesRefreshWindow
return (
<RefreshButton
@@ -78,7 +82,7 @@ function RecalculationRefreshButton({ experiment }: { experiment: Experiment }):
progress={recalculationProgress}
queuedHint={queuedRerun ? 'Changes apply after the current recalculation finishes' : undefined}
blockedReason={
- isManualRefreshBlocked && nextAllowedManualRefresh
+ showRefreshWindow && isManualRefreshBlocked && nextAllowedManualRefresh
? `Next refresh possible ${dayjs(nextAllowedManualRefresh).fromNow()}`
: undefined
}